假设您有两个实体 Cats 和 Licks。每个都有另一个列表。给定另一个的 id,你如何编写 JPA 来找到一个。
我的问题是:为什么不让这更简单呢?这个界面令人困惑......但无论如何,这就是你如何做到的。
@PersistenceContext
protected EntityManager em;
@Test
public void testFindCatsByLickId() throws Exception
{
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
Root<Cat> cats = cq.from( Cat.class );
Root<Lick> licks = cq.from( Lick.class );
ListJoin<Cat, Lick> joinCatL = cats.join(Cat_.lickList);
// just creating the following ListJoin object will cause this query to fail!
// ListJoin<Lick, Cat> joinLCat = lick.join(Lick_.catList);
Predicate p = cb.and(
cb.equal(licks.get(Lick_.lickId), new Integer(2))
, cb.equal(licks, joinCatL)
);
cq.select(cats).where(p);
TypedQuery query = em.createQuery(cq);
List<Cat> list = query.getResultList();
assertList( list );
assertTrue(null != list && ! list.isEmpty() );
}