Spring Data JPA分析与封装

8.6 - JPA
本文将针对Spring Data JPA 源码结构梳理、高级用法、封装扩展进行。
本文的书写顺序是按照分析一个已经封装好的JPA框架而一步步进行的。

一、类结构

1.1 Qo

封装的查询类

在这里插入图片描述
DataQueryObject作为最上层接口,被DataQueryObjectSort实现,DataQueryObjectPage又对DataQueryObjectSort做了扩展。

1.2 QueryField注解

标注在查询类的字段上,标注查询信息

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface QueryField {
   
    QueryType type();

    String[] name() default "";
}
  • 通过type指定条件类型
  • 根据name指定属性名

1.3 BaseRepository(持久功能接口)

在这里插入图片描述

  • 扩展接口:BaseRepository继承了JpaSpecificationExecutor
  • 扩展接口:BaseRepository继承了JpaRepository

1.4 BeasRepositoryImpl(持久功能接口实现)

在这里插入图片描述

  • 扩展类:BeasRepositoryImpl实现了BaseRepository
  • 扩展类:BeasRepositoryImpl继承了SimpleJpaRepository

1.5 BaseRepositoryFactoryBean(持久Bean工厂)

在这里插入图片描述
扩展工厂类:RepositoryFactoryBean是对JpaRepositoryFactoryBean做的一次封装

二、分析被扩展的Jpa的相关类

想要搞清楚每个扩展类的作用,就必须先了解每个被扩展的类在springJpa中的作用

2.1 持久功能接口(JpaRepository、JpaSpecificationExecutor)

在这里插入图片描述

作为SpringJpa框架所有功能接口的基类,JpaRepository继承了动态查询功能接口与分页排序crue等等相关的基本查询接口(api),规定了实现该接口需要实现所有普遍常用的持久方法,这个实现类也是springjpa的功能方法处理中心。

JpaSpecificationExecutor

针对复杂的业务场景,仅靠JpaRepository提供的一些功能并不能满足,jpa的实现类还要实现JpaSpecificationExecutor,来支持Specification可重用断言规范的复杂查询。我们将在后面讲解扩展Jpaapi实现类的时候讲。

2.2 持久功能实现类(SimpleJpaRepository)

SimpleJpaRepository实现类实现了:JpaRepositoryImplementation接口,该接口继承了上文说到的两个接口。JpaRepositoryImplementation接口定义了配置Repository的两个方法

  • setRepositoryMethodMetadata:配置Repository的方法元数据
  • setEscapeCharacter:设置Repository的转义字符规范

我们知道了这个类的具体作用,并没有继续研究下去的意义,因为这对我们理解如何封装SpringDataJpa没有帮助,如果想要研究Jpa的细节原理,才有研究这个类的必要。

2.3 持久Bean工厂(JpaRepositoryFactoryBean)

JpaRepositoryFactory是生产JpaRepository的一个地方,我们需要了解它的结构,但无需关注它的细节。
在这里插入图片描述

RepositoryFactoryBeanSupport

Adapter for Springs {@link FactoryBean} interface to allow easy setup of repository factories via Spring configuration.
Springs对FactoryBean接口的适配器,允许通过Spring轻松设置存储库工厂配置。
通过该类可以为我们提供生产jpaRepository的能力。
在这里插入图片描述

