【问题标题】:Java - JPA-Specification: how to create criteria/specification on a field that belongs to a nested object?Java - JPA 规范:如何在属于嵌套​​对象的字段上创建标准/规范?
【发布时间】: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


    【解决方案1】:

    如果你想过滤嵌套对象。你可以写

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

    【讨论】:

      【解决方案2】:

      itemRoot.get("根类中嵌套对象字段的名称").get("nestedfieldname");

      示例: cb.equal(root.get("b").get("type"),value)

      在你的情况下 - itemRoot.get("b").get("type");

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-07
        • 2018-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-06
        • 2011-02-23
        相关资源
        最近更新 更多