SpringBoot Jpa的SimpleJpaRepository

SimpleJpaRepository

  先看结构SimpleJpaRepository_Diagram

  • SimpleJpaRepository实现了JpaRepositoryImplementation接口,它是CrudRepository的默认实现;
  • SimpleJpaRepository的构造方法都包含EntityManager,从这里可以看出来,SimpleJpaRepository是通过EntityManager实现具体功能的。
  • SimpleJpaRepository代码太长就不贴出来了,比较值得注意的地方是:类上注解了@Transactional(readOnly = true)delete*、save*、flush 等都添加了@Transactional注解。
  • 对于查询功能很多都借助了applySpecificationToCriteria方法,将spring data的Specification转换为javax.persistence的CriteriaQuery
  • 正常 JPA 继承JpsRepository接口,此接口继承的PagingAndSortingRepository有分页和排序。自定义repository时,就需要对JpsRepositoryCrudRepository有所选择。

JpaRepositoryFactory

简单介绍了一下SimpleJpaRepository就不得不说JpaRepositoryFactory,这才是基础。

先看关系:

JpaRepositoryFactoryBean_Diagram

  • JpaRepositoryFactorygetTargetRepository会根据RepositoryInformation创建JpaRepositoryImplementation,这里默认创建的是SimpleJpaRepository实例
  • RepositoryFactorySupportgetRepository 方法在调用子类的 getTargetRepository 创建SimpleJpaRepository 实例之后,会对其进行proxy,设置其接口为用户定义的dao接口、Repository、TransactionalProxy,并添加了SurroundingTransactionDetectorMethodInterceptor、DefaultMethodInvokingMethodInterceptor、QueryExecutorMethodInterceptor、ImplementationMethodExecutionInterceptorMethodInterceptor,最后生成最终的实现类

本文地址: https://github.com/maxzhao-it/blog/post/22565/