如何在JPA2中检查集合大小 [英] How to check a collection size in JPA2
本文介绍了如何在JPA2中检查集合大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下内容:
@Entity
public class Book
{
private List<String> authors;
@ElementCollection
public List<String> getAuthors() {
return authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
}
如何键入JPA2 CriteriaQuery表达式,例如,这将使我查找所有具有2位以上作者的所有Books?
How to type a JPA2 CriteriaQuery expression which, say, will let me find all the Books which have more than 2 authors?
推荐答案
在JPQL中:
select b from Book where size(b.authors) >= 2
使用标准API(但是为什么要用以下混乱内容替换这种简单的静态查询?):
Using the criteria API (but why would you replace such a simple static query with the following mess?):
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Book> criteriaQuery = cb.createQuery(Book.class);
Root<Book> book = criteriaQuery.from(Book.class);
Predicate predicate = cb.ge(cb.size(book.get(Book_.authors)), 2);
criteriaQuery.where(predicate);
criteriaQuery.select(book);
这篇关于如何在JPA2中检查集合大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文