您的位置:首页 > 编程语言 > Java开发

关于springboot中JPA查询的一些问题

2020-03-06 17:17 525 查看

关于springboot中JPA查询的一些问题

初用JPA,感觉比较傻瓜式,一些复杂的查询以及自定义查询无法实现,结果证明。。。是我不会用(自嘲一下)下面,将归纳下我遇到的一些问题,并附上解决方法
一、关于Pageable的使用
在2.2.3版本中,PageRequest提供了静态方法,所以new的骚操作就没办法进行了,需要注意!附上代码
Pageable pageable = PageRequest.of(1, 20, Sort.DEFAULT_DIRECTION.DESC, "createTime");
需要说明的是,其中排序的字段可以是多个,最终以字符串进行参数传递即可

二、sql脚本的编写
这里需要着重注意的是,如何对空值进行过滤,网上查到了两种方式,一种是使用hql的形式进行查询与判断,另一种是编写原生sql进行查询与判断,用关键字**nativeQuery**进行区分,为true时表示原生sql。
1、hql形式
@Query(value = "select table from Table table "
+ "where ( ?1 is null or table.a = ?1 ) "
+ "and ( ?2 is null or table.b like %?2% ) "
+ "and ( ?3 is null or table.c = ?3) "
+ "order by ?#{#pageable} ", countQuery = "select table from Table table "
+ "where ( ?1 is null or table.a = ?1 ) "
+ "and ( ?2 is null or table.b like %?2% ) "
+ "and ( ?3 is null or table.c = ?3) ")
List<Table> findTableList(String a, String b, String c, Pageable pageable);
① 需要注意的是,这里用到了模糊查询,在参数两侧根据需要加上“%”;
② a,b,c参数需要在方法中进行一次判断,不能传一个空值;
2、sql形式
@Query(value = "select * from table where "
+ "if(?1 !='',x1=?1,1=1) "
+ "and if(?2 !='',x2=?2,1=1) "
+ "and if(?3 !='',x3=?3,1=1) ", nativeQuery = true)
List<Table> findTableList(String a, String b, String c);
这种方式目前没有使用过,所以暂时不做注释,之后用到了再进行修改。
  • 点赞
  • 收藏
  • 分享
  • 文章举报
qq_22020393 发布了3 篇原创文章 · 获赞 0 · 访问量 32 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: