SpringData - 通过连接表进行排序,在第一个表

时间:2017-09-07 13:52:45

标签: java spring spring-data spring-data-jpa

PersonEntityoneToManyAddressEntity的关系。

此外,我已经定义了Specification<PersonEntity>Pageable个对象。 我的可分页对象按addresses.city排序。

没有排序我有适当的结果,但如果按城市排序我在返回页面中有重复。如果我添加到我的规范query.distinct(true),它在运行时会失败,因为sort by不在选择结果中。

基本上我只需要在第二个表(地址)中加入第一个结果或以某种方式删除重复项。怎么做?

修改

personRepository.findAll(specification, pageable);
// specification contains only (root, query, builder) -> builder.equal(root.get(PersonEntity_.orgId), orgId)
// pageable - sort asc, addresses.city, page 0, pagesize 100

当然问题是,在我按地址列表排序之后,当Person有多个地址时,它会执行LEFT OUTER JOIN,这会产生两个结果。

EDIT2:

github https://github.com/querydsl/querydsl/issues/1150中有一个未解决的问题 我们对jparepositories有什么解决方法吗?

2 个答案:

答案 0 :(得分:0)

您尝试过使用

@QueryHints(value = {
        @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_PASS_DISTINCT_THROUGH, value = "false")
})

正如名称​​ HINT_PASS_DISTINCT_THROUGH 所说,它不会将distinct关键字传递给SQL,并且hibernate将注意过滤差异。

例如

@QueryHints(value = {
        @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_PASS_DISTINCT_THROUGH, value = "false")
})
@Query("select distinct p from Product p left join fetch p.reviews re order by re.text desc")
List<Product> findAll();

产生以下SQL

select
    product0_.id as id1_1_0_,
    reviews1_.id as id1_2_1_,
    product0_.name as name2_1_0_,
    reviews1_.product_id as product_3_2_1_,
    reviews1_.text as text2_2_1_,
    reviews1_.product_id as product_3_2_0__,
    reviews1_.id as id1_2_0__ 
from
    product product0_ 
left outer join
    review reviews1_ 
        on product0_.id=reviews1_.product_id 
order by
    reviews1_.text desc

答案 1 :(得分:0)

遇到类似问题,为了避免结果集中出现重复记录,请使用 @Where with 子句。

使用类似的东西

@OneToMany
@Where(clause="<column name of Address that will give you distinct result>")
List<Address> addresses;

在运行时,where 子句被附加到左外连接后的查询中。

希望它有助于解决您的查询!...