桃桃桃*_*桃桃子 6 java sql postgresql spring-data-jpa spring-boot
Spring Data Jpa 方法是这样的:
@Query("select pb.id,pp.max_borrow_amt,pp.min_borrow_amt
from product_loan_basic pb left join product_loan_price pp on pb.code=pp.product_code
where pb.code IN(?1) and pb.status='publish' order by ?2 ",
nativeQuery = true)
List<Object[]> findByCodesIn(List<String> codes,String orderby);
Run Code Online (Sandbox Code Playgroud)
那么 order by 是“ max_borrow_amt desc ”,但这是无效的。
列表是无序的。
如果您使用 JPA 查询,则可以使用Sort作为查询方法的参数来定义排序顺序:
@Query("select m from Model m")
List<Model> getSortedList(Sort sort);
Run Code Online (Sandbox Code Playgroud)
然后,例如:
List<Model> models = getSortedList(Sort.by(Sort.Direction.DESC, "name"));
Run Code Online (Sandbox Code Playgroud)
但是 Spring Data JPA不能用于 Sort本机查询:
Spring Data JPA 目前不支持对原生查询进行动态排序,因为它必须操作声明的实际查询,而对于原生 SQL,它不能可靠地做到这一点。
但是,您可以改用Pageable及其实现PageRequest:
@Query(value = "select m.name as name from models m", nativeQuery = true)
List<ModelProjection> getSortedList(Pageable p);
Run Code Online (Sandbox Code Playgroud)
进而:
List<ModelProjection> modelNames = getSortedList(PageRequest.of(0, 1000, Sort.Direction.DESC, "name"));
Run Code Online (Sandbox Code Playgroud)
PS 代替Objects数组作为返回参数,最好使用投影,例如:
public interface ModelProjection {
String getName();
}
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下,好的做法是在查询中使用别名(即m.name as name)。它们必须与投影中的相应吸气剂相匹配。
| 归档时间: |
|
| 查看次数: |
5217 次 |
| 最近记录: |