Spring 加强版 ORM 框架 Spring Data 入门

概述

Spring 中有多种操作数据库的方式,通常来说我们优先选择的是 MyBatis,如果业务比较简单我们还会使用 JdbcTemplate,另外据说国外使用 spring-data-jpa 比较多?

最近发现了 Spring 中另一款操作关系型数据库的框架,相对 JdbcTemplate 来说使用上又简化了一些,它也是 Spring Data 大家族中的一员,即 spring-data-jdbc,分享给大家。

由于 Spring Data 内容较多,分为上下两篇介绍,本篇我们先介绍一些 Spring Data 的基础知识,下篇再介绍 spring-data-jdbc。

模块划分

Spring Data 大家族中有一些每个模块都要遵守的规范,这些规范定义在 spring-data-commons 模块中,理解这些规范后,切换到具体的实现模块能很快上手。这些模块之间的关系可以用下面的图来表示。
在这里插入图片描述

核心概念

Spring Data 的实现借鉴了领域驱动设计 DDD 的设计原则,规范中的核心概念是 Repository,它表示一个管理 Domain 的仓库,所有的数据库操作都要经过 Repository。
在这里插入图片描述

Domain 则表示数据库表在 Java 中的映射,每个 Domain 都必须有一个唯一的 ID 标识,可以通过 @Id 注解标识。例如,我们有一个关系型数据库表 user,结构如下:

create table user
(
    id          bigint unsigned auto_increment
        primary key,
    username    varchar(20)  null,
    password    varchar(20)  null
);

可以使用如下的类表示。

@Data
public class User {

    @Id
    private Long id;

    private String username;
    
    private String password;
}

Repository 作为一个接口,接收具体的 Domain 类型和 Domain 的 ID 类型作为泛型参数。接口定义如下。

public interface Repository<T, ID> {
}

自定义 Repository 接口

Repository

Repository 只是一个标记接口,对于开发者来说需要提供一个 Repository 的子接口,然后再定义一些操作数据库的方法。例如,针对上面的 Domain User 我们可以定义一个这样的 Repository

public interface UserRepository extends Repository<User, Long> {

    Optional<User> findById(Long id);
}

Spring Data 实现模块会根据特定的语法规则将方法解析为具体的查询方式,例如对于 spring-data-jdbc 模块来说,上面的 findById 可以解析为如下 SQL。

select id,username,password from user where id = ?

如果多个 Domain 相同的操作比较多,我们还可以将方法定义到一个 BaseRepository 中,示例如下。

@NoRepositoryBean
public interface BaseRepository<T, ID> extends Repository<T, ID> {

    Optional<T> findById(ID id);
}

public interface UserRepository extends BaseRepository<User, Long> {    
}

创建 Repository 实例

Spring Data 实现模块会为我们定义的接口创建代理对象并将这个代理对象注册为 bean,为了避免将 BaseRepository 注册为 bean,我们需要为自定义的 BaseRepository 添加注解 @NoRepositoryBean

最后,我们还需要使用 @EnableXXXRepository 注解开启接口注册为 bean 的功能,以 spring-data-jdbc 为例,如下。

@EnableJdbcRepositories(basePackages = "com.zzuhkp.repository")
@Configuration
public class JdbcConfig {
}

basePackages 属性指定 repository 的接口位置,默认为注解所在类的包。

CrudRepository

Spring Data 为我们预置了一些 Repository 的子接口,最常用的是 CrudRepository ,它定义了增删改查的基本方法,接口定义如下。

@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {
	<S extends T> S save(S entity);
	<S extends T> Iterable<S> saveAll(Iterable<S> entities);
	
	Optional<T> findById(ID id);
	boolean existsById(ID id);
	Iterable<T> findAll();
	Iterable<T> findAllById(Iterable<ID> ids);
	long count();
	
	void deleteById(ID id);
	void delete(T entity);
	void deleteAll(Iterable<? extends T> entities);
	void deleteAll();
}

其中 savesaveAll 方法根据是否为新记录进行添加或更新操作。

PagingAndSortingRepository

如果我们需要进行分页查询或排序,我们还可以继承 PagingAndSortingRepository 接口,这个接口的定义如下。

