SpringJpa学习教程-02根据关键字查询

SpringJpa学习教程-02根据关键字查询

常用的接口继承类

Repository:无任何方法

CrudRepository:具有简单的一些增删改查的方法

PageAndSortingRepository:具有一些简单的分页查询功能和排序功能

JpaRepository:继承了PagingAndSortingRepository,对它的方法进行了一些扩展,
以下是提供的一些方法,可以看到支持批量更新和删除

<S extends T> List<S> saveAll(Iterable<S> entities);
<S extends T> S saveAndFlush(S entity);
void deleteInBatch(Iterable<T> entities);

自定义查询配置

JpaApplication中添加注解
@EnableJpaRepositories(queryLookupStrategy = QueryLookupStrategy.Key.CREATE_IF_NOT_FOUND)

解释:

@EnableJpaRepositories表示启用自定义查询

查询策略有三种:

  • CREATE :直接根据方法名进行创建,如果方法名不符合规则则启动时报错
  • USE_DECLARED_QUERY:注解方式创建
  • CREATE_IF_NOT_FOUND:两种方式的结合,先使用注解扫描,没扫描到,则使用Create创建

自定义查询

我们在UserRepository中添加以下方法,分别是根据姓名查询所有的用户和查询出不带重复姓名的用户列表

List<User> findUsersByName(String name);

List<User> findDistinctByName(String name);

UserController中添加以下方法

@GetMapping(path = "/byName")
@ResponseBody
public List<User> findByName(@RequestParam(value = "name") String name) {
	return userRepository.findUsersByName(name);
}
@GetMapping(path = "/findNameWithDistinct")
@ResponseBody
public List<User> findNameWithDistinct(@RequestParam(value = "name") String name) {
	return userRepository.findDistinctByName(name);
}

启动SpringBoot进行访问,可知方法生效了.

关键字列表

关键字 示例 JPQL表达式
And findByNameAndEmail where u.name = ?1 and u.email = ?2
Or findByNameOrEmail where u.name = ?1 or u.email = ?2
Is/Equals findByNameEquals where u.name = ?1
Between findByBirthdayBetween where u.birthday 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 findByNameIsNull where x.name is null
IsNotNull/NotNull findByNameNotNull where x.name not null
Like findByNameLike where x.name like ?1
NotLike findByNameNotLike where x.name not like ?1
StartingWith findByNameStartingWith where x.name like %?1
EndingWith findByNameEndingWith where x.name like ?1%
Containing findByNameContaining where x.name like %?1%
OrderyBy findByAgeOrderByNameDesc where x.age = ?1 order by x.name desc
Not findByNameNot where x.name <> ?1
In/NotIn findByAgeIn(Collection ages) where x.age in ?1
True/False findByActiveTrue where x.active = true
IgnoreCase findByNameIgnoreCase where UPPER(x.name) = UPPER(?1)

以上均为find系列的前缀,与find相同的前缀还有read``get``query``stream
也就是说,findByName=getByName等同

计数系列:count
存在系列:exists
删除系列:delete/remove

猜你喜欢

转载自blog.csdn.net/qq_32409957/article/details/86586582