假设您有两个实体猫和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() );
}
答案 0 :(得分:0)
当您需要从一组可选搜索条件动态撰写查询时,条件API非常有用。在这种情况下,使用JPQL可以实现更简单,更易读的代码:
String jpql = "select cat from Lick lick inner joinlick.cats cat where lick.id = :lickId";
List<Cat> cats = em.createQuery(jpql, Cat.class).setParameter("lickId", 2)
.getResultList();
甚至更简单,完全没有任何疑问:
Lick lick = em.get(Lick.class, 2);
List<Cat> cats = lick.getCats();