@NoRepositoryBean
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
	Iterable<T> findAll(Sort sort);

	Page<T> findAll(Pageable pageable);
}

Sort 声明方式如下。

Sort sort1 = Sort.by("username").ascending().and(Sort.by("password").descending());

Sort.TypedSort<User> sort = Sort.sort(User.class);
Sort sort2 = sort.by(User::getUsername).ascending().and(sort.by(User::getPassword).descending());

Pageable 声明方式如下。

Pageable page = PageRequest.of(0, 10, sort1);

📢 注意Pageable 的页码是从 0 开始的。

@RepositoryDefinition

如果我们不想继承 Spring Data 提供的接口,我们还可以在自己的接口上标注 @RepositoryDefinition 注解指定 Domain 类型和 ID 类型。如下所示。

@RepositoryDefinition(domainClass = User.class, idClass = Long.class)
public interface UserRepository {

    Optional<User> findById(Long id);
}

自定义 Repository 接口实现

上面定义的 Repository 接口方法都必须借助 Spring Data 自身的实现,Spring Data 还允许我们定义自己的 Repository 实现。

首先定义一个接口。

package com.zzuhkp.demo.repository;

public interface CustomizedUserRepository {

    int save(User entity);
}

然后定义 Repository 实现。

package com.zzuhkp.demo.repository;

@Component
public class CustomizedUserRepositoryImpl<T> implements CustomizedUserRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int save(User entity) {
        String sql = "insert into user(username,password) values(?,?)";
        String username = entity.getUsername();
        String password = entity.getPassword();

        return jdbcTemplate.update(sql, username, password);
    }
}

然后我们的 Repository 继承自定义的 CustomizedUserRepository 接口即可。

public interface UserRepository extends Repository<User, Long>, CustomizedUserRepository {
    
}

📢 注意:Spring Data 只会在自定义 Repository 接口所在包下面查找名称为 XxxImpl 的实现,如果有多个实现会使用名称为 xxxImpl 的 bean。如果不想使用 Impl 后缀,可以通过 @EnableXXXRepository.repositoryImplementationPostfix 注解属性修改。

@EnableJdbcRepositories(repositoryImplementationPostfix = "Impl")
@Configuration
public class JdbcConfig {
}

自定义 Repository 方法

Spring Data 实现模块有两种方式根据方法确认具体的数据库操作,第一种是解析 Repository 方法名,第二种是解析 Repository 方法上的注解。不同的 Spring Data 实现模块使用的注解可能有所不同,但是对于方法名的解析是类似的。

语法规则

Repository 的方法名可以分为 subject 部分和 predicate 部分,例如 find...by... 中的 find 后面的部分表示要查询的 subject,by 后面的部分表示查询条件 predicate。

find 后还可以跟 distincttopfirst 等词语限制查询结果,by 后面可以紧跟 Domain 类的属性名和一些修饰词进行限定。下面是一些示例,可以很容易看明白。

public interface UserRepository extends PagingAndSortingRepository<User, Long> {

   // 查询第一个满足条件的 User
   User findFirstByUsername(String username);

   // 查询前 10 个满足条件的 User
   List<User> findTop10ByUsernameOrderByIdAsc(String username);

   // 根据用户名查询用户,忽略用户名大小写
   List<User> findDistinctByUsernameIgnoreCase(String username);
}

关键字比较多,不同的实现模块可能支持的关键字有所不同,对于 spring-data-jdbc 来说可以参考 Spring Data Repository 方法关键字 查询支持的关键字。

接入 Spring Data 时, Intellij Idea 还会有代码提示,如果你还在用 eclipse,不妨试试 Idea ?
在这里插入图片描述

特殊参数

PagingAndSortingRepository 接口方法支持 PageableSort 作为方法参数,如果不想进行分页或者排序,可以传入 Pageable.unpaged()Sort.unsorted()

返回类型

Spring Data Repository 支持多种方法的返回值,具体如下。

  • 基本类型及其包装类型。

  • Domain 具体类型以及 Optional<Domain>。。

  • 集合/迭代类型:List<Domain>Set<Domain>Iterable<Domain>Stream<Domain>,除此之外还支持 Spring Data 内置的 Streamable<Domain> 类型。

  • 异步结果:FutureCompletableFutureListenableFuture,需要 @EnableAsync 开启异步,并在方法上添加 @Async 注解。

