2013-08-19 52 views
0
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) 

其中ProofTestApplicationMapProofTestComapartmentMap是映射表,它們在java結束時沒有實體。如何使用休眠寫入此加入查詢CRITERIA

+0

希望此鏈接將幫助你:) http://stackoverflow.com/questions/6165743/how-to-write-hibernate-criteria-query-for-two-different-tables – DushanthaR

+0

沒有,我需要使用標準API而不僅僅是HQL或SQL。 –

+0

映射2個關係和3個表格非常困難。此外,維護這種映射真的很複雜。如果你有一對多,多對多的關係,你還需要保持懶惰的加載策略,這會讓你的工作變得更加困難。在我看來,這是不必要的映射。 – erencan

回答

1

爲您的查詢提供適當的縮進總是更好。其優點是:

  • 你就會明白查詢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個謂詞,可以投入列表。但爲了您的理解,我保持這樣。

讓我知道它是否對你有幫助。感謝和愉快的編碼。

+0

首先,我很抱歉未格式化我的查詢,並感謝您的解決方案。你能否建議一些靜態元模型以外的東西? –

+0

沒問題。但是,我可以知道爲什麼你不想在沒有靜態元模型的情況下做到這一點?使用靜態元模型可以提供類型安全功能。添加靜態元模型也非常簡單。您可以查看這篇博文:[鏈接](http://dailytechdairy.blogspot.in/2013/08/java-persistency-api-20-jpa-hibernate.html) –

+0

是的確定其實際上是個人問題..我在一個項目的中間,並有一個緊迫的最後期限。如果我這樣做,我必須在幾個部分工作,這樣會花費很多時間。所以我只想節省時間。 –