爲您的查詢提供適當的縮進總是更好。其優點是:
- 你就會明白查詢easilly
- 其他人也將很快明白。
所以我爲你做了這個。現在查詢是這樣的:
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);
現在下面是CriteriaBuilder實施與靜態元模型:
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();
如果你看到上面的代碼中,總共有6個謂詞,可以投入列表。但爲了您的理解,我保持這樣。
讓我知道它是否對你有幫助。感謝和愉快的編碼。
希望此鏈接將幫助你:) http://stackoverflow.com/questions/6165743/how-to-write-hibernate-criteria-query-for-two-different-tables – DushanthaR
沒有,我需要使用標準API而不僅僅是HQL或SQL。 –
映射2個關係和3個表格非常困難。此外,維護這種映射真的很複雜。如果你有一對多,多對多的關係,你還需要保持懶惰的加載策略,這會讓你的工作變得更加困難。在我看來,這是不必要的映射。 – erencan