Spring jpa criteriaBuilder在列表中搜索

时间:2016-01-18 11:01:07

标签: java spring hibernate jpa java-persistence-api

我有一个包含作者列表的书类:

@Entity
@Table(name = "book")
public class Book extends Content {

    @ManyToMany(fetch = FetchType.LAZY)
    private List<Author> authors;
...}

现在,这是我的BookSpecifications课程:

public static Specification<Book> authorIdIs(Long authorId) {
    return new Specification<Book>() {
        @Override
        public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
            return cb.isTrue(root.get("authors").get("id").in(authorId));
        }
    };
}

如何检查列表中的给定authorId

错误:

java.lang.IllegalStateException: Illegal attempt to dereference path source [null.authors] of basic type
    at org.hibernate.jpa.criteria.path.AbstractPathImpl.illegalDereference(AbstractPathImpl.java:98) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:191) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    at com.tarameshgroup.derakht.service.specs.BookSpecifications$3.toPredicate(BookSpecifications.java:40) ~[classes/:na]
    at org.springframework.data.jpa.domain.Specifications$ComposedSpecification.toPredicate(Specifications.java:189) ~[spring-data-jpa-1.9.2.RELEASE.jar:na]

1 个答案:

答案 0 :(得分:10)

为此你可以使用Join with predicate:

参考下面的代码,

public static Specification<Book> authorIdIs(Long authorId) {
    return new Specification<Book>() {
        @Override
        public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                Join join = root.join("authors");                   
                return cb.equal(join.get("id"),authorId);
        }
    };
}