我将从源码文档或实际作用一一解释每个接口的作用

  • InitializingBean:InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。想要了解InitializingBean如何使用的小伙伴,可以参考:Spring中的InitializingBean接口的使用
  • RepositoryFactoryInformation:Interface for components that can provide meta-information about a repository factory, the backing EntityInformation and RepositoryInformation as well as the QueryMethods exposed by the repository.(组件的接口,这些组件可以提供有关存储库工厂的元信息、支持EntityInformation和RepositoryInformation以及存储库公开的查询方法。) 。由此可见通过该接口可以实现一些存储库工厂的配置。
  • FactoryBean:为IOC容器中Bean的实现提供了更加灵活的方式,FactoryBean在IOC容器的基础上给Bean的实现加上了一个简单工厂模式和装饰模式(如果想了解装饰模式参考:修饰者模式(装饰者模式,Decoration) 我们可以在getObject()方法中灵活配置。其实在Spring源码中有很多FactoryBean的实现类。想要了解FactoryBean如何使用的小伙伴,可以参考:FactoryBean的使用
  • BeanClassLoaderAware:获取Bean的类装载器。
  • BeanFactoryAware:实现这个接口的bean其实是希望知道自己属于哪一个beanfactory。测试文章:文章地址
  • ApplicationEventPublisherAware:事件发布接口,与ApplicationEvent搭配实现事件发布监听机制。想要了解该机制用法的小伙伴,可以参考:添加链接描述
TransactionalRepositoryFactoryBeanSupport

从名字可以看到该类是对RepositoryFactoryBeanSupport事务化的处理。
阅读源码文档,可以看出该类向存储库代理添加事务性功能。注册一个transactionalrepositoryproxyppostprocessor(事务持久代理后置处理器),该处理器将TransactionInterceptor(事务拦截器)添加到要创建的存储库代理。

JpaRepositoryFactoryBean
继承了TransactionalRepositoryFactoryBeanSupport,实现了通过JpaRepositoryFactory(内部引用)创建Repository的能力。

由此我们对整个SpringDataJpa的源码结构分析完毕,具体细节实现暂时不必研究。

三、扩展JPA

3.1 BaseRepositoryFactoryBean

spring data jpa中使用JpaRepository等接口定义repository时,将默认使用SimpleJpaRepository,可通过自定义实现类改写或自定义接口方法逻辑
使用自定义repository实现类分为三步:

  1. 创建MyJpaRepository实现类并继承SimpleJpaRepository,实现自己的规则
  2. 创建MyJpaRepositoryFactoryBean,并指定我们自己的实现类
  3. 主启动类中配置JpaFactoryBean,指定使用我们自己的RepositoryFactoryBean
public class BaseRepositoryFactoryBean<R extends JpaRepository<T, I>, T,
        I extends java.io.Serializable> extends JpaRepositoryFactoryBean<R, T, I> {
   

    /**
     * Creates a new {@link JpaRepositoryFactoryBean} for the given repository interface.
     *
     * @param repositoryInterface must not be {@literal null}.
     */
    public BaseRepositoryFactoryBean(Class<? extends R> repositoryInterface) {
   
        super(repositoryInterface);
    }

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
   
        return new BaseRepositoryFactory(em);
    }

    /**
     * 创建一个内部类,该类不用在外部访问
     *
     * @param <T>
     * @param <I>
     */
    private static class BaseRepositoryFactory<T, I extends java.io.Serializable>
            extends JpaRepositoryFactory {
   

        private final EntityManager em;

        public BaseRepositoryFactory(EntityManager em) {
   
            super(em);
            this.em = em;
        }

        /**
         * 设置具体的实现类是BaseRepositoryImpl
         *
         * @param information
         * @return
         */
        @Override
        protected JpaRepositoryImplementation<?, ?> getTargetRepository(RepositoryInformation information,
                                                                        EntityManager entityManager) {
   
            return new BaseRepositoryImpl<T, I>((Class<T>) information.getDomainType(), entityManager);
        }

        /**
         * 获取具体的实现类的class
         *
         * @param metadata
         * @return
         */
        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
   
            return BaseRepositoryImpl.class;
        }
    }
}

主启动类配置

@EnableJpaRepositories(repositoryFactoryBeanClass = BaseRepositoryFactoryBean.class)

3.2 BaseRepository

定义了我们要扩展的接口方法。其中Qo里面定义了查询条件的相关信息

@NoRepositoryBean
@Transactional(readOnly = true, rollbackFor = Exception.class)
public interface BaseRepository<T, ID extends java.io.Serializable> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T> {
   

    List<T> findAll(DataQueryObject query);

    Page<T> findAll(DataQueryObject query, Pageable page);

    Page<T> findAll(DataQueryObjectPage dataQueryObjectpage);

    List<T> findAll(DataQueryObject dataQueryObject, Sort sort);

    List<T> findAll(DataQueryObjectSort dataQueryObjectSort);
}

四、Specification复杂查询

在进行实现类的扩展之前,我们需要先了解复杂查询的用法

api

查看JpaSpecificationExecutor,我们可以看到SpringDataJpa给我们提供的Specification复杂查询接口。

/**
* Interface to allow execution of {@link Specification}s based on the JPA criteria API.
*
* @author Oliver Gierke
* @author Christoph Strobl
*/
public interface JpaSpecificationExecutor<T> {
   

   /**
    * Returns a single entity matching the given {@link Specification} or {@link Optional#empty()} if none found.
    *
    * @param spec can be {@literal null}.
    * @return never {@literal null}.
    * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if more than one entity found.
    */
   Optional<T> findOne(@Nullable Specification<T> spec);

   /**
    * Returns all entities matching the given {@link Specification}.
    *
    * @param spec can be {@literal null}.
    * @return never {@literal null}.
    */
   List<T> findAll(@Nullable Specification<T> spec);

   /**
    * Returns a {@link Page} of entities matching the given {@link Specification}.
    *
    * @param spec can be {@literal null}.
    * @param pageable must not be {@literal null}.
    * @return never {@literal null}.
    */
   Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable);

   /**
    * Returns all entities matching the given {@link Specification} and {@link Sort}.
    *
    * @param spec can be {@literal null}.
    * @param sort must not be {@literal null}.
    * @return never {@literal null}.
    */
   List<T> findAll(@Nullable Specification<T> spec, Sort sort);

   /**
    * Returns the number of instances that the given {@link Specification} will return.
    *
    * @param spec the {@link Specification} to count instances for. Can be {@literal null}.
    * @return the number of instances.
    */
   long count(@Nullable Specification<T> spec);
}

进入Specification,发现必须实现的方法(其他方法为默认方法不必实现):

@Nullable
	Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder);

该方法为我们构造条件。它有三个参数

  • Root:实体类对象
  • CriteriaQuery:做子查询,我们不必去了解这个类,因为我们将要实现的方法并没有用到这个。
  • CriteriaBuilder:条件构造器,生成Predicate(条件表达式对象)。

使用测试

ArticleServiceImpl

    @Override
    public List<Article> findByTitleAndDescr(String title, String descr)
    {
   
        // 构造一个Specification对象
        <
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JPA是Java Persistence API的缩写,是Java EE规范中用于ORM(对象关系映射)的API。它定义了一组接口和注解,使开发人员可以通过编写面向对象的代码来操作数据库。引用提到了在pom.xml中添加了两个依赖,即org.springframework.data:spring-data-jpa和org.springframework.boot:spring-boot-starter-data-jpa,这是使用Spring Data JPA时需要添加的依赖。 Spring Data JPA是在JPA规范下对Repository层进行封装实现。它提供了一套简化的方法和规范,使开发人员可以更轻松地进行数据库操作。引用中的代码片段展示了如何定义一个符合Spring Data JPA规范的DAO层接口。通过继承JpaRepositoryJpaSpecificationExecutor接口,我们可以获得封装了基本CRUD操作和复杂查询的功能。 关于JPASpring Data JPA的区别,引用提到了一个很好的解释。JPA是一种规范,而Spring Data JPA是在JPA规范下提供的Repository层的实现。通过使用Spring Data JPA,我们可以方便地在不同的ORM框架之间进行切换,而不需要更改代码。Spring Data JPA还对Repository层进行了封装,省去了开发人员的不少麻烦。 综上所述,JPA是Java EE规范中的API,而Spring Data JPA是在JPA规范下的Repository层的实现Spring Data JPA封装JPA规范,提供了更方便的方法和规范,使开发人员可以更轻松地进行数据库操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [JPASpring-Data-JPA简介](https://blog.csdn.net/benjaminlee1/article/details/53087351)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* [JPA & Spring Data JPA详解](https://blog.csdn.net/cd546566850/article/details/107180272)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值