简体   繁体   中英

select query in java (JPA)

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.

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

...

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
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM