![](/img/trans.png)
[英]Spring Data JPA @Query annotation, nativeQuery = true,
[英]Spring data JPA nativeQuery order by is invalid
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);
如果您使用JPA查詢,則可以使用Sort作為查詢方法的參數來定義排序順序:
@Query("select m from Model m")
List<Model> getSortedList(Sort sort);
然后,例如:
List<Model> models = getSortedList(Sort.by(Sort.Direction.DESC, "name"));
但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);
然后:
List<ModelProjection> modelNames = getSortedList(PageRequest.of(0, 1000, Sort.Direction.DESC, "name"));
PS而不是Object
s數組作為返回參數,最好使用投影 ,例如:
public interface ModelProjection {
String getName();
}
請注意,在這種情況下,最好的做法是在查詢中使用別名(即m.name as name
)。 它們必須與投影中的相應吸氣劑相匹配。
感謝大家! 我的問題已經解決了。
如果你想使用Spring數據jpa nativeQuert&Sort,你應該這樣做:
@Query(value =“select pb.id,pp.max_borrow_amt from product_loan_basic pb left join product_loan_price pp on pb.code = pp.product_code ORDER BY?#{pageable}”,countQuery =“select count(*)from product_loan_basic” ,nativeQuery = true)頁面findAllProductsAndOrderByAndSort(可分頁可分頁);
?#{#pageable}是必需的,並且需要countQuery。
Pageable pageable = new PageRequest(0,1000,Sort.Direction.DESC,"id");
然后結果排序
我無法使用@Param
Page<Object[]> findAllUsersdSort(@Param("firstName")String firstName,@Param("lastName")String lastName
Pageable pageable);
它抱怨
Mixed parameter strategies - use just one of named, positional or JPA-ordinal strategy
我不得不使用:
Page<Object[]> findAllUsersdSort(String firstName, String lastName, Pageable pageable);
我無法讓它僅適用於 H2。 不確定我是否需要物理數據庫。
我在第一名添加了 ?#{#pageable} 。
@Query(
value ="select * from person where firstName = ?1 and lastName = ?2 ORDER BY ?#{#pageable} ",nativeQuery = true)
它給了這個錯誤:
"could not prepare statement; SQL [select * from person where firstName = ? and lastName = ? ORDER BY ? , lastName desc, id desc]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement"
然后我嘗試刪除 ORDER BY ?#{#pageable} 並僅使用
@Query(
value ="select * from person where firstName = ?1 and lastName = ?2",nativeQuery = true)
它給了我新的錯誤
"could not prepare statement; SQL [select * from person where firstName = ? and lastName = ? order by lastName desc, id desc limit ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement"
不知道那個限制在哪里? 來自?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.