按关系属性排序

时间:2017-08-01 04:33:25

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

这是我的工作数据库设置:

@Entity
class Foo {
    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "FOO_ID")
    private Set<Bar> bars;

//...

}

@Entity
class Bar {
    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    @Column(name = "STATUS")
    private String status;
    //...
}

FooRepository扩展了CrudRepository {

@Query("select distinct f from Foo f left join f.bars b where b.status = :status ")
public Page<Bar> findByBarStatus(@Param("status") BarStatus status, Pageable pageable);

}

我希望能够按Bar.status对此查询进行排序,以下是我尝试更改查询的方式:

@Query("select distinct f from Foo f left join f.bars b where b.status = :status order by b.status desc")
public Set<Bar> findByBarStatus(@Param("status") BarStatus status);

然而,这会导致sql语法错误:

org.h2.jdbc.JdbcSQLException: Order by expression "BARS1_.STATUS" must be in the result list in this case;

2 个答案:

答案 0 :(得分:2)

此处您已在f上应用了distinct,因此您不能按顺序使用其他列。实际上,逐项清单必须在选择列表中。

所以,问题出在查询中,如果您确定f将是唯一的(但事实并非我)或您可以尝试with子句,

with temp as  
(select distinct f, b.status 
 from Foo f left join f.bars b 
 where b.status = :status order by b.status desc) 
select f from temp

答案 1 :(得分:0)

您必须在查询选择语句中调用b.status,如下面的查询。

    select DISTINCT(f), b.status from Foo f
 LEFT JOIN f.bars b where b.status = :status order by b.status desc