Criteria Builder in Java for Dynamic Queries

    0

    0

    Kishan Kumar

    This code example initializes and uses the EntityManager persistence context read to query the entity class. A criteria builder is then used to create a query and root entity class is chosen. Finally, the TypedQuery is initialized with the criteria and results are returned.

    Initlialize below code in Constructor
      @PersistenceContext(unitName = "read")
      private EntityManager entityManagerRead;
    
    Now Write this below code in your function
    
    CriteriaBuilder criteriaBuilder = entityManagerRead.getCriteriaBuilder();
    CriteriaQuery<EntityClass> criteriaQuery = criteriaBuilder.createQuery(EntityClass.class);
    Root<EntityClass> entityClassRoot = criteriaQuery.from(EntityClass.class);
    
    Specification<EntityClass> entityClassSpecification = EntityClassSpecificationBuilder.searchSpecification(request);
    // Read my another article to check how specification builder is created and used
    Predicate searchPredicate = entityClassSpecification.toPredicate(entityClassRoot, criteriaQuery, criteriaBuilder);
    
    if (searchPredicate != null)
      criteriaQuery.where(searchPredicate);
    
    // Below two lines are for pagination you must consider adding this if you are having long list of data
    request.setLimit(Objects.nonNull(request.getLimit()) ? 500 : 5000);
    request.setOffset(Objects.nonNull(request.getOffset()) ? request.getOffset() : 0);
    
    cq.select(entityClassRoot);
    cq.orderBy(Sort.Direction.ASC.equals(request.getDirection()) ? criteriaBuilder.asc(
        entityClassRoot.get(request.getOrderBy())) : criteriaBuilder.desc(entityClassRoot.get(request.getOrderBy())));
    
    TypedQuery<EntityClass> typedQuery = entityManagerRead.createQuery(criteriaQuery);
    List<EntityClass> entityClass = typedQuery.setFirstResult(request.getOffset()).setMaxResults(
        request.getLimit()).getResultList();
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.