按照SpringData命名规范
1.查询方法:find| read| get开头 + By
关键字: 涉及查询条件时,条件属性用关键字连接,要注意的是条件属性首字母大写
And,Or,Between,LessThan,GreaterThan,After ,Before,IsNull,IsNotNUll,NotNull
Like, NotLike,StartingWith,EndWith,Containing,OrderBy,Not ,In,NotInt,True,False
eg:Select * from user where id=? -> getById(Integer id)
eg: Select * from user where username=? and pws=? -> findByUsernameAndPws(String name , String pws)
eg :select * from user -> findUser()
eg:select count(*) from user ->count()
eg:select* from user where between age ? and? -> getByAgeBetween(int a,int b)
eg:select* from user where age >? and age<=? -> getByAgeGreaterThanAndAgeLessThan(int a,int b)
eg:select * from user where age is null and pws=? ->getByAgeIsNullAndPws
eg: select * from user where username like 'hu%' ->getByUserNameLike(String nameLike)
->getgetByUserStartingwith(String nameLike)
eg:select * from user order by id desc ->getByOrderByIdDesc()
eg: select * from user where age in (1,3,4) ->getByAgeIn(Collection age );
2.LessThan,GreaterThan,After ,Before 没有等号
Like,NotLike :前后都不加% 传值时自己加
StartingWith:结尾加%
EndingWith:开头加%
Containning:左右都加%
3.级联查询
包含外键的一方(被维护方),不包含(维护放),维护方的外键上添加注解@Transient
被维护方上加注解@OneToOne(targetEntity=User.class)和@JoinColum(name="id",unique=true)
维护方@OneToOne(mappedBy="Info")
eg: select *from user u left join info i on u.id=i.uid where i.telphone=? ->getByInfoTelphone(String number)
当级联查询条件与主表属性冲突用_分隔 getByInfo_Telphone(String number)
4.@Query注解
加上这个注解表明不按照定义规范命名
@Query(value="From User where age in (Select max(age) from user)")
@Query(value="Select * From User where age in (Select max(age) from user)",nativeQuery=true)
nativeQuery=true 本地sql方法查询
传参:1.?占位符的方式默认左侧是1
@Query(value="From user where username=?1 And pwd=?2")
public List
2.:name 命名方式 通过@Param("")指定参数
@Query(value="From user where username=:username And pwd=: pwd")
public List
5.@Modifying注解
@Query+@Modifying可以定义个性化更新操作,调用的地方必须加事务,没有事务不能正常进行
修改sql
@Query(value="update user set username=:user where id =:id")
@Modifying
@Transactional
public int updateById(@Param("username")String username , @Param("id") int id)
6.CrudRepository接口
save(T t) 不需要加事务---->insert 单个
save(Entities e) ------->insert批量添加
区别:save(Entities e) 批量添加时一旦失败都会回滚
findOne(Integer id) 根据主键查出
exists(Integer id) 查询是否存在