多个联接与JPA2

时间:2012-05-18 14:20:48

标签: java jpa-2.0

我正试图掌握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();

这不行。如果我评论第二&amp; where调用的第三个参数,它的工作原理(所以我只提供一个客户名称)。所以我弄错了。我只是不知道是什么!这是我试图用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书,看看我是否能解决这个问题!

1 个答案:

答案 0 :(得分: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)
));