JPA2.0學習筆記---Criteria 查詢
阿新 • • 發佈:2019-02-18
@Override
public List<Book> getBookByTitle(String title) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Book> c = cb.createQuery(Book.class);
Root<Book> book = c.from(Book.class);
c.select(book); //類似於 from Book b 這個裡面的b
c.distinct(true); // 去除重複行
//構建引數
List<Predicate> criteList = new ArrayList<Predicate>(); if (title != null) { ParameterExpression<String> p = cb.parameter(String.class, "title"); //criteList.add(cb.equal(book.get("title"), p)); cb.and(cb.equal(book.get("title"), p)); } if (criteList.size() == 0) { throw new RuntimeException("no criteria"); } else if (criteList.size() == 1) { c.where(criteList.get(0)); } else { c.where(cb.and(criteList.toArray(new Predicate[0]))); } TypedQuery<Book> q = em.createQuery(c); if(title != null) q.setParameter("title", title); return q.getResultList(); }
下面是簡化版~ 適合一個
@Override public List<Book> getBookByTitle(String title) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Book> c = cb.createQuery(Book.class); Root<Book> book = c.from(Book.class); c.select(book); ParameterExpression<String> pe_title = cb.parameter(String.class,"title"); c.where(cb.equal(book.get("title"), pe_title)); TypedQuery<Book> q = em.createQuery(c); if(title != null) q.setParameter("title", title); return q.getResultList(); }