SpringBoot Jpa的SimpleJpaRepository
SimpleJpaRepository
先看结构
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时,就需要对JpsRepository与CrudRepository有所选择。
JpaRepositoryFactory
简单介绍了一下SimpleJpaRepository就不得不说JpaRepositoryFactory,这才是基础。
先看关系:

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