参考文章:SpringBoot | JPA基本查询及多条件查询,参数为空判断
关键字 方法命名 sql where字句
And findByNameAndPwd where name= ? and pwd =?
Or findByNameOrSex where name= ? or sex=?
Is,Equals findById,findByIdEquals where id= ?
Between findByIdBetween where id between ? and ?
LessThan findByIdLessThan where id < ?
LessThanEquals findByIdLessThanEquals where id <= ?
GreaterThan findByIdGreaterThan where id > ?
GreaterThanEquals findByIdGreaterThanEquals where id > = ?
After findByIdAfter where id > ?
Before findByIdBefore where id < ?
IsNull findByNameIsNull where name is null
isNotNull,NotNull findByNameNotNull where name is not null
Like findByNameLike where name like ?
NotLike findByNameNotLike where name not like ?
StartingWith findByNameStartingWith where name like ‘?%’
EndingWith findByNameEndingWith where name like ‘%?’
Containing findByNameContaining where name like ‘%?%’
OrderBy findByIdOrderByXDesc where id=? order by x desc
Not findByNameNot where name <> ?
In findByIdIn(Collection<?> c) where id in (?)
NotIn findByIdNotIn(Collection<?> c) where id not in (?)
True findByAaaTue where aaa = true
False findByAaaFalse where aaa = false
IgnoreCase findByNameIgnoreCase where UPPER(name)=UPPER(?)
@Query(value = "select * from people where if(?1 !='',name like concat('%',?1,'%'),1=1) and if(?2 !='',sex=?2,1=1)"+
" and if(IFNULL(?3,'') !='',age=?3,1=1) and if(IFNULL(?4,'') !='',num=?4,1=1) ",nativeQuery = true)
List<People> find(String name,String sex,Integer age,Integer num);
备注:
nativeQuery = true
的含义是使用原生SQL,即注解中的SQL语句会生效,false的话就不会生效。?1、?2、?3、?4
的意思是代表方法中的第几个参数。like concat('%', ?1, '%')
if(?1 !='',name like concat('%',?1,'%'),1=1)
代表传入的参数name如果不为""(Spring类型空是""而不是null)将参数传入name,如果为空时显示1=1 代表参数为真,对查询结果不产生作用。IF 的语法满足mysql的基本语法,IF(expr1,expr2,expr3)
, 如果 expr1 为真(expr1 <> 0 以及 expr1 <> NULL),那么 IF() 返回 expr2,否则返回expr3if(IFNULL(?3,'') !='',age=?3,1=1)
表示如果传入的年龄是null,则替换成空字符串,然后判断是否为空,不为空则将参数传入age,否则忽略不对查询结果产生影响。IFNULL 是mysql中的一个函数,这个函数一般用来替换 NULL 值的。IFNULL(value1,value2)
,判断value1是否为null,如果为null则用value2替换。@Query(value = "select * from xxx where if(?1 !='',x1=?1,1=1) and if(?2 !='',x2=?2,1=1)" +
"and if(?3 !='',x3=?3,1=1) ",nativeQuery = true)
List<XXX> find(String X1,String X2,String X3);
@Query(value = "SELECT ds.*,us.username,dept.deptname FROM core_dm_datasetinfo ds " +
"LEFT JOIN mds_ds_user us ON us.pkid = ds.userid " +
"LEFT JOIN mds_ds_department dept ON dept.deptnumber = ds.departid " +
"and if(IFNULL(:userId,'') != '', ds.userid = :userId, 1=1) " +
"and if(IFNULL(:departNumber,'') != '', ds.departid like CONCAT('',:departNumber,'%'), 1=1) " +
"and if(IFNULL(:basedbId,'') != '', ds.basedbid = :basedbId, 1=1) ",
nativeQuery=true
)
List<Map<String, Object>> findDatsetInfo1(@Param(value = "userId")String userId,
@Param(value = "departNumber")String departNumber,
@Param(value = "basedbId")String basedbId);