请考虑以下事项:
@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条件查询表达式,哪一天,我会找到所有超过2位作者的书籍?
答案 0 :(得分:18)
在JPQL中:
select b from Book where size(b.authors) >= 2
使用条件API(但为什么要用下面的混乱替换这样一个简单的静态查询?):
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Book> criteriaQuery = cb.createQuery(Book.class);
Root<Book> book = criteria.from(Book.class);
Predicate predicate = cb.ge(cb.size(book.get(Book_.authors)), 2);
criteriaQuery.where(predicate);
criteriaQuery.select(