Spring Data 多模块

有时候,我们可能需要使用多个 Spring Data 的模块,例如操作关系型数据库我们可以使用 spring-data-jpa,操作 MongoDB 数据库我们可以使用 spring-data-mongodb,这个时候必须有一种方式能够区分不同类型的 Repository,具体来说有两种方式。

1. 根据 Respsitory 类型区分

如果自定义的 Repository 实现了某个模块特有的接口,可以根据这个特有的接口创建代理。例如:

public interface UserRepository extends JpaRepository<User, Long> { 
}

2. 根据 Domain 注解区分
不用的 Spring Data 模块在 Domain 类型上使用的注解有所不同,如果使用了某个模块特有的注解,也可以识别出 Repository 的类型。例如:

@Data
@Entity
public class User  {
    
    @Id
    private Long id;

    private String username;

    private String password;
    
}

@Entity 是 JPA 特有的注解,因此可以识别 UserRepositoryspring-data-jpa 模块的 Repository。

3. basePackages 区分
有时候我们定义的 Repository 接口可能没继承某个模块特有的注解,并且 Domain 类上混合使用了多个模块的注解,这个时候怎么办呢?

放大招,在 @EnableXXXRepository 注解的 basePackages 属性中指定 Repository 所在的具体包名,这时候 Spring Data 就可以识别出 Repository 接口是哪个模块下的了。

@EnableJdbcRepositories(basePackages = "com.zzuhkp.repository")

事件发布

Repository 管理的 Domain 又被称为聚合根,聚合根可以发布一些 Domain 事件。

Spring Data 支持事件发布的注解是 @DomainEvents,可以在聚合根的方法上添加这个注解,当调用 savesaveAlldeletedeleteAll 时会调用注解标注的方法。例如:

@Data
public class User {
    
    private Long id;

    @DomainEvents
    Collection<UserEvent> domainEvents() {
        System.out.println("发布事件");
        return Collections.singleton(new UserEvent().setId(this.getId()));
    }
    
}

如果发布事件时使用了一些资源,还可以使用 @AfterDomainEventPublication 标注的方法在事件发布后清理一些资源。

@Data
public class User {
    
    @AfterDomainEventPublication
    void callbackMethod() {
        System.out.println("事件已发布");
    }   
}

怎么接收这些事件呢?直接使用 Spring 提供的事件监听器即可。

@EventListener
public void event(UserEvent event) {
    System.out.println("接收到 UserEvent 事件");
}

感觉这个特性用的应该不多,大家有个印象即可。

Spring Web 支持

Spring Data 提供了对 Spring MVC 的支持,可以通过 @EnableSpringDataWebSupport 注解开启。提供的功能特性如下:

1. Domain 解析

开启 Spring Web 支持后 Spring Data 会注册一个 DomainClassConverter 类型的转换器,将路径变量或请求参数转换为 handler 方法中的 Domain 参数值。

@GetMapping("/user/{id}")
User get(@PathVariable("id") User user) {
    return user;
}

2. Pageable、Sort 解析

开启 Spring Web 支持后 Spring Data 会为类型为 PageableSort 的 handler 方法参数分别注册一个参数解析器,具体为 PageableHandlerMethodArgumentResolverSortHandlerMethodArgumentResolver

@GetMapping("/user/list")
List<User> list(Pageable pageable) {
    return null;
}

客户端传哪个参数才能解析呢?先看一个示例。

page=0&size=10&sort=username,asc&sort=password,desc,ignorecase
  • page 表示页码,从 0 开始;
  • size 表示页大小,默认为 10。
  • sort 用于排序,格式为 property(,asc|desc)(,ignorecase), property 为属性名,asc 表示升序, desc 表示降序,ignorecase 表示忽略大小写。

总结

Spring Data 功能特性 = 通用功能 + 各模块独有功能,本篇主要总结了 Spring Data 的通用功能特性部分,这些基础知识适用于 Spring Data 的各模块,了解这些内容后,再学习具体模块能很快上手了。后面会对具体模块进行介绍。

  • 30
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 28
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 28
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大鹏cool

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值