遇到的需求是这样的,要根据传入的用户id列表进行查询,不过数据库中还一个字段deleted标记用户是否删除,所以不能用自带的方法。
/**
* 查询教师详情信息列表
* @param pageable 分页器
* @param username 姓名
* @param zgh 职工号
* @param uidList 用户id列表
* @return 教师详情列表
* */
@Query(value = "select * from g_teacher_info " +
"where deleted=0 " +
"and if(?1!='',username like %?1%,1=1)"+
"and if(?2!='',zgh = ?2,1=1)"+
"and (coalesce(?3,null) is null or uid in (?3))",
nativeQuery = true
)
Page<TeacherInfo> findPageBySearch(Pageable pageable, String username, String zgh, List<Integer> uidList);
if
参数 类似于三元表达式,例if(?1!='',username like %?1%,1=1)
当第一个参数不为空的时候,返回username like %?1%
,否则返回 1=1
。此处Pageable
为自带分页类,不会进入到参数顺序中,所以?1对应的是第二个参数username。
coalesce
英文意思为合并。返回第一个非null的参数,这里作用是用来判断uidList参数是否为null,当uidList为null的时候,coalesce(?3,null) is null
成立,就不会判断后面的条件了。否则就等同于
and uid in (?3))
此处顺带提一下 and or 的捷径。表达式A&&B 中,只有当A为true情况下,才会去执行B表达式。
有时候可以当做空的判断。例 :
public void start() {
String id = null;
if(id==null && test()){
System.out.println("执行结束");
}
}
public boolean test(){
System.out.println("执行某个方法");
return true;
}
当我们id为null的时候,才会执行test方法。or
方法则相反, A||B 中,只有当A为false时,才会执行B表达式。例:
if(A==null || test()){
//巴拉巴拉
}
这种情况,只有当A不为null时候,才会执行test()方法