2012-05-18 35 views
0

我正試圖抓住JPA2並試圖做一些聯接來獲得單個結果。這是我目前試過的:與JPA2的多個聯接

CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); 
CriteriaQuery<FileCollection> cq = cb.createQuery(getEntityClass()); // getEntityClass() will return FileCollection.class 

Root<FileCollection> collectionRoot = cq.from(getEntityClass()); 
Join<FileCollection, Repository> repositories = collectionRoot.join(FileCollection_.repository); 
Join<Repository, Customer> customers = repositories.join(Repository_.customer); 

cq.select(collectionRoot); 
cq.where(cb.equal(customers.get(Customer_.name), customerName), 
    cb.equal(repositories.get(Repository_.name), repositoryName) , 
    cb.equal(collectionRoot.get(FileCollection_.folderName), folderName) 
); 

return getEntityManager().createQuery(cq).getSingleResult(); 

雖然這不行。如果我將第二個參數的第二個參數註釋掉,它就可以工作(所以我只提供一個客戶名)。所以我出錯了。我只是不知道什麼!以下是我試圖用SQL表達的查詢:

SELECT f.* 
FROM filecollection f 
JOIN repository r ON f.REPOSITORY_ID = r.REPOSITORY_ID 
JOIN customer c ON r.CUSTOMER_ID = c.CUSTOMER_ID 
WHERE c.NAME = 'X' AND r.NAME = 'Y' AND f.FOLDER_NAME = 'Z'; 

任何人都可以幫助我並指出我的錯誤。與此同時,我會回到我的JPA2書籍,看看我能否解決這個問題!

+0

任何異常堆棧跟蹤? – DaTroop

+0

A NoResultsException。我傳遞的參數是正確的,但如果我的查詢正確,我希望得到結果。 –

回答

1

我想應該是這樣的:

cq.where(cb.and(cb.equal(customers.get(Customer_.name), customerName), 
       cb.equal(repositories.get(Repository_.name), repositoryName) , 
       cb.equal(collectionRoot.get(FileCollection_.folderName), folderName) 
)); 
+0

這並沒有改變結果。當我相信它不應該時,它仍然沒有結果。 –

+0

結果SQL查詢是什麼樣的? – DaTroop

+0

我剛剛打開Hibernate日誌記錄,就像我注意到我的錯誤。你的解決方案是正確的 - 我無法打字!感謝您的幫助:) –