为什么要重构save?

jpa提供的save方法会将原有数据置为null,而大多数情况下我们只希望跟新自己传入的参数,所以便有了重写或者新增一个save方法。

本着解决这个问题,网上搜了很多解决方案,但是没有找到合适的,于是自己研究源码,先展示几个重要源码

1、SimpleJpaRepository方法实现类,由于代码过多只展示部分源码

public class SimpleJpaRepository<T, ID> implements JpaRepository<T, ID>, JpaSpecificationExecutor<T> {
private static final String ID_MUST_NOT_BE_NULL = "The given id must not be null!";
private final JpaEntityInformation<T, ?> entityInformation;
private final EntityManager em;
private final PersistenceProvider provider;
@Nullable
private CrudMethodMetadata metadata; public SimpleJpaRepository(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
Assert.notNull(entityInformation, "JpaEntityInformation must not be null!");
Assert.notNull(entityManager, "EntityManager must not be null!");
this.entityInformation = entityInformation;
this.em = entityManager;
this.provider = PersistenceProvider.fromEntityManager(entityManager);
} public SimpleJpaRepository(Class<T> domainClass, EntityManager em) {
this(JpaEntityInformationSupport.getEntityInformation(domainClass, em), em);
} public void setRepositoryMethodMetadata(CrudMethodMetadata crudMethodMetadata) {
this.metadata = crudMethodMetadata;
} @Nullable
protected CrudMethodMetadata getRepositoryMethodMetadata() {
return this.metadata;
} protected Class<T> getDomainClass() {
return this.entityInformation.getJavaType();
} private String getDeleteAllQueryString() {
return QueryUtils.getQueryString("delete from %s x", this.entityInformation.getEntityName());
}
@Transactional
public <S extends T> S save(S entity) {
if (this.entityInformation.isNew(entity)) {
this.em.persist(entity);
return entity;
} else {
return this.em.merge(entity);
}
}
}
2、JpaRepositoryFactoryBean
public class JpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID> extends TransactionalRepositoryFactoryBeanSupport<T, S, ID> {
@Nullable
private EntityManager entityManager; public JpaRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
super(repositoryInterface);
} @PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
} public void setMappingContext(MappingContext<?, ?> mappingContext) {
super.setMappingContext(mappingContext);
} protected RepositoryFactorySupport doCreateRepositoryFactory() {
Assert.state(this.entityManager != null, "EntityManager must not be null!");
return this.createRepositoryFactory(this.entityManager);
} protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new JpaRepositoryFactory(entityManager);
} public void afterPropertiesSet() {
Assert.state(this.entityManager != null, "EntityManager must not be null!");
super.afterPropertiesSet();
}
} 

根据源码及网上资料总结如下方案

一、重写save

优势:侵入性小,缺点将原方法覆盖。

创建JpaRepositoryReBuild方法继承SimpleJpaRepository。直接上代码

public class JpaRepositoryReBuild<T, ID> extends SimpleJpaRepository<T, ID> {

    private final JpaEntityInformation<T, ?> entityInformation;
private final EntityManager em; @Autowired
public JpaRepositoryReBuild(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityInformation = entityInformation;
this.em = entityManager;
} /**
* 通用save方法 :新增/选择性更新
*/
@Override
@Transactional
public <S extends T> S save(S entity) { //获取ID
ID entityId = (ID) this.entityInformation.getId(entity);
T managedEntity;
T mergedEntity;
if(entityId == null){
em.persist(entity);
mergedEntity = entity;
}else{
managedEntity = this.findById(entityId).get();
if (managedEntity == null) {
em.persist(entity);
mergedEntity = entity;
} else {
BeanUtils.copyProperties(entity, managedEntity, getNullProperties(entity));
em.merge(managedEntity);
mergedEntity = managedEntity;
}
}
return entity;
} /**
* 获取对象的空属性
*/
private static String[] getNullProperties(Object src) {
//1.获取Bean
BeanWrapper srcBean = new BeanWrapperImpl(src);
//2.获取Bean的属性描述
PropertyDescriptor[] pds = srcBean.getPropertyDescriptors();
//3.获取Bean的空属性
Set<String> properties = new HashSet<>();
for (PropertyDescriptor propertyDescriptor : pds) {
String propertyName = propertyDescriptor.getName();
Object propertyValue = srcBean.getPropertyValue(propertyName);
if (StringUtils.isEmpty(propertyValue)) {
srcBean.setPropertyValue(propertyName, null);
properties.add(propertyName);
}
}
return properties.toArray(new String[0]);
}
}

启动类加上JpaRepositoryReBuild 方法

@EnableJpaRepositories(value = "com.XXX", repositoryBaseClass = JpaRepositoryReBuild.class)
@SpringBootApplication
@EnableDiscoveryClient // 即消费也注册
public class SystemApplication { public static void main(String[] args) {
SpringApplication.run(SystemApplication.class, args);
} }

二、扩张jpa方法

1、新建新增方法接口BaseRepository

@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID> { /**
* 保存但不覆盖原有数据
* @param entity
* @return
*/
T saveNotNull(T entity);
}

2、创建BaseRepositoryImpl方法

@NoRepositoryBean
public class BaseRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseRepository<T, ID> { private final JpaEntityInformation<T, ?> entityInformation;
private final EntityManager em; public BaseRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation,entityManager);
this.entityInformation = entityInformation;
this.em = entityManager;
} public BaseRepositoryImpl(Class<T> domainClass, EntityManager em) {
this(JpaEntityInformationSupport.getEntityInformation(domainClass, em), em);
} @Override
@Transactional
public T saveNotNull(T entity) { //获取ID
ID entityId = (ID) this.entityInformation.getId(entity);
T managedEntity;
T mergedEntity;
if(entityId == null){
em.persist(entity);
mergedEntity = entity;
}else{
managedEntity = this.findById(entityId).get();
if (managedEntity == null) {
em.persist(entity);
mergedEntity = entity;
} else {
BeanUtils.copyProperties(entity, managedEntity, getNullProperties(entity));
em.merge(managedEntity);
mergedEntity = managedEntity;
}
}
return mergedEntity;
} private static String[] getNullProperties(Object src) {
//1.获取Bean
BeanWrapper srcBean = new BeanWrapperImpl(src);
//2.获取Bean的属性描述
PropertyDescriptor[] pds = srcBean.getPropertyDescriptors();
//3.获取Bean的空属性
Set<String> properties = new HashSet<>();
for (PropertyDescriptor propertyDescriptor : pds) {
String propertyName = propertyDescriptor.getName();
Object propertyValue = srcBean.getPropertyValue(propertyName);
if (StringUtils.isEmpty(propertyValue)) {
srcBean.setPropertyValue(propertyName, null);
properties.add(propertyName);
}
}
return properties.toArray(new String[0]);
}
}

3、创建工厂BaseRepositoryFactory

public class BaseRepositoryFactory<R extends JpaRepository<T, ID>, T, ID extends Serializable> extends JpaRepositoryFactoryBean<R, T, ID> {

    public BaseRepositoryFactory(Class<? extends R> repositoryInterface) {
super(repositoryInterface);
} @Override
protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
return new MyRepositoryFactory(em);
} private static class MyRepositoryFactory extends JpaRepositoryFactory { private final EntityManager em;
public MyRepositoryFactory(EntityManager em) {
super(em);
this.em = em;
} @Override
protected Object getTargetRepository(RepositoryInformation information) {
return new BaseRepositoryImpl((Class) information.getDomainType(), em);
} @Override
protected Class getRepositoryBaseClass(RepositoryMetadata metadata) {
return BaseRepositoryImpl.class;
} } }

4、启动类引入

@EnableJpaRepositories(repositoryFactoryBeanClass = BaseRepositoryFactory.class, basePackages ="com.XXX")
@SpringBootApplication
@EnableDiscoveryClient // 即消费也注册
public class SystemApplication { public static void main(String[] args) {
SpringApplication.run(SystemApplication.class, args);
}
}

  

  

  

  

扩展JPA方法,重写save方法的更多相关文章

  1. Django model重写save方法及update踩坑记录

    一个非常实用的小方法 试想一下,Django中如果我们想对保存进数据库的数据做校验,有哪些实现的方法? 我们可以在view中去处理,每当view接收请求,就对提交的数据做校验,校验不通过直接返回错误, ...

  2. Java中方法重写和方法重载

     首先方法重写和方法重载是建立在Java的面向对象的继承和多态的特性基础上而出现的.至于面向对象的继承和多态的特性我就不在这里多说了.继承是指在一个父类的基础再创建一个子类,这样子类就拥有了父类的非私 ...

  3. MongoDB中insert方法、update方法、save方法简单对比

    MongoDB中insert方法.update方法.save方法简单对比 1.update方法 该方法用于更新数据,是对文档中的数据进行更新,改变则更新,没改变则不变. 2.insert方法 该方法用 ...

  4. 方法重写和方法重载;this关键字和super关键字

    1:方法重写和方法重载的区别?方法重载能改变返回值类型吗? 方法重写: 在子类中,出现和父类中一模一样的方法声明的现象. 方法重载: 同一个类中,出现的方法名相同,参数列表不同的现象. 方法重载能改变 ...

  5. Java方法重写与方法重载

    方法重载:发生在同一个类中,方法名相同方法形参列表不同就会重载方法. 方法重写:发生在继承当中,如果子的一个类方法与父类中的那个方法一模一样(方法名和形参列表一样),那么子类就会重写父类的方法. 方法 ...

  6. [原创]java WEB学习笔记79:Hibernate学习之路--- 四种对象的状态,session核心方法:save()方法,persist()方法,get() 和 load() 方法,update()方法,saveOrUpdate() 方法,merge() 方法,delete() 方法,evict(),hibernate 调用存储过程,hibernate 与 触发器协同工作

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  7. 【java开发】方法重写和方法重载概述

    类的继承   父类-子类 关键字 extends 新建一个父类 public class Person {     private String name;          private int ...

  8. C++学习笔记24,方法重写与方法隐藏

    该博文仅用于交流学习.请慎用于不论什么商业用途.本博主保留对该博文的一切权利. 博主博客:http://blog.csdn.net/qq844352155 转载请注明出处: 方法重写.是指在子类中又一 ...

  9. Java 深度克隆 clone()方法重写 equals()方法的重写

    1.为什么要重写clone()方法? 答案:Java中的浅度复制是不会把要复制的那个对象的引用对象重新开辟一个新的引用空间,当我们需要深度复制的时候,这个时候我们就要重写clone()方法. 2.为什 ...

随机推荐

  1. struts2学习(15)struts2防重复提交

    一.重复提交的例子: 模拟一种情况,存在延时啊,系统比较繁忙啊啥的. 模拟延迟5s钟,用户点了一次提交,又点了一次提交,例子中模拟这种情况: 这样会造成重复提交:   com.cy.action.St ...

  2. OSGi学习-总结

    本文是osgi实战一书的前几章读书总结 1.  OSGi简介 Java缺少对高级模块化的支持,为了弥补Java在模块化方面的不足,大多数管理得当的项目都会要求建立一整套技术,包括: 适应逻辑结构的编程 ...

  3. read/write/fsync与fread/fwrite/fflush的关系和区别

    read/write/fsync: 1. linux底层操作: 2. 内核调用, 涉及到进程上下文的切换,即用户态到核心态的转换,这是个比较消耗性能的操作. fread/fwrite/fflush: ...

  4. 将服务器上的SqlServer数据库备份到本地

    如何将服务器上的SqlServer数据库备份到本地电脑 http://bbs.csdn.net/topics/370051204 有A数据库服务器,B本机:    我现在想通过在B机器上通过代码调用S ...

  5. 主从DNS服务器的搭建

    一.DNS主从的理解 主从服务器,在一开始的理解中,以为是主的dns服务器挂掉后,(dns服务自动转向辅助dns服务器),客户端还能继续解析.事实貌似不是这样的.当我把主dns停掉的时候,客户端只设一 ...

  6. python学习笔记(九):操作数据库

    我们在写代码的时候,经常会操作数据库,增删改查,数据库有很多类型,关系型数据库和非关系数据库,这里咱们介绍一下python怎么操作mysql.redis和mongodb. 一.python操作mysq ...

  7. OD 实验(十九) - 对多态和变形程序的逆向

    程序: 这个窗口显示这是一个需要去除的 Nag 窗口 点击“确定” 用 PEiD 看一下 这是一个用汇编语言写的程序 逆向: 用 OD 载入程序 Nag 窗口的标题和文本 右键 -> 查找 -& ...

  8. 何用glmnet或lars包进行feature selection

    #datalibrary(lars)data(diabetes)attach(diabetes) #glmnetlibrary(glmnet)library(foreach)library(Matri ...

  9. vue之vue-router跳转

    vue之vue-router跳转 一.配置 在初始化使用vue-cli的时候会有vue-router的安装选择,选择安装即可. 二.嵌套路由 一般情况下,登录和项目页面属于同级,所以App.vue 只 ...

  10. angularjs之ng-option

    ng-options一般有以下用法: 对于数组: label for value in array select as label for value in array label group by  ...