ORDER BY using Criteria API - java

When I write a HQL query
Query q = session.createQuery("SELECT cat from Cat as cat ORDER BY cat.mother.kind.value");
return q.list();
Everything is fine. However, when I write a Criteria
Criteria c = session.createCriteria(Cat.class);
c.addOrder(Order.asc("mother.kind.value"));
return c.list();
I get an exception org.hibernate.QueryException: could not resolve property: kind.value of: my.sample.data.entities.Cat
If I want to use Criteria and Order, how should I express my "order by"?

You need to create an alias for the mother.kind. You do this like so.
Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();

This is what you have to do since sess.createCriteria is deprecated:
CriteriaBuilder builder = getSession().getCriteriaBuilder();
CriteriaQuery<User> q = builder.createQuery(User.class);
Root<User> usr = q.from(User.class);
ParameterExpression<String> p = builder.parameter(String.class);
q.select(usr).where(builder.like(usr.get("name"),p))
.orderBy(builder.asc(usr.get("name")));
TypedQuery<User> query = getSession().createQuery(q);
query.setParameter(p, "%" + Main.filterName + "%");
List<User> list = query.getResultList();

It's hard to know for sure without seeing the mappings (see #Juha's comment), but I think you want something like the following:
Criteria c = session.createCriteria(Cat.class);
Criteria c2 = c.createCriteria("mother");
Criteria c3 = c2.createCriteria("kind");
c3.addOrder(Order.asc("value"));
return c.list();

You can add join type as well:
Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);

For Hibernate 5.2 and above, use CriteriaBuilder as follows
CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<Cat> query = builder.createQuery(Cat.class);
Root<Cat> rootCat = query.from(Cat.class);
Join<Cat,Mother> joinMother = rootCat.join("mother"); // <-attribute name
Join<Mother,Kind> joinMotherKind = joinMother.join("kind");
query.select(rootCat).orderBy(builder.asc(joinMotherKind.get("value")));
Query<Cat> q = sessionFactory.getCurrentSession().createQuery(query);
List<Cat> cats = q.getResultList();

Related

Problem with translating SQL 'IN' subquery into a JPA Criteria Query

I'm trying to translate this SQL query into a JPA Criteria Query:
select distinct student0_.name
from vnic03.student student0_
where (exists(select teacher0_.social_number
from vnic03.teacher teacher0_
where teacher0.social_number = ?
and teacher0_.school_id in (select school0_.id
from vnic03.school school0_
where school0_.student_id = student0_.id)))
These are the tables (I have simplified and renamed them for posting them here, in reallity they have several million entries):
Right now I have following code:
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<String> searchQuery = criteriaBuilder.createQuery(String.class);
Root<Student> root = searchQuery.from(Student.class);
List<Predicate> restrictions = new ArrayList<>();
Subquery<Teacher> subQuery = searchQuery.subquery(Teacher.class);
Root<Teacher> fromSchoolSubQuery = subQuery.from(Teacher.class);
List<Predicate> subRestrictions = new ArrayList<>();
Subquery<School> subQuery2 = searchQuery.subquery(School.class);
Root<School> fromSchoolSubSubQuery = subQuery2.from(School.class);
List<Predicate> subSubRestrictions = new ArrayList<>();
subRestrictions.add(criteriaBuilder.equal(fromSchoolSubQuery.get(Social_number), userInput));
subRestrictions.add(criteriaBuilder.equal(fromSchoolSubQuery.get(School_ID), subQuery2.select(fromSchoolSubSubQuery.get(School_ID)).where(criteriaBuilder.equal(fromSchoolSubSubQuery.get(Student_ID), root.get(student_ID)))));
restrictions.add(criteriaBuilder.exists(subQuery.select(
fromSchoolSubQuery.get(Social_number)).where(
subRestrictions.toArray(new Predicate[0]))));
searchQuery.distinct(true)
.select(root.get(name))
.where( restrictions.toArray(new Predicate[restrictions.size()]) );
TypedQuery<String> query = em.createQuery(searchQuery)
List<String> nameList = query.getResultList();
But this translates into:
select distinct student0_.name
from vnic03.student student0_
where (exists(select teacher0_.social_number
from vnic03.teacher teacher0_
where teacher0.social_number = ?
and teacher0_.school_id = (select school0_.id
from vnic03.school school0_
where school0_.student_id = student0_.id)))
So I just need to replace the = by in in the last and part. I found in other SO questions something like this:
CriteriaBuilder.In<String> in = criteriaBuilder.in( ??? );
or
Path<Object> path = root.get(student_ID);
CriteriaBuilder.In<Object> in = criteriaBuilder.in(path);
but I just don't know how to use it properly...
So if you know how to translate only this part, it would solve it for me probably already:
where teacher0_.school_id **in** (select school0_.id
from vnic03.school school0_
where school0_.student_id = student0_.id)))
I found a Solution after reading chapter 5 in this article: https://www.baeldung.com/jpa-criteria-api-in-expressions
Subquery<School> subQueryForInExpression = searchQuery.subquery(School.class);
Root<School> fromSchoolSubQuery = subQueryForInExpression.from(School.class);
subQueryForInExpression.select(fromSchoolSubQuery.get(student_id)).where(criteriaBuilder.equal(fromSchoolSubQuery.get(school_id), root.get(student_id)));
The subQueryForInExpression represents the Select subquery in the IN Expression:
select school0_.id
from vnic03.school school0_
where school0_.student_id = student0_.id
Now we have to add the in Expression to the subRestrictions, this is done with CriterisBuilder.in(...).value(subQueryForInExpression):
subRestrictions.add(criteriaBuilder.in(fromSchoolSubQuery.get(school_id)).value(subQueryForInExpression));

Implement Hibernate with OrderBy

I want to implement Hibernate query with OrderBy clause. I tried this:
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<OrdersModel> query = builder.createQuery(OrdersModel.class);
Root<OrdersModel> root = query.from(OrdersModel.class);
query.select(root).orderBy(root.get("added"));
Query<OrdersModel> q = session.createQuery(query);
cdList = q.getResultList();
But I have to cast the .orderBy like this query.select(root).orderBy((List<javax.persistence.criteria.Order>) root.get("added"));
Do you know what is the proper way to implement this?
I tried also this:
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<OrdersModel> query = builder.createQuery(OrdersModel.class);
Root<OrdersModel> root = query.from(OrdersModel.class);
query.select(root);
query.orderBy(builder.desc(root.get("added")));
Query<OrdersModel> q = session.createQuery(query).setMaxResults(5);
cdList = q.getResultList();
But the rows order are not displayed properly. The list is not properly sorted.

Build criteria query with joins and custom parameters

I need to build following query using JPA and criteria query but I stuck on join conditions. The query is:
SELECT p.*
FROM output cu
JOIN user ur ON cu.id = ur.id AND cu.key = ur.key
JOIN product p ON cu.id = p.id AND cu.key = p.key
WHERE p.refreshtimestamp IS NOT NULL AND cu.active = true
So far I have following, but how to apply join conditions:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Output> cq = cb.createQuery(Output.class);
Root<Output> output= cq.from(Output.class);
Join<Output, User> user = output.join("user", JoinType.INNER);
Join<User, Product> product = user.join("product", JoinType.INNER);
Any help will be appreciated
Following should help.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Product> criteria = builder.createQuery(Product.class);
Root<Output> outputRoot = criteria.from(Output.class);
Root<User> userRoot = criteria.from(User.class);
Root<Product> productRoot = criteria.from(Product.class);
Predicate[] predictes = {
builder.equal(outputRoot.get("id"), userRoot.get("key")),
builder.equal(productRoot.get("id"), userRoot.get("key")),
builder.notEqual(productRoot.get("refreshtimestamp"), null), // not sure about null
builder.equal(outputRoot.get("active"), true)
};
criteria.select(productRoot);
criteria.where(builder.and(predicates));
Although this would produce cross joins query, it will work because of where clause making it work like inner join as you require.

JPA 2 + Criteria API

Employee (table)
id - int
ctd_id - int
message - char
SELECT a.*
FROM Employee a left outer join
( select * from Employee where message = 23 ) b
on a.ctd_id = b.ctd_id
where a.message = 22 and b.id is null;
This is what i tried
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> criteria = cb.createQuery(Employee.class);
Root<Employee> emp = criteria.from(Employee.class);
CriteriaQuery<Employee> sq = c.select(emp);
Subquery<Employee> sq2 = criteria.subquery(Employee.class);
Root<Employee> emp2 = sq2.from(Employee.class);
Join<Employee,Employee> sqEmp = emp2.join("ctd_id", JoinType.LEFT);
sq.select(sqemp).where(cb.equal(emp2.get("message"), cb.parameter(String.class, "23")));
sq.where(cb.in(path).value(sq2));
TypedQuery<Employee> q = em.createQuery(criteria);
List<Employee> employeess = q.getResultList()
But, i am not able to understand as to how i should apply a join on a subquery with where clause.
please help .
JPA does not support sub-queries in the FROM clause.
Either use SQL for your query, or rewrite it not to have a sub-query in the from clause, it doesn't look like you need it.

JPQL: inner join with group by

I'm trying to retrieve data from database using criteriabuilder. It's working great, query is almost perfect... almost. Unfortunately Java don't want me to use group by or distinct as a result of my query. How to make Java retrieve only unique records? My code is here:
List<Documentation> documentationList = new ArrayList<>();
DatabaseConnector dc = new DatabaseConnector();
List<Predicate> criteria = new ArrayList<Predicate>();
EntityManager em = dc.getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Documentation> select = builder.createQuery(Documentation.class);
Root<Documentation> u = select.from(Documentation.class);
Join<Documentation, DocumentationUser> du = u.join("documentationUserCollection", JoinType.INNER);
javax.persistence.Query q = em.createQuery(select);
select.groupBy(u.<String>get("documentationId"));
select.distinct(true);
documentationList = q.setMaxResults(pageSize).setFirstResult(first).getResultList();
Try swapping 2 lines lower the line that creates the query:
select.groupBy(u.<String>get("documentationId"));
select.distinct(true);
javax.persistence.Query q = em.createQuery(select);

Categories

Resources