简体   繁体   中英

How to write this join query with hibernate CRITERIA

select ptm.* from ProofTestMaster ptm LEFT JOIN 
ProofTestApplicationMap ptam on ptm.proofTestID = ptam.proofTestID 
LEFT JOIN ProofTestComapartmentMap ptcm on ptm.proofTestID = ptcm.proofTestID 
where (ptam.applicationID = 3 and ptm.isDeleted = 0) or 
(ptcm.compartmentID = 4 and ptm.isDeleted = 0)

Where ProofTestApplicationMap and ProofTestComapartmentMap is map table and they don't have entity in java end.

It is always better to put proper indentation for your query. The advantages are:

  • You will understand the query easilly
  • Other person will also understand quickly.

So I did this for you. Now the query looks like:

select 
    ptm.* 
from ProofTestMaster ptm 
    LEFT JOIN ProofTestApplicationMap ptam on ptm.proofTestID = ptam.proofTestID 
    LEFT JOIN ProofTestComapartmentMap ptcm on ptm.proofTestID = ptcm.proofTestID 
where 
    (ptam.applicationID = 3 and ptm.isDeleted = 0) or 
    (ptcm.compartmentID = 4 and ptm.isDeleted = 0);

Now below is the implementation with CriteriaBuilder with Static Metamodel:

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);

Root<ProofTestMaster> mainRoot = criteriaQuery.from(ProofTestMaster.class);

Join<ProofTestMaster, ProofTestApplicationMap> firstJoin = mainRoot.join(ProofTestMaster_.proofTestID, JoinType.LEFT);
Join<ProofTestMaster, ProofTestComapartmentMap> secondJoin = mainRoot.join(ProofTestMaster_.proofTestID, JoinType.LEFT);

Predicate p1 = criteriaBuilder.equal(firstJoin.get(ProofTestApplicationMap_.applicationID),3);
Predicate p2 = criteriaBuilder.equal(mainRoot.get(ProofTestMaster_.isDeleted),0);
Predicate p3 = criteriaBuilder.equal(secondJoin.get(ProofTestComapartmentMap_.compartmentID), 4);
Predicate p4 = criteriaBuilder.and(p1,p2);
Predicate p5 = criteriaBuilder.and(p3,p2);
Predicate p6 = criteriaBuilder.or(p4,p5);

criteriaQuery.where(p6);

criteriaQuery.select(criteriaBuilder.count(mainRoot));

Long count = entityManager.createQuery(criteriaQuery).getSingleResult();

If you see the above code, there are total 6 Predicates, which can be put into List. But I kept it like this for your understanding.

Let me know if it helps you. Thanks and happy coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM