Reputation: 125
I'm selecting records in JAVA with JPA and playframework like this:
EntityManager em = JPA.em();
List<News> resultUrl = News.find("link", url).fetch();
if (resultUrl.isEmpty()) { //check if it is exist
}
But i want to select records with two condition, like this:
where link='url' and name='joe'
How can i do this? Thanks for helping. Best wishes.
Upvotes: 0
Views: 1227
Reputation: 2584
My proposal is to define a named query:
@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
}
Then you call it like that:
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();
Upvotes: 2
Reputation: 4896
One way to do it with Play is
List<News> resultUrl = News.find("byLinkAndName", url, "joe").fetch();
if (resultUrl.isEmpty()) { //check if it is exist
}
Another:
List<News> resultUrl = News.find("link = ? and name = ?", url, "joe").fetch();
if (resultUrl.isEmpty()) { //check if it is exist
}
Upvotes: 2
Reputation: 485
Get a look at CriteriaBuilder, CriteriaQuery and 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();
Regards
Upvotes: 0
Reputation: 149
Use:
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();
...
Upvotes: 2