2017-08-01 113 views
0

这是我的工作数据库设置:排序由相关特性

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

'select distinct f,b.status ....' –

回答

1

在这里已对f施加不同,因此不能有一些其他的列,以便通过。实际上,按项目排序必须在选择列表中。

那么,问题出在查询时,您可以删除,如果你确信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 
+0

这没有奏效。 java.lang.IllegalArgumentException:方法 – Benedictus

+0

的查询验证失败,它没有使用'with'包装,但返回两个值。所以我猜在包装器中有一个语法错误 – Benedictus

+0

好吧..我想你需要在查询注释中设置'nativeQuery = true'来使这个工作。例如'@Query(nativeQuery = true,value = << supply-query-string >>)' –

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