MySQL动态条件查询,可用于JPA自定义SQL多条件查询
程序员文章站
2022-04-21 15:43:50
...
今天分享一个mysql的小技巧。在使用JPA操作数据库的时候,常常要自定义SQL,但是有很多条件是不确定的,所以要通过动态判断。现在太晚了,我先把代码贴出来,JPA带分页查询,供大家参考,等以后有时间了,我在来详细说明。
@Query( value = "SELECT * FROM result a, sheet b, user c, users d, type e\n" +
" WHERE a.task_sheet_id = b.id AND b.test_type_id = e.id AND b.test_user_id = c.id AND c.user_id = d.id " +
" AND if(:code = '' OR :code is null ,1=1, b.code like %:code%) " +
" AND if(:name = '' OR :name is null ,1=1, d.`name` like %:name%) " +
" AND if(:status = '' OR :status is null ,1=1, b.start_status = :status) ",
countQuery = "SELECT count(*) \n"+
"FROM test_result a, task_sheet b, user_test c, admin_users d, test_type e\n" +
"WHERE a.task_sheet_id = b.id AND b.test_type_id = e.id AND b.test_user_id = c.id AND c.user_id = d.id "+
" AND if(:code = '' OR :code is null ,1=1, b.code like %:code%) " +
" AND if(:name = '' OR :name is null ,1=1, d.`name` like %:name%) " +
" AND if(:status = '' OR :status is null ,1=1, b.start_status = :status) ",
nativeQuery = true)
Page<Map> findTestResultGetTaskAll(Object code,Object name,Object status,Pageable pageable);