使用jpa之动态插入与修改(重写save)


Posted in Java/Android onNovember 23, 2021

jpa之动态插入与修改(重写save)

1.动态插入

@Data
@Entity
@DynamicInsert
@Table(name = "cpu_dynamics_information")
@EntityListeners(AuditingEntityListener.class)
public class CpuDynamicsInformation extends CommonEntity implements Serializable {
  private static final long serialVersionUID = -662804563658253624L;
  // cpu动态属性
  private Integer cpuCore;
  // cpu用户使用率
  private Double cpuUseRate;
  // cpu系统使用率
  private Double cpuSysRate;
  // cpu等待率
  private Double cpuWaitRate;
  // cpu空闲率
  private Double cpuIdleRate;
  // cpu总的使用率
  private Double cpuCombineRate;
  private Long serverId;
}

关键注解:

@DynamicInsert
@EntityListeners(AuditingEntityListener.class)

2.重写save(修改)

@SuppressWarnings(value = "all")
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]);
  }
}

3.启动类

@EnableJpaAuditing
@SpringBootApplication(exclude = MongoAutoConfiguration.class)
@EnableJpaRepositories(
    value = {"com.fooww.research.repository", "com.fooww.research.shiro.repository"},
    repositoryBaseClass = JpaRepositoryReBuild.class)
public class MonitorServerApplication {
  public static void main(String[] args) {
    SpringApplication.run(MonitorServerApplication.class, args);
  }
}

关键注释:

  • EnableJpaRepositories 扫描的repository包
  • repositoryBaseClass 重写的save类
  • EnableJpaAuditing 使@EntityListeners(AuditingEntityListener.class) 生效

扩展JPA方法,重写save方法

为什么要重构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);
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Java/Android 相关文章推荐
Java基于字符界面的简易收银台
Jun 26 Java/Android
Jackson 反序列化时实现大小写不敏感设置
Jun 29 Java/Android
新手初学Java List 接口
Jul 07 Java/Android
详细了解java监听器和过滤器
Jul 09 Java/Android
Java生成读取条形码和二维码的简单示例
Jul 09 Java/Android
Spring this调用当前类方法无法拦截的示例代码
Mar 20 Java/Android
Java字符缓冲流BufferedWriter
Apr 09 Java/Android
Java设计模式之代理模式
Apr 22 Java/Android
JavaScript正则表达式实现注册信息校验功能
May 30 Java/Android
SpringBoot使用ip2region获取地理位置信息的方法
Jun 21 Java/Android
HttpClient实现表单提交上传文件
Aug 14 Java/Android
Java Redisson多策略注解限流
Sep 23 Java/Android
Jpa Specification如何实现and和or同时使用查询
Nov 23 #Java/Android
解析mybatis-plus中的resultMap简单使用
Nov 23 #Java/Android
JPA 通过Specification如何实现复杂查询
Java使用JMeter进行高并发测试
Java 在线考试云平台的实现
OpenCV实现反阈值二值化
聊聊SpringBoot自动装配的魔力
Nov 17 #Java/Android
You might like
php标签云的实现代码
2012/10/10 PHP
PHP中使用Memache作为进程锁的操作类分享
2015/03/30 PHP
PHP get_html_translation_table()函数用法讲解
2019/02/16 PHP
Javascript开发包大全整理
2006/12/22 Javascript
js里怎么取select标签里的值并修改
2012/12/10 Javascript
javascript修改表格背景色实例代码分享
2013/12/10 Javascript
jQuery的选择器中的通配符使用介绍
2014/03/20 Javascript
jquery图片切换实例分析
2015/04/15 Javascript
JavaScript获取浏览器信息的方法
2015/11/20 Javascript
详解Vue使用 vue-cli 搭建项目
2017/04/20 Javascript
JS运动特效之同时运动实现方法分析
2018/01/24 Javascript
傻瓜式解读koa中间件处理模块koa-compose的使用
2018/10/30 Javascript
layui框架与SSM前后台交互的方法
2019/09/12 Javascript
js判断浏览器的环境(pc端,移动端,还是微信浏览器)
2020/12/24 Javascript
js实现圆形显示鼠标单击位置
2020/02/11 Javascript
Element Notification通知的实现示例
2020/07/27 Javascript
vue实现简单全选和反选功能
2020/09/15 Javascript
在antd Table中插入可编辑的单元格实例
2020/10/28 Javascript
Python实现删除Android工程中的冗余字符串
2015/01/19 Python
python实现批量修改文件名代码
2017/09/10 Python
python导入csv文件出现SyntaxError问题分析
2017/12/15 Python
python判断字符串或者集合是否为空的实例
2019/01/23 Python
python Tkinter版学生管理系统
2019/02/20 Python
用pyqt5 给按钮设置图标和css样式的方法
2019/06/24 Python
详解解决Python memory error的问题(四种解决方案)
2019/08/08 Python
解决python3中os.popen()出错的问题
2020/11/19 Python
使用python操作lmdb对数据读取的实例
2020/12/11 Python
this关键字的含义
2015/04/08 面试题
乌鸦喝水教学反思
2014/02/07 职场文书
煤矿安全承诺书
2014/05/22 职场文书
档案保密承诺书
2014/06/03 职场文书
上班迟到检讨书
2014/09/15 职场文书
班子群众路线教育实践个人对照检查材料思想汇报
2014/09/30 职场文书
考试作弊万能检讨书
2014/10/19 职场文书
学籍证明模板
2015/06/18 职场文书
人身损害赔偿协议书
2016/03/22 职场文书