命名查询的等效条件查询

时间:2011-10-27 10:26:38

标签: java hibernate hibernate-criteria

由于here.

,我的命名查询如下所示
@NamedQuery(
name="Cat.favourites", 
query="select c 
      from Usercat as uc 
      inner join uc.cat as c 
      where uc.isFavourtie = true 
      and uc.user = :user")

实施的调用如下:

Session session = sessionFactory.getCurrentSession();
Query query = session.getNamedQuery("Cat.favourites");
query.setEntity("user", myCurrentUser);
return query.list();

返回猫列表的等效标准查询是什么?

1 个答案:

答案 0 :(得分:2)

使用JPA 2.0标准: (这是使用JPA 2.0 Criteria api实现此目的的众多方法之一)

final CriteriaQuery<Cat> cq = getCriteriaBuilder().createQuery(Cat.class);
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();

final Root<Usercat> uc= cq.from(Usercat.class);

cq.select(uc.get("cat");

Predicate p = cb.equal(uc.get("favourtie", true);
p = cb.and(p, cb.equal(uc.get("user"), user));
cq.where(p);

final TypedQuery<Cat> typedQuery = entityManager.createQuery(cq);
return typedQuery.getResultList();