java-jpa规范:如何在属于嵌套对象的字段上创建标准/规范?

vuktfyat  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(480)

我正在我的项目中使用JDK1.8、hibernate和jpa。并使用规范/条件构建我的搜索查询。
我有一个类a(hibernate实体),它的属性是类b。所以,大致上,它看起来像:

@Entity
class A {
     Long id;  
     String comment;

     @OneToOne
     B b;
}

还有。。。

@Entity
class B {

     Long id;
     String type;
}

我的存储库类大致如下所示:

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]

关于如何在属于嵌套对象的字段上创建条件/规范有什么见解吗?

nfs0ujit

nfs0ujit1#

如果要筛选嵌套对象。你可以写

itemRoot.get("NestedTableName").get("nestedfieldname")

In your case - itemRoot.get("B").get("type")

相关问题