gpt4 book ai didi

java - 按关系属性排序

转载 作者:行者123 更新时间:2023-11-30 02:26:51 24 4
gpt4 key购买 nike

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

@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;

最佳答案

在这里,您已在 f 上应用了不同,因此您不能有其他列作为排序依据。实际上,order by item 必须存在于选择列表中。

所以,问题出在查询中,如果您确定 f 是唯一的(但我猜不是这种情况),您可以删除 unique ,或者您可以尝试 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

关于java - 按关系属性排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45429024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com