Search code examples
javahibernate-criteria

Case Statement with multiple conditions using hibernate criteria


SELECT case when status = 'A' and login='Y' then 'Login Allowed' else 'Enable the Login Status' end as UserLoginStatus FROM Users.

i have verified few answers from stackoverflow but unable find the code to handle the above case.

Below sample code will work for single conditions(case when with status='A') .

**CriteriaBuilder cbr = session_hiber.getCriteriaBuilder();
cbr.selectCase()
.when(cbr.equal(path.get("status"), "A"), "Login Allowed")
.otherwise("Enable the Login Status")
.alias("UserLoginStatus");**

How to handle the Case criteria with multiple conditions using criteriaBuilder.


Solution

  • came across this post while I was working on same scenario.

    Following code worked for me. by creating the list of predicates and then passing it in the when clause

    List<Predicate> casePredicates = getcasePredicate(criteriaBuilder,contractBidRoot);
    criteriaBuilder.selectCase()
                        .when(criteriaBuilder.and(casePredicates.toArray(new
                        Predicate[casePredicates.size()])), "DISCARD")
                        .otherwise(contractBidRoot.get(Constant.STATUS))));
    
    public List<Predicate> getcasePredicate(CriteriaBuilder criteriaBuilder, Root<ContractBid> contractBidRoot)
    {
           List<Predicate> casePredicates = new ArrayList<>(); 
           casePredicates.add(criteriaBuilder.lessThanOrEqualTo(contractBidRoot.get("date"),
           LocalDateTime.now()));
           casePredicates.add(criteriaBuilder.equal(contractBidRoot.get("status"), "DONE"));
           return casePredicates;
    }