Skip to content

Instantly share code, notes, and snippets.

@xsalefter
Created October 27, 2012 22:23
Show Gist options
  • Save xsalefter/3966643 to your computer and use it in GitHub Desktop.
Save xsalefter/3966643 to your computer and use it in GitHub Desktop.
// Part of your business logic code (using JPA). In this case, 'entityClass' is @Entity class,
// and 'restrictions' is list of org.dynamicfinder.Restriction instance passed from
// contoller/presesentation layer.
QueryBuilder queryBuilder = new JpaQueryBuilder(entityClass).where(restrictions);
// What we really need is query string based on restriction defined in
// controller.
final String queryString = queryBuilder.getQueryString();
final String countQueryString = queryBuilder.getCountQueryString();
// Use parsed queryString as plain JPQL to EntityManager#createQuery() method.
final TypedQuery<E> query = this.entityManager.createQuery(queryString, entityClass);
final TypedQuery<Long> countQuery = this.entityManager.createQuery(countQueryString, Long.class);
// Now, JPA need to know about which parameter should be added to their
// Query object. Luckily, dynamicfinder provide a way for this easily:
final Map<Integer, Restriction> actualRestriction = queryBuilder.getActualRestrictions();
for (final Integer parameter : actualRestriction.keySet()) {
query.setParameter(parameter, actualRestriction.get(parameter).getValue());
countQuery.setParameter(parameter, actualRestriction.get(parameter).getValue());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment