我正試圖抓住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書籍,看看我能否解決這個問題!
任何異常堆棧跟蹤? – DaTroop
A NoResultsException。我傳遞的參數是正確的,但如果我的查詢正確,我希望得到結果。 –