Spring Data JPA 教程: 介绍篇

来源:互联网 发布:淘宝npm镜像安装方法 编辑:程序博客网 时间:2024/06/06 20:19

Spring Data JPA 教程: 介绍篇

原文链接

使用Java Persistence API创建数据仓库(repositories)是一个繁琐的过程,耗费我们大量的时间,并且需要我们写一堆重复恶心的代码。我们可以使用下面这些步骤减少重复代码的编写:

  1. 创建一个抽象仓库基类(abstract base repository class),该类为entities提供CRUD的操作。
  2. 创建具体的仓库类(repository class)继承上面的抽象仓库基类(abstract base repository class)。

这种方法仍有问题,我们还是要写一些代码去创建数据库查询,并将他们关联起来。更糟糕的是,每次要做一次新的数据库查询,我们都要写一遍这样的代码。这种无脑代码会浪费我们大量的时间。

What would you say if I would tell you that we can create JPA repositories without writing any boilerplate code?(原文)

你很可能不相信,但是Spring Data JPA确实能帮我们解决这种问题。Spring Data JPA项目官网这样描述:

>实现一个应用程序的数据访问层的共走一直以来都很繁琐。为了执行简单的查询以及分页甚至于审计,我们要编写太多冗余的代码。Spring Data JPA目的是:尽可能地通过减少实际需要的代码,改善数据访问层的实现。作为一个开发者,你仅需编写你的仓库接口(repository interfaces),包括自定义的查询方法,然后Spring会自动的对你的那些接口进行实现。

这篇博客是对Spring Data JPA的一个介绍。我们将会学习Spring Data JPA究竟是什么,然后会对Spring Data仓库接口(repository interfaces)有个大概的了解。

下面我们就来开始。

什么是Spring Data JPA?

Spring Data JPA 不是一个JPA provider。它只是一个库/框架,在JPA provider的上面加了一个额外的抽象的一层。如果我们决定使用Spring Data JPA,我们的应用程序的数据存储层将包含以下的三层:

  • Spring Data JPA:提供创建JPA repositories的支持,需要我们去继承Spring Data repository interface
  • Spring Data Commons:为特定存储项目(Spring Data Projects)提供可共享的基础设施
  • JPA Provider 实现了Java Persistence API,如Hibernate等

下面一张图描述了数据存储层的结构:

开始的时候,Spring Data JPA让我们的应用变得复杂一些。它给我们的数据访问层增加了额外的一层,但同时也让我们少写了很多冗余代码。

这看起来设个不错的交易。对吗?

Spring Data Repositories的介绍

Spring Data JPA的强大之处在于数据存储的抽象(the repository abstraction),这种抽象是由Spring Data Commons project提供,并被特定的存储子项目继承实现。

我们几乎不应关心数据存储抽象(the repository abstraction)的具体实现,但是我们必须熟悉Spring Data repository interfaces。这些接口描述如下:

首先,Spring Data Commons project提供了以下的接口:

  • Repository<T,ID extends Serializable>

    1. 描述要操作的实体类型和实体的id
    2. 帮助Spring容器在classpath扫描的时候去查找实际的repository interface。
  • CrudRepository<T, ID extends Serializable> 为要操作的实体类提供CRUD的操作。

  • PagingAndSortingRepository<T, ID extends Serializable>声明了一些用来排序和分页的方法

  • QueryDslPredicateExecutor<T> 不是一个”repository interface”,使用QueryDsl Predicate objects访问数据库查找数据。

其次,Spring Data JPA project提供了以下的接口:

  • JpaRepository<T, ID extends Serializable> 接口是一个JPA特定的仓库接口,里面将the common repository interfaces里声明的方法整合在一个简单的接口内。

  • JpaSpecificationExecutor<T> 接口不是一个“repository interface”。它声明了一些方法,这些方法使用Specification<T> objects中从数据库中获取实体数据。

repository的继承关系如下图

如何使用上面讲的这些东西呢?这个问题将会在教程的下一篇讲解,但是必不可少地我们要按以下的步骤来进行:

  1. 创建一个repository interface并继承Spring Data提供的repository interfaces。

  2. 为创建的repository interface提供查询方法。

  3. 使用Spring将该接口自动的注入到另外的一个组件中使用。

接下来我们来总结一下我们在这篇博文上所学的内容。

总结

  • Spring Data JPA 不是一个JPA provider。它只是将the Java Persistence API (and the JPA provider)隐藏在它的数据存储抽象(repository abstraction)中。

  • Spring Data 提供多种repository interfaces,适用于不同的操作。

0 0