Reputation: 457
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.
Upvotes: 1
Views: 5207
Reputation: 1050
It is always better to put proper indentation for your query. The advantages are:
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.
Upvotes: 1