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);
Related
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));
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.
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.
I have the following native SQL query that I am trying to convert to JPA criteria:
select et.* from t_empl_tx et, t_dept d
where et.assigned_dept = d.dept (+)
and et.employee_id = :employee_id
and (et.start_date >= d.dept_est_date and
et.start_date <= d.dept_close_date or
et.start_date is null or
d.dept is null)
(Note that (+) is roughly equivalent to a left outer join in this case. Yes, I know it denotes the OPTIONAL table, etc, etc).
Here is my attempt at the code:
EntityManager entityManager = getEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<EmployeeTransaction> criteriaQuery = criteriaBuilder.createQuery(EmployeeTransaction.class);
Root<EmployeeTransaction> root = criteriaQuery.from(EmployeeTransaction.class);
// this line bombs!
Join<EmployeeTransaction, Department> join =
root.join(EmployeeTransaction_.assignedDepartment).join(Department_.id).join(DepartmentCompositeId_.department, JoinType.LEFT);
List<Predicate> predicates = new ArrayList<>();
predicates.add(criteriaBuilder.equal(root.get(EmployeeTransaction_.id).get(EmployeeTransactionCompositeId_.employeeId), employeeId));
predicates.add(criteriaBuilder.or(
criteriaBuilder.and(
criteriaBuilder.greaterThanOrEqualTo(root.<Date>get(EmployeeTransaction_.requestedStartDate), join.get(Department_.id).<Date>get(DepartmentCompositeId_.departmentCreationDate)),
criteriaBuilder.lessThanOrEqualTo(root.<Date>get(EmployeeTransaction_.requestedStartDate), join.<Date>get(Department_.departmentCloseDate))
),
criteriaBuilder.isNull(root.get(EmployeeTransaction_.requestedStartDate)),
criteriaBuilder.isNull(join.get(Department_.id).get(DepartmentCompositeId_.departmentCreationDate))
));
criteriaQuery.select(root).where(predicates.toArray(new Predicate[]{}));
TypedQuery<EmployeeTransaction> query = entityManager.createQuery(criteriaQuery);
List<EmployeeTransaction> result = query.getResultList();
This issue seems to be that I'm trying to join a string column, assigedDepartment, to a single field of a composite ID. This is perfectly legal in SQL, but not so easy in the code.
One option is to convert to a number of subqueries, which seems to kill the point of the left outer join entirely.
Can anyone point out what I'm doing wrong?
Jason
You should post your entities so that the answers can be more specific.
However, I'll give a try.
If I am right, you can rewrite the query:
select et.*
from t_empl_tx et
left join t_dept d on et.assigned_dept = d.dept
where
et.employee_id = :employee_id
and (
et.start_date >= d.dept_est_date
and et.start_date <= d.dept_close_date
or et.start_date is null
or d.dept is null)
So, shortly, you have to move the JoinType.LEFT to assignedDepartment join:
EntityManager entityManager = getEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<EmployeeTransaction> criteriaQuery = criteriaBuilder.createQuery(EmployeeTransaction.class);
Root<EmployeeTransaction> root = criteriaQuery.from(EmployeeTransaction.class);
Join<EmployeeTransaction, Department> department = root.join(EmployeeTransaction_.assignedDepartment, JoinType.LEFT);
Path<Date> employeeTransactionRequestedStartDate = root.get(EmployeeTransaction_.requestedStartDate);
Path<DepartmentCompositeId> departmentId = department.get(Department_.id);
Path<Date> departmentCreationDate = departmentId.get(DepartmentCompositeId_.departmentCreationDate)
Path<Date> departmentCloseDate = departmentId.get(DepartmentCompositeId_.departmentCloseDate)
criteriaQuery.select(root).where(
criteriaBuilder.equal(root.get(EmployeeTransaction_.id).get(EmployeeTransactionCompositeId_.employeeId), employeeId),
criteriaBuilder.or(
criteriaBuilder.and(
criteriaBuilder.greaterThanOrEqualTo(employeeTransactionRequestedStartDate, departmentCreationDate)),
criteriaBuilder.lessThanOrEqualTo(employeeTransactionRequestedStartDate, departmentCloseDate)
),
criteriaBuilder.isNull(employeeTransactionRequestedStartDate),
criteriaBuilder.isNull(departmentCreationDate)
)
);
TypedQuery<EmployeeTransaction> query = entityManager.createQuery(criteriaQuery);
List<EmployeeTransaction> result = query.getResultList();
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();