I have a query I would write in older Hibernate (utilising the SessionFactory
bean). However, I have shifted to Spring Boot and am now utilizing the JPA 2 which is essentially seems like a layer of abstraction over Hibernate. Could anyone guide me on as to how to add restrictions? I believe I will now have to use the EntityManager
bean with JPA. Here is the older query.
@Override
@SuppressWarnings("unchecked")
public List<Party> queryPartiesBetweenDates(Date startDate, Date endDate, String sortBy, Integer count) {
Criteria criteria = getCurrentSession().createCriteria(Party.class);
if (startDate != null) {
criteria.add(Restrictions.ge("startDate", startDate));
}
if (endDate != null) {
criteria.add(Restrictions.lt("endDate", endDate));
}
if (count != null) {
criteria.setMaxResults(count);
}
if (sortBy == null || !sortBy.equals("distance")) {
criteria.addOrder(Order.asc("startDate"));
}
return criteria.list();
}
Thanks!
The CriteriaBuilder is quite a bit more verbose than the native hibernate Restriction API, the primary reason is that it is fully typed when you use the MetaModel, which means the code will not compile if the type or name of a column causing a query to be invalid. Here is an example that does not use the generated MetaModel classes, and mostly resembles the old Hibernate code.
EntityManager em = emf.createEntityManager(); // or injected
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Party> query = cb.createQuery(Party.class);
Root<Party> partyRoot = query.from(Party.class);
query.select(partyRoot);
Predicate predicate = null;
Path<Date> startDatePath = partyRoot.<Date>get("startDate");
if (startDate != null) {
predicate = cb.greaterThanOrEqualTo(startDatePath, startDate);
}
if (endDate != null) {
Predicate additionalPredicate = cb.lessThanOrEqualTo(partyRoot.<Date>get("endDate"), startDate);
if (predicate == null) {
predicate = additionalPredicate;
} else {
predicate = cb.and(predicate, additionalPredicate);
}
}
query.where(predicate);
if (sortBy == null || !sortBy.equals("distance")) {
query.orderBy(cb.asc(startDatePath));
}
return em.createQuery(query).setMaxResults(count).getResultList();
If you have many Predicates, it may be a good idea to add them to a list, or create a utility method for handling them.