等价条件查询命名查询 [英] Equivalent criteria query for named query

查看:109
本文介绍了等价条件查询命名查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的命名查询看起来像这样,这要归功于

  @NamedQuery(
name =Cat.favourites,
query =从Usercat中选择c
作为uc
内部连接uc.cat作为c
其中uc.isFavourtie = true
和uc.user =:user)

实现调用如下所示:

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

返回猫列表的等效条件查询是什么?

$ b $使用JPA 2.0标准:
(这是使用JPA 2.0 Criteria API可以实现这一目标的众多方法之一)

b
$ b

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

最终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);
返回typedQuery.getResultList();


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 ?

解决方案

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

这篇关于等价条件查询命名查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