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

这虽然行不​​通。如果我注释掉 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 书,看看我是否能解决这个问题!

4

1 回答 1

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)
));
于 2012-05-18T14:36:46.550 回答