使用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 相关文章推荐
springboot利用redis、Redisson处理并发问题的操作
Jun 18 Java/Android
IDEA使用SpringAssistant插件创建SpringCloud项目
Jun 23 Java/Android
详解Spring Boot使用系统参数表提升系统的灵活性
Jun 30 Java/Android
mybatis源码解读之executor包语句处理功能
Feb 15 Java/Android
SpringBoot整合Minio文件存储
Apr 03 Java/Android
Java8 CompletableFuture 异步回调
Apr 28 Java/Android
Jmerte 分布式压测及分布式压测配置
Apr 30 Java/Android
利用正则表达式匹配浮点型数据
May 30 Java/Android
java实现面板之间切换功能
Jun 10 Java/Android
SpringBoot项目部署到阿里云服务器的实现步骤
Jun 28 Java/Android
Java Spring读取和存储详细操作
Aug 05 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
PHP5.0正式发布 不完全兼容PHP4 新增多项功能
2006/10/09 PHP
PHP操作文件类的函数代码(文件和文件夹创建,复制,移动和删除)
2011/11/10 PHP
php数字每三位加逗号的功能函数
2015/10/22 PHP
PHP中empty和isset对于参数结构的判断及empty()和isset()的区别
2015/11/15 PHP
学习php设计模式 php实现合成模式(composite)
2015/12/08 PHP
详解PHP中websocket的使用方法
2016/09/15 PHP
比较详细的关于javascript中void(0)的具体含义解释
2007/08/02 Javascript
使用JavaScript的AngularJS库编写hello world的方法
2015/06/23 Javascript
js闭包引起的事件注册问题介绍
2016/03/29 Javascript
JS onkeypress兼容性写法详解
2016/04/27 Javascript
jQuery使用中可能被XSS攻击的一些危险环节提醒
2016/05/24 Javascript
微信jssdk逻辑在vue中的运用详解
2018/11/14 Javascript
微信小程序 如何保持登录状态
2019/08/16 Javascript
基于JavaScript判断两个对象内容是否相等
2020/01/10 Javascript
Vue的Eslint配置文件eslintrc.js说明与规则介绍
2020/02/03 Javascript
Node.js中文件系统fs模块的使用及常用接口
2020/03/06 Javascript
[39:21]LGD vs OG 2019国际邀请赛淘汰赛 胜者组 BO3 第二场 8.24
2019/09/10 DOTA
Python实现从脚本里运行scrapy的方法
2015/04/07 Python
python tensorflow基于cnn实现手写数字识别
2018/01/01 Python
简单了解python模块概念
2018/01/11 Python
使用apidoc管理RESTful风格Flask项目接口文档方法
2018/02/07 Python
python实现最小二乘法线性拟合
2019/07/19 Python
解决keras backend 越跑越慢问题
2020/06/18 Python
css3实现一个div设置多张背景图片及background-image属性实例演示
2017/08/10 HTML / CSS
Giglio美国站:意大利奢侈品购物网
2018/02/10 全球购物
Dillard’s百货官网:Dillards.com
2018/05/26 全球购物
专注澳大利亚特产和新西兰特产的澳洲中文网:0061澳洲制造
2019/03/24 全球购物
澳大利亚Mocha官方网站:包、钱包、珠宝和配饰
2019/07/18 全球购物
环境工程专业个人求职信
2013/12/05 职场文书
2014教师研修学习体会
2014/07/08 职场文书
学生实习证明范文
2014/09/28 职场文书
慰问信范文
2015/02/14 职场文书
学校就业保障协议书
2019/06/24 职场文书
python程序的组织结构详解
2021/12/06 Python
MySQL 逻辑备份 into outfile
2022/05/15 MySQL
Python 避免字典和元组的多重嵌套问题
2022/07/15 Python