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(); }
Pascal thivent
source share