How To Create Conditional CriteriaBuilder with WHERE In Spring Boot using JPA or spring boot JPA.

Criteria used to create conditional complex query in JPA using EntityManager.

Creating CriteriaBuilder in spring boot using spring boot jpa or JPA is simple using EntityManager based on some condition where need to check null values or any other values, so using criteria the result can be filtered from Database based on the condition of Criteria.


Like below example - 

  • Created A class CriteriaBuilderDemo, in which creating the instance of EntityManager.
  • Creating the method that is taking all the parameters for the criteria and will return the List<User> based on criteria.
  • Getting instance of CriteriaBuilder using entityManager, using this will need to create CriteriaQuery and then will create a root that will contain the query and return type class.
  • Create a predicate based on the primary key.
  • Add the conditional values to predicate.
  • Pass the predicate to query for conditional result.
  • Get the result for query



public class CriteriaBuilderDemo {
  @PersistenceContext
private EntityManager entityManager;
public CriteriaBuilderDemo(){
}

public List<User> findAllByIds(Long Id, Long typeId, Long code) {
List<User> result = null;
try {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<User> query = builder.createQuery(User.class);
Root<User> root = query.from(User.class);
Predicate predicate = builder.isNotNull(root.get("id"));
if(typeId != null) {
predicate = builder.and(predicate, builder.equal(root.get("typeId"), typeId));
}
if(typeId == null) {
predicate = builder.and(predicate, builder.isNull(root.get("typeId")));
}
if(code != null) {
predicate = builder.and(predicate, builder.equal(root.get("code"), code));
}
query.where(predicate);
result = entityManager.createQuery(query).getResultList();
}catch(Exception e) {
System.out.println(e);
}
return result;
}
}



Check Official Docs : Click Here









Post a Comment

Previous Post Next Post