7

考虑以下:

@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 个作者的书籍?

4

1 回答 1

21

在 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 = criteriaQuery.from(Book.class);
Predicate predicate = cb.ge(cb.size(book.get(Book_.authors)), 2);
criteriaQuery.where(predicate);
criteriaQuery.select(book);
于 2012-12-20T22:19:22.963 回答