spring数据规范api-unidirectional-join-onetomany

tmb3ates  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(331)

我有两个实体,一个 Dokument :

@Entity
@Table(name = "DOKUMENT")
public class Dokument {
    @Id
    private Long id;
    ...
}

以及 BusinessList :

@Entity
@Table(name = "BUSINESS_LIST")
public class BusinessList{

    @Id
    private Long id;

    @Column(name = "BUSINESS_LIST_NUMBER", unique = true)
    @NotNull
    private String businessListNumber;

    @OneToMany
    @JoinColumn(name = "BUSINESS_LIST_ID")
    private List<Dokument> dokuments = new ArrayList<>();
    ...
}

我想按业务列表编号查找所有文档。我正在尝试使用规范api进行查询。原始sql查询如下所示:

SELECT * FROM DOKUMENT d 
INNER JOIN BUSINESS_LIST b ON d.BUSINESS_LIST_ID = b.id  
WHERE b.BUSINESSLIST_NUMMER = :businessListNumber

然而,对于api规范来说,这并不是那么直截了当的。如果我能在这两者之间建立双向关系,那么方法将非常简单:

public static Specification<Dokument> businessListNumberEqual(String businessListNumber) {
        return (Root<Dokument> root, CriteriaQuery<?> query, CriteriaBuilder builder) -> {
            if (businessListNumber == null) {
                return null;
            }
            Join<Dokument, BusinessList> businessListJoin = root.join("businessList", JoinType.INNER);
            return builder.equal(businessListJoin .get("businessListNumber"), businessListNumber);
        };
    }

不幸的是,我不允许在这里使用双向关系,我也没有尝试建立这个。
你能帮我吗?:)

fbcarpbf

fbcarpbf1#

尝试创建两个不同的规范,一个用于join,另一个用于where子句,而不是创建一个规范。
使用businesslist存储库您应该可以得到预期的查询

public static Specification<BusinessList> joinDocument() {
    return (root, query, builder) -> {           
        root.join("dokuments", JoinType.INNER);
        return null;
    };
}

public static Specification<BusinessList> businessListNumberEqual(String businessListNumber) {
    return (root, query, builder) -> {
        if (businessListNumber == null) {
            return null;
        }            
        return builder.equal(root.get("businessListNumber"), businessListNumber);
    };
}

 Specification.where(joinDocument()).and(businessListNumberEqual("businessListNumber"));

查看git上的代码https://github.com/chetanchilhate/spring-data-jpa-specification-join

相关问题