我试图与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();


这是行不通的。如果我注释掉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书籍,看看是否可以解决这个问题!

最佳答案

我认为应该是这样的:

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)
));

关于java - 通过JPA2多次加入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10654382/

10-09 03:35