关于JPA的@Query原生sql分页排序问题

使用JPA开发的过程中使用@Query注解使用原生sql查询数据,之前一直是按照时间倒叙来查询的,使用的为硬编码。

 @Query(value = "select * from view_hs_auction_hang_item where  " +
            " if(?1 is not null,item_code like CONCAT('%',?1,'%'),1=1)" +
            "and if(?2 is not null,item_name like CONCAT('%',?2,'%'),1=1)" +
            "order by show_time desc",countQuery = "" +
            "select count(1) from view_hs_auction_hang_item where  " +
            " if(?1 is not null,item_code like CONCAT('%',?1,'%'),1=1)" +
            " and if(?2 is not null,item_name like CONCAT('%',?2,'%'),1=1) "
           ,nativeQuery = true)
    Page<HsAuctionHangItem> findByLike(String itemcode, String itmeName, Pageable pageable);

之前一直是通过order by show_time desc 这种写法可以实现功能但是要将字段和排序做活的话,这种写法并不行。
使用@Query 的方法并不能在sql中排序,它的排序信息全部封装到分页的对象中pageable
前端传过来的排序字段都封装到这个集合中

{"sort":[{"direction":"DESC","property":"occurTime"}]}//前端传的字段
List<PageAndSortReq.Order> sort = req.getSort();
//这里是前端传的是实体类中的属性要获取对应数据库中的字段
	@Column(name = "firm_code")
	private String firmCode;

 Field field = ViewTqQueryFirmHoldDetail.class.getDeclaredField(order.getProperty());// 暴力获取private修饰的成员变量
 Column annotation = field.getAnnotation(Column.class);
 这样到数据库中对应的字段
 在封装到排序到集合中

这样就可以实现对应的功能了


版权声明:本文为weixin_44013783原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。