繁体   English   中英

Spring data JPA nativeQuery order by 无效

[英]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);

Spring Data JPA中的动态排序

如果您使用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");

然后结果排序

使用分页查看Spring Data和Native Query

我无法使用@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM