My named query looks like this, thanks to here.
#NamedQuery(
name="Cat.favourites",
query="select c
from Usercat as uc
inner join uc.cat as c
where uc.isFavourtie = true
and uc.user = :user")
And the call to implement looks like this :
Session session = sessionFactory.getCurrentSession();
Query query = session.getNamedQuery("Cat.favourites");
query.setEntity("user", myCurrentUser);
return query.list();
What would be the equivalent criteria query that returns a list of cats ?
With JPA 2.0 Criteria:
(This is one of the many ways you can achieve this using JPA 2.0 Criteria api)
final CriteriaQuery<Cat> cq = getCriteriaBuilder().createQuery(Cat.class);
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final Root<Usercat> uc= cq.from(Usercat.class);
cq.select(uc.get("cat");
Predicate p = cb.equal(uc.get("favourtie", true);
p = cb.and(p, cb.equal(uc.get("user"), user));
cq.where(p);
final TypedQuery<Cat> typedQuery = entityManager.createQuery(cq);
return typedQuery.getResultList();
Related
I try do the folow JPQL clause to criteria Api
SELECT new ProductDTOOut(p.id,p.name,
(SELECT pr.price FROM Price pr WHERE pr.product.id = p.id and pr.company.id = :companyId) )
FROM Product p
without success,
how can I do it ?
tnx advanced
I know solve my problem follow answer :
CriteriaBuilder cb = manager.getCriteriaBuilder();
CriteriaQuery<ProductDTOOut> criteriaQuery = cb.createQuery(ProductDTOOut.class);
// create query
Root<Product> rootFrom = criteriaQuery.from(Product.class);
// creating subquery
Subquery<Double> subquery = criteriaQuery.subquery(Double.class);
Root<Price> subqueryRoot = subquery.from(Price.class);
subquery.select(subqueryRoot.get(Price_.PRICE));
subquery.where(
cb.equal(rootFrom.get(Product_.ID),
subqueryRoot.get(Price_.PRODUCT).get(Product_.ID)),
cb.equal(
subqueryRoot.get(Price_.COMPANY).get(Company_.ID), companyId));
criteriaQuery.select(cb.construct(ProductDTOOut.class,
rootFrom.get(Product_.ID),
rootFrom.get(Product_.NAME),
subquery // here put subquery
));
TypedQuery<ProductDTOOut> query = manager.createQuery(criteriaQuery);
return query.getResultList();
I hope that I helped someone with the same question.
please help me out writing criteria builder for this query
SELECT *
FROM XYZ
WHERE date_v < "2020/01" AND
id NOT IN (SELECT id FROM XYZ WHERE date_v = '2020/01')
i have looked at using subqueries in jpa criteria api but i am unable to figure it
I have tried using subquery and joins but it throwing different error after all i get to know that i need to get more clarity about query criteria usages. any help much appreciated
You have to create XyzEntity with Long id and LocalDate date_v fields.
// query
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<XyzEntity> query = cb.createQuery(XyzEntity.class);
Root<XyzEntity> root = query.from(XyzEntity.class);
LocalDate date = LocalDate.of(2020, 1, 1);
// subquery
Subquery<Long> subQuery = query.subquery(Long.class);
Root<XyzEntity> subRoot = subQuery.from(XyzEntity.class);
Predicate idSubPredicate = cb.equal(root.get("id"), subRoot.get("id"));
Predicate dateSubPredicate = cb.equal(subRoot.get("date_v"), date);
subQuery.select(subRoot.get("id")).where(idSubPredicate, dateSubPredicate);
// query predicates
Predicate datePredicate = cb.greaterThan(root.get("date_v"), date);
Predicate notExistsPredicate = cb.exists(subQuery).not();
// query result
query.select(root).where(datePredicate, notExistsPredicate);
List<XyzEntity> result = entityManager.createQuery(query).getResultList();
I have mentioned the corrections in comments for the answer but I feel providing full solution seems good and helps others:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Entity> query = cb.createQuery(Entity.class);
Root<Entity> root = query.from(Entity.class);
// subquery
Subquery<Long> subQuery = query.subquery(Long.class);
Root<Entity> subRoot = subQuery.from(Entity.class);
Predicate subPredicate = cb.equal(subRoot.get("date_v"), dateValue);
subQuery.select(subRoot.get("id")).where(subPredicate);
// query predicates
Predicate datePredicate = cb.lessThan(root.get("date_v"), dateValue);
Predicate notExistsPredicate = root.get("id").in(subQuery).not();
// query result
query.select(root).where(datePredicate, notExistsPredicate);
Query d = entityManager.createQuery(query);
List<Entity> resultList = d.getResultList()
I am using Spring boot JPA to below execute below query
select DELTA_TYPE,OPERATION_ID,COUNT(*) from ACTIVE_DISCREPANCIES ad group by DELTA_TYPE,OPERATION_ID
DELTA_TYPE,OPERATION_ID, etc may come from external system, in repository class I tried to execute native query
#Query(value="select OPERATION_ID,DELTA_TYPE,count(*) from ACTIVE_DISCREPANCIES ad group by ?1",nativeQuery = true)
public List<Object[]> groupByQuery(#Param("reconType") String recGroupColumns);
where recGroupColumns="DELTA_TYPE,OPERATION_ID" but didnt work as #param will split ','
Second option for me was criteria query
public List<Object[]> getReconGroupList() {
String recGroupColumns = "OPERATION_ID,DELTA_TYPE";
String[] arrStr = recGroupColumns.split(",");
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]> query = criteriaBuilder.createQuery(Object[].class);
Root<ActiveDiscrepancies> adr = query.from(ActiveDiscrepancies.class);
query.groupBy(adr.get("operationId"), adr.get("deltaType"));
// query.groupBy(adr.get("deltaType"));
query.multiselect(adr.get("operationId"), adr.get("deltaType"), criteriaBuilder.count(adr));
TypedQuery<Object[]> typedQuery = entityManager.createQuery(query);
List<Object[]> resultList = typedQuery.getResultList();
return resultList;
}
Here how can I pass groupBy and multiselect dynamically?
Using projections we can solve this scenario, below is the code
Criteria criteria = getSession().createCriteria(ActiveDiscrepancies.class);
ProjectionList projectionList = Projections.projectionList();
for(String str : colList) {
projectionList.add(Projections.groupProperty(str));
}
projectionList.add(Projections.rowCount());
criteria.setProjection(projectionList);
List results = criteria.list();
getSession().close();
I have an entity called User, which has the following relationship to an entity called Company:
#Entity
public class User {
...
#ManyToOne
#JoinColumn(name="COMPANY_ID",referencedColumnName="ID")
private Company company = null;
...
}
And on my database, I have a User table with a "COMPANY_ID" column. How can I create a JPA criteria query using this field?
Using a criteria builder, I've tried the following expressions without success:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(User.class);
Root mockEntityRoot = cq.from(User.class);
//cq.where(cb.equal(mockEntityRoot.get("company"), 2));
//cq.where(cb.equal(mockEntityRoot.get("COMPANY_ID"), 12));
cq.where(cb.equal(mockEntityRoot.get("company.id"), 8));
entityManager.createQuery(cq).getResultList();
But I got the following error: "The attribute [company.id] from the managed type User is not present."
Thanks in advance.
I think you need an explicit join.
Notice I am using Criteria's metamodel.
This is a snippet I have, it's not the same thing as yours but you can have an idea
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Site> q = cb.createQuery(Site.class);
Root<Site> e = q.from(Site.class);
Join<Site,SiteType> siteType = e.join(Site_.siteType);
Predicate predicate = cb.conjunction();
Predicate p1 = cb.equal(siteType.get(SiteType_.id), selectedSiteType.getId());
Predicate p2 = cb.equal(e.get(Site_.markedAsDeleted), false);
predicate = cb.and(p1,p2);
q.where(predicate);
q.select(e);
TypedQuery<Site> tq = entityManager.createQuery(q);
List<Site> all = tq.getResultList();
return all;
When using the JPA Criteria API, what is the advantage of using a ParameterExpression over a variable directly? E.g. when I wish to search for a customer by name in a String variable, I could write something like
private List<Customer> findCustomer(String name) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Customer> criteriaQuery = cb.createQuery(Customer.class);
Root<Customer> customer = criteriaQuery.from(Customer.class);
criteriaQuery.select(customer).where(cb.equal(customer.get("name"), name));
return em.createQuery(criteriaQuery).getResultList();
}
With parameters this becomes:
private List<Customer> findCustomerWithParam(String name) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Customer> criteriaQuery = cb.createQuery(Customer.class);
Root<Customer> customer = criteriaQuery.from(Customer.class);
ParameterExpression<String> nameParameter = cb.parameter(String.class, "name");
criteriaQuery.select(customer).where(cb.equal(customer.get("name"), nameParameter));
return em.createQuery(criteriaQuery).setParameter("name", name).getResultList();
}
For conciseness I would prefer the first way, especially when the query gets longer with optional parameters. Are there any disadvantages of using parameters like this, like SQL injection?
you can use ParameterExpression like this:
assume that you have some input filter, an example could be this:
in your query you have to check the value of a fiscal Code.
let's start:
first of all create criteriaQuery and criteriaBuilder and root
CriteriaBuilder cb = _em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<RootEntity> soggettoRoot = cq.from(RootEntity.class);
1) inizialize a predicateList(use for where clause) and a paramList(use for param)
Map<ParameterExpression,String> paramList = new HashMap();
List<Predicate> predicateList = new ArrayList<>();
2 )check if the input is null and create predicateList and param
if( input.getFilterCF() != null){
//create ParameterExpression
ParameterExpression<String> cf = cb.parameter(String.class);
//if like clause
predicateList.add(cb.like(root.<String>get("cf"), cf));
paramList.put(cf , input.getFilterCF() + "%");
//if equals clause
//predicateList.add(cb.equal(root.get("cf"), cf));
//paramList.put(cf,input.getFilterCF()());
}
3) create the where clause
cq.where(cb.and(predicateList.toArray(new Predicate[predicateList.size()])));
TypedQuery<Tuple> q = _em.createQuery(cq);
4) set param value
for(Map.Entry<ParameterExpression,String> entry : paramList.entrySet())
{
q.setParameter(entry.getKey(), entry.getValue());
}
When using a parameter, likely (dependent on JPA implementation, datastore in use, and JDBC driver) the SQL will be optimised to a JDBC parameter so if you execute the same thing with a different value of the parameter it uses the same JDBC statement.
SQL injection is always down to the developer as to whether they validate some user input that is being used as a parameter.