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实现类分为三步:
- 创建MyJpaRepository实现类并继承SimpleJpaRepository,实现自己的规则
- 创建MyJpaRepositoryFactoryBean,并指定我们自己的实现类
- 主启动类中配置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对象
<