【发布时间】:2021-05-20 22:21:52
【问题描述】:
我在我的项目中使用 jdk 1.8、hibernate 和 jpa。并使用规范/标准来构建我的搜索查询。
我有一个 class A(一个休眠实体),它具有 class B 作为属性。所以,粗略地说,它看起来像:
@Entity
class A {
Long id;
String comment;
@OneToOne
B b;
}
和...
@Entity
class B {
Long id;
String type;
}
我的 repository 类看起来像(大致):
public interface ARepository extends PagingAndSortingRepository<A, Integer>,
JpaSpecificationExecutor<A> {
}
大多数简单的 JPA 查询都按预期工作。甚至直接基于 A 类的规范/标准也在起作用。但是,我需要创建一个 动态查询 并且应该在 PagingAndSortingRepository 类的“findAll”方法下执行。 这个查询应该等同于
select * from A a left join B b on a.b_id = b.id
where b.type='final' and a.comment='blah';
我在规范中创建了与上述类似的逻辑,例如:
public Specification<A> getSpecification() {
return (itemRoot, query, criteriaBuilder) -> {
.........
List<Predicate> partialQueries = new ArrayList<>();
partialQueries.add(criteriaBuilder.equal(itemRoot.get("b.type"), "final"));
partialQueries.add(criteriaBuilder.equal(itemRoot.get("comment"), "blah"));
//Other queries to be added...
return criteriaBuilder.and(partialQueries.toArray(new Predicate[0]));
};
}
然后出现错误:
Unable to locate Attribute with the the given name [b.type] on this ManagedType [com.something.domain.A]
对如何为属于嵌套对象的字段创建条件/规范有任何见解吗?
【问题讨论】:
标签: java spring jpa criteria hibernate-criteria