0

我正在使用 JPA 和 playframework 选择 JAVA 中的记录,如下所示:

EntityManager em = JPA.em();
List<News> resultUrl = News.find("link", url).fetch();
 if (resultUrl.isEmpty()) { //check if it is exist
}

但我想选择具有两个条件的记录,如下所示:

where link='url' and name='joe'

我怎样才能做到这一点?感谢您的帮助。最好的祝愿。

4

4 回答 4

2

利用:

Query q = em.createQuery("FROM News n WHERE n.link=:url and n.name=:name");
q.setParameter("url", "url").setParameter("name", "joe");
List<News> resultUrl = q.getResultList();

...

于 2012-04-17T08:16:07.027 回答
2

使用 Play 的一种方法是

List<News> resultUrl = News.find("byLinkAndName", url, "joe").fetch();
 if (resultUrl.isEmpty()) { //check if it is exist
}

其他:

List<News> resultUrl = News.find("link = ? and name = ?", url, "joe").fetch();
 if (resultUrl.isEmpty()) { //check if it is exist
}
于 2012-04-17T08:47:32.883 回答
2

我的建议是定义一个命名查询:

@Entity
@NamedQueries({
    @NamedQuery(name = News.FIND_BY_URL_AND_NAME, query = "Select n FROM News as n WHERE n.url=:" + News.PARAM_URL + " AND n.name=:" + News.PARAM_NAME)
})
public class News {
    public static final String FIND_BY_URL_AND_NAME = "News.findByUrlAndName";
    public static final String PARAM_URL = "url";
    public static final String PARAM_NAME = "name";

    //CONTINUE
}

然后你这样称呼它:

Query query = em.createNamedQuery(News.FIND_BY_URL_AND_NAME);
query.setParameter(News.PARAM_URL, "url");
query.setParameter(News.PARAM_NAME, "name");
List<News> news = query.getResultList();
于 2012-04-17T08:48:02.870 回答
0

看看 CriteriaBuilder、CriteriaQuery 和 Predicate:

EntityManager em = JPA.em();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> criteriaQuery = cb.createQuery(News.class);
Root<T> root = criteriaQuery.from(News.class);
criteriaQuery.select(root);

List<Predicate> ps = new ArrayList<Predicate>();
ps.add(sb.equal(root.get("link", url));
ps.add(sb.equal(root.get("name", "joe"));

criteriaQuery.where(cb.and(ps.toArray(new Predicate[0])));

List<News> resultUrl = em.createQuery(criteriaQuery).getResultList();

问候

于 2012-04-17T08:13:44.000 回答