在使用spring data的jpa过程中碰到一个问题,@Query中写的原生的sql语句无法动态实现,这是最扯的事情。我现在要添加搜索条件,字段都不固定,这东西也无法往上面添加,业务复杂也根本无法靠框架自动生成,只能自己写sql,自己写sql还不能动态!!!
用jpa要么用EntityManager,用这种实在难受,好了,来写下思路把,其实就是靠sql语句实现,想办法来让条件生效或者不生效。来个例子
SELECT * FROM table WHERE (id = null OR null IS NULL)
如果传入的参数是null条件就不生效,因为后面的null is NULL得出的结果是true,所以不会生效。如果不是null那么id=xxx条件就会生效xxx是不等于null的,所以OR后面条件不生效,前面条件生效,有个BUG就是如果你想筛选字段等于NULL的,就会出现。。。。
好了思路就是这,自己看着sql进行调整把。
另外我记得还可以靠if条件来判断条件生效不生效的。也可以去实验下。
来个代码例子看看
@Query(value = "SELECT a.*," + "FROM a LEFT JOIN b ON a.id= b.id" + "LEFT JOIN c ON a.id= c.id" + "WHERE a.use_status in(1,2) AND b.use_status=1 AND c.use_status=1 " + "AND (a.id= ?1 OR ?1 IS NULL) " + "AND (a.xxx= ?2 OR ?2 IS NULL) " + "AND (a.ccc= ?3 OR ?3 IS NULL) " + "AND (a.ddd= ?4 OR ?4 IS NULL) ", countQuery = "SELECT COUNT(1) FROM a LEFT JOIN b ON a.id= b.id" + "LEFT JOIN c ON a.id= c.id" + "WHERE a.use_status in(1,2) AND b.use_status=1 AND c.use_status=1 " + "AND (a.id= ?1 OR ?1 IS NULL) " + "AND (a.xxx= ?2 OR ?2 IS NULL) " + "AND (a.ccc= ?3 OR ?3 IS NULL) " + "AND (a.ddd= ?4 OR ?4 IS NULL) ", nativeQuery = true) Page<Map<String, Object>> getList(Pageable pageable, Long id, Long xxx, Long ccc, Integer ddd);