这是我的工作数据库设置:
@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;
答案 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