spring boot jpa repository 支持的方法名

Supported keywords inside method names
Keyword Sample JPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstname,findByFirstnameIs,findByFirstnameEquals … where x.firstname = 1?
Between findByStartDateBetween … where x.startDate between 1? and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1(parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1(parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1(parameter bound wrapped in%)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection<Age> ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection<Age> age) … where x.age not in ?1
True findByActiveTrue() … where x.active = true
False findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)
Top findTop7ByDeletedAndProjectStatus
Top 1 findFirstByOrderById
使用@Query
可以在自定义的查询方法上使用@Query来指定该方法要执行的查询语句,比如:
@Query(“select o from UserModel o where o.uuid=?1”)
public List<UserModel> findByUuidOrAge(int uuid);
注意:
1:方法的参数个数必须和@Query里面需要的参数个数一致
2:如果是like,后面的参数需要前面或者后面加“%”,比如下面都对:
@Query(“select o from UserModel o where o.name like ?1%”)
public List<UserModel> findByUuidOrAge(String name);
@Query(“select o from UserModel o where o.name like %?1”)
public List<UserModel> findByUuidOrAge(String name);
@Query(“select o from UserModel o where o.name like %?1%”)
public List<UserModel> findByUuidOrAge(String name);
当然,这样在传递参数值的时候就可以不加‘%’了,当然加了也不会错
还可以使用@Query来指定本地查询,只要设置nativeQuery为true,比如:
@Query(value=”select * from tbl_user where name like %?1″ ,nativeQuery=true)
public List<UserModel> findByUuidOrAge(String name);
注意:当前版本的本地查询不支持翻页和动态的排序
使用命名化参数,使用@Param即可,比如:
@Query(value=”select o from UserModel o where o.name like %:nn”)
public List<UserModel> findByUuidOrAge(@Param(“nn”) String name);
同样支持更新类的Query语句,添加@Modifying即可,比如:
@Modifying
@Query(value=”update UserModel o set o.name=:newName where o.name like %:nn”)
public int findByUuidOrAge(@Param(“nn”) String name,@Param(“newName”) String newName);
注意:
1:方法的返回值应该是int,表示更新语句所影响的行数
2:在调用的地方必须加事务,没有事务不能正常执行

发表评论

电子邮件地址不会被公开。 必填项已用*标注