Java Spring jpa criteriaBuilder在列表中搜索
我有一个图书类,里面有作者列表:Java Spring jpa criteriaBuilder在列表中搜索,java,spring,hibernate,jpa,java-persistence-api,Java,Spring,Hibernate,Jpa,Java Persistence Api,我有一个图书类,里面有作者列表: @Entity @Table(name = "book") public class Book extends Content { @ManyToMany(fetch = FetchType.LAZY) private List<Author> authors; ...} 如何检查列表中给定的authorId 错误: java.lang.IllegalStateException: Illegal attempt to deref
@Entity
@Table(name = "book")
public class Book extends Content {
@ManyToMany(fetch = FetchType.LAZY)
private List<Author> authors;
...}
如何检查列表中给定的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]
为此,您可以使用连接谓词: 参考以下代码
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);
}
};
}
公共静态规范授权(长授权){
返回新规范(){
@凌驾
公共谓词toPredicate(根根、CriteriaQuery、CriteriaBuilder cb){
Join=root.Join(“作者”);
返回cb.equal(join.get(“id”),authorId);
}
};
}
我并不是说我会帮忙,但你能详细说明一下你是如何使用它的吗?这对我来说是一个新的构造,所以我不知道规范从哪里来,以及如何执行它。。。在我看来,根没有正确初始化参见[null.authors]
中的null
,但它不是真正的NPE…好吧,我找到了一些教程-…@Betlista我的问题是在列表中搜索,应该类似于builder.equal(root.get(“authors”).get(“id”).as(Long.class),authorId)
@Harsahl如果我还需要选择作者属性怎么办?我认为join不会自动选择*.authors@zt1983811,所以您只需要在join中获取这些属性。
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);
}
};
}