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

10 篇文章 0 订阅
5 篇文章 0 订阅
本文是SpringJPA学习教程的第二部分,主要介绍如何根据关键字进行查询。内容涵盖常用接口继承类,如Repository、JpaRepository、PagingAndSortingRepository的特性,以及如何通过自定义查询配置和方法实现关键字查询。示例展示了如何在接口中添加自定义查询方法,如根据姓名查询用户和获取不重复姓名的用户列表。
摘要由CSDN通过智能技术生成

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表达式
AndfindByNameAndEmailwhere u.name = ?1 and u.email = ?2
OrfindByNameOrEmailwhere u.name = ?1 or u.email = ?2
Is/EqualsfindByNameEqualswhere u.name = ?1
BetweenfindByBirthdayBetweenwhere u.birthday between ?1 and ?2
LessThanfindByAgeLessThanwhere x.age < ?1
LessThanEqualfindByAgeLessThanEqualwhere x.age <= ?1
GreaterThanfindByAgeGreaterThanwhere x.age > ?1
GreaterThanEqualfindByAgeGreaterThanEqualwhere x.age >= ?1
AfterfindByStartDateAfterwhere x.startDate > ?1
BeforefindByStartDateBeforewhere x.startDate < ?1
IsNullfindByNameIsNullwhere x.name is null
IsNotNull/NotNullfindByNameNotNullwhere x.name not null
LikefindByNameLikewhere x.name like ?1
NotLikefindByNameNotLikewhere x.name not like ?1
StartingWithfindByNameStartingWithwhere x.name like %?1
EndingWithfindByNameEndingWithwhere x.name like ?1%
ContainingfindByNameContainingwhere x.name like %?1%
OrderyByfindByAgeOrderByNameDescwhere x.age = ?1 order by x.name desc
NotfindByNameNotwhere x.name <> ?1
In/NotInfindByAgeIn(Collection ages)where x.age in ?1
True/FalsefindByActiveTruewhere x.active = true
IgnoreCasefindByNameIgnoreCasewhere UPPER(x.name) = UPPER(?1)

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值