Best practice for creating a dynamic, typed JPA request?

I am trying to convert the "TableController" -Class that we used (without ORM) to generate dynamic SQL (in fact, the order column and direction are added to SQL).

Think of this โ€œTableControllerโ€ as a class that has a function to return the Entities list of a given class (known at runtime), in that order (String column / name properties, boolean asc / desc, both at runtime).

Now the problem is JPA (Hibernate - but the client only needs to use JPA interfaces): How can I implement this without string concatenation and in a safe way?

Thanks!

+7
java hibernate jpa
source share
1 answer

Now the problem is JPA (Hibernate - but the client only needs to use JPA interfaces): how can I implement this without string concatenation and in a safe way?

If you are using a JPA 2.0 implementation, I think you should look at the criteria API to create dynamic queries.

If you are using JPA 1.0, there is no standard way other than string concatenation (and my suggestion would be to use Hibernate's proprietary Query Criteria ).

The following article may also present some (specific) ideas: Hibernate Querying 102: Criteria API .


Imagine a method that has three parameters: Class entityClass, String orderByColumn, boolean ascending. How to create a query without concatenating strings that will give me all the objects of this class in the correct order?

With the Criteria API from JPA 2.0, you can do something like this:

public <T> List<T> findAllEntitiesOrderedBy(Class<T> entityClass, String orderByColumn, boolean ascending) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<T> criteria = builder.createQuery(entityClass); Root<T> entityRoot = criteria.from(entityClass); criteria.select(entityRoot); javax.persistence.criteria.Order order = ascending ? builder.asc(entityRoot.get(orderByColumn)) : builder.desc(entityRoot.get(orderByColumn)); criteria.orderBy(order); return em.createQuery(criteria).getResultList(); } 
+18
source share

All Articles