2012-04-17 79 views
0

我選擇記錄JAVA JPA和playframework這樣的:選擇查詢(JPA)

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' 

我該怎麼做? 感謝您的幫助。 最良好的祝願。

回答

0

獲取一看CriteriaBuilder,CriteriaQuery中和謂語:

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

問候

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

...

2

一種方式與遊戲做的很

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 
} 
+0

不需要擔心實體經理在這裏。 Play爲你處理所有這些事情。 – emt14 2012-04-17 08:49:39

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