Thursday, May 8, 2014

JPA Criteria API Queries (CriteriaBuilder, CriteriaQuery) Create Dynamic Query instead of appending String

Removed
Here is an example about how to create a Dynamic Query.


 This is very efficient when you have a method where some parameters may be null. so instead of creating a String builder (or String Buffer) and append the SQL Query, it is better to use the Criteria API Queries.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 
public List<Devices> findDevice(String enterpriseId, List<String> modelIds, List<String> deviceIds, Date constructionDate) {
 
 CriteriaBuilder builder = entityManager.getCriteriaBuilder();
 CriteriaQuery<Devices> query = builder.createQuery(Devices.class);
 Root<Devices> deviceRoot = query.from(Devices.class);

 List<Predicate> predicateList = new ArrayList<Predicate>();
 if(enterpriseId !=null ){
  predicateList.add(builder.equal(deviceRoot.get("enterprise").get("enterpriseId"), enterpriseId));

 }
 if(modelIds != null && !modelIds.isEmpty()){
  predicateList.add(builder.isTrue(deviceRoot.get("deviceModel").get("modelId").in(modelIds)));
 }
 if(deviceIds != null && !deviceIds.isEmpty()){
  predicateList.add(builder.isTrue(deviceRoot.get("deviceId").in(deviceIds)));
 }

 predicateList.add(builder.greaterThan(deviceRoot.<Date>get("constructionDate"), constructionDate));

 query.where(builder.and(predicateList.toArray(new Predicate[predicateList.size()])));

   
 return entityManager.createQuery(query).getResultList();
}

Hope it helped you :) 

No comments :

Post a Comment

Articles les plus consultés