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

目录
  • jpa之动态插入与修改(重写save)
    • 1.动态插入
    • 2.重写save(修改)
    • 3.启动类
  • 扩展JPA方法,重写save方法
    • 为什么要重构save?
    • 一、重写save
    • 二、扩张jpa方法

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);
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • JPA save()方法将字段更新为null的解决方案

    这篇文章主要介绍了JPA save()方法将字段更新为null的解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 今天在开发上碰到一个问题,在做页面展示的时候传给前端十个字段,前端修改了其中3个的值,所以只传了3个值给后端,其余字段默认为null,更新后其他7个字段在全部变为了空值. 在前端没法全量回传所有属性的前提下,由后端来处理这类问题. 解决方法: 1.写一个工具方法(UpdateUtil) 用来筛选出所有的空值字段 2.更新时先通

  • 详解Spring Data JPA动态条件查询的写法

    我们在使用SpringData JPA框架时,进行条件查询,如果是固定条件的查询,我们可以使用符合框架规则的自定义方法以及@Query注解实现. 如果是查询条件是动态的,框架也提供了查询接口. JpaSpecificationExecutor 和其他接口使用方式一样,只需要在你的Dao接口继承即可(官网代码). public interface CustomerRepository extends CrudRepository<Customer, Long>, JpaSpecification

  • 详解SpringBoot实现JPA的save方法不更新null属性

    序言:直接调用原生Save方法会导致null属性覆盖到数据库,使用起来十分不方便.本文提供便捷方法解决此问题. 核心思路 如果现在保存某User对象,首先根据主键查询这个User的最新对象,然后将此User对象的非空属性覆盖到最新对象. 核心代码 直接修改通用JpaRepository的实现类,然后在启动类标记此实现类即可. 一.通用CRUD实现类 public class SimpleJpaRepositoryImpl<T, ID> extends SimpleJpaRepository&l

  • Spring Data JPA实现动态查询的两种方法

    前言 一般在写业务接口的过程中,很有可能需要实现可以动态组合各种查询条件的接口.如果我们根据一种查询条件组合一个方法的做法来写,那么将会有大量方法存在,繁琐,维护起来相当困难.想要实现动态查询,其实就是要实现拼接SQL语句.无论实现如何复杂,基本都是包括select的字段,from或者join的表,where或者having的条件.在Spring Data JPA有两种方法可以实现查询条件的动态查询,两种方法都用到了Criteria API. Criteria API 这套API可用于构建对数据

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

    目录 jpa之动态插入与修改(重写save) 1.动态插入 2.重写save(修改) 3.启动类 扩展JPA方法,重写save方法 为什么要重构save? 一.重写save 二.扩张jpa方法 jpa之动态插入与修改(重写save) 1.动态插入 @Data @Entity @DynamicInsert @Table(name = "cpu_dynamics_information") @EntityListeners(AuditingEntityListener.class) pub

  • 深入理解javascript动态插入技术

    最近发现各大类库都能利用div.innerHTML=HTML片断来生成节点元素,再把它们插入到目标元素的各个位置上.这东西实际上就是insertAdjacentHTML,但是IE可恶的innerHTML把这优势变成劣势.首先innerHTML会把里面的某些位置的空白去掉,见下面运行框的结果: 复制代码 代码如下: <!doctype html><html dir="ltr" lang="zh-CN">    <head>     

  • PHP正在进行时-变量详解及字符串动态插入变量

    在PHP中,变量是$+变量名,变量名遵循标识符的命名规则,可以以字母.下划线开头,可以由数字.下划线.字母组成合法的变量名. 变量声明 所有变量在使用之前应该进行声明,而且最好带上注释,虽然在PHP中可以不显示声明变量.声明变量之后,可以为变量进行赋值:变量的赋值有两种类型值赋值和引用赋值. <?php #合法的声明变量 $_name; $account; $show_title; #赋值 $color="red"; #引用赋值 $user_color=&$color;

  • mybatis动态插入list传入List参数的实例代码

    mybatis动态插入list的实例代码如下所述: <insert id="savePrpcitemkindList" parameterType="java.util.List"> insert into prpcitemkind (RISKCODE, ITEMKINDNO, FAMILYNO, FAMILYNAME, PROJECTCODE, CLAUSECODE, CLAUSENAME, KINDCODE, KINDNAME, ITEMNO, IT

  • JS动态插入脚本和插入引用外部链接脚本的方法

    在日常开发中,经常遇到 js 动态插入脚本 . 什么是 js 动态插入脚本 ? 指的是在页面加载时不存在,但将来的某一时刻通过修改该 DOM 动态添加的脚本.和操作 HTML 元素一样. js 动态插入脚本也有两种方式:插入 JavaScript 代码和插入外部文件. 一.直接插入 javascript 代码 <script type="text/javascript"> function sayHi() { alert("hi"); } </sc

  • JavaScript数组,JSON对象实现动态添加、修改、删除功能示例

    本文实例讲述了JavaScript数组,JSON对象实现动态添加.修改.删除功能.分享给大家供大家参考,具体如下: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>javascript里面的数组,json对象,动态添加,修改,删除示例</t

  • JS动态插入并立即执行回调函数的方法

    本文实例讲述了JS动态插入并立即执行回调函数的方法.分享给大家供大家参考,具体如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <

  • JS把内容动态插入到DIV的实现方法

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="content-

  • mssql2008 自定义表类型实现(批量插入或者修改)

    在做大型网站或者系统的时候,经常会遇到个问题就是批量插入或者修改数据库.如果遇到这个问题,还是一条条记录来处理,这样的效率太低了,所以要考虑批量插入或者修改 今天这边不讲SqlBulkCopy,只简单讲sql自定义表类型.因为目前的项目我用到了分表的方式,用存储过程比较方便自动创建分表.现在把我目前写的功能简单做个记录,也方便以后自己查阅 第一步,在数据库里点击 新建查询 创建相应的sql 复制代码 代码如下: --======自定义表类型Demo====== --创建表 create tabl

  • JavaScript动态插入CSS的方法

    写组件时有时想把一些组件特性相关的 CSS 样式封装在 JS 里,这样更内聚,改起来方便.JS 动态插入 CSS 两个步骤:创建1.一个 style 对象 2.使用 stylesheet 的 insertRule 或 addRule 方法添加样式 一.查看样式表 先看下 document.styleSheets,随意打开一个页面 其中前三个是通过 link 标签引入的 CSS 文件,第四个是通过 style 标签内联在页面里的 CSS.有如下属性 每一个 cssRule 又有如下属性 其中的 c

随机推荐