Equivalent criteria query for named query

僤鯓⒐⒋嵵緔 提交于 2019-12-08 00:47:46

问题


My named query looks like this, thanks to 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")

And the call to implement looks like this :

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

What would be the equivalent criteria query that returns a list of cats ?


回答1:


With JPA 2.0 Criteria: (This is one of the many ways you can achieve this using 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();


来源:https://stackoverflow.com/questions/7914607/equivalent-criteria-query-for-named-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!