iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >如何使用jpa实现动态插入与修改
  • 944
分享到

如何使用jpa实现动态插入与修改

2023-06-25 17:06:45 944人浏览 薄情痞子
摘要

这篇文章给大家分享的是有关如何使用jpa实现动态插入与修改的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。jpa之动态插入与修改(重写save)1.动态插入@Data@Entity@DynamicInsert@Ta

这篇文章给大家分享的是有关如何使用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;  }    @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;    }         @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

@NoRepositoryBeanpublic interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {         T saveNotNull(T entity);}

2、创建BaseRepositoryImpl方法

@NoRepositoryBeanpublic 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实现动态插入与修改”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

--结束END--

本文标题: 如何使用jpa实现动态插入与修改

本文链接: https://www.lsjlt.com/news/306245.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 如何使用jpa实现动态插入与修改
    这篇文章给大家分享的是有关如何使用jpa实现动态插入与修改的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。jpa之动态插入与修改(重写save)1.动态插入@Data@Entity@DynamicInsert@Ta...
    99+
    2023-06-25
  • 使用jpa之动态插入与修改(重写save)
    目录jpa之动态插入与修改(重写save)1.动态插入2.重写save(修改)3.启动类扩展JPA方法,重写save方法为什么要重构save?一、重写save二、扩张jpa方法jpa...
    99+
    2024-04-02
  • 使用JPA+querydsl如何实现多条件动态查询
    目录JPAquerydsl多条件动态查询介绍一下querydsl看源码springdataJPA和querydsl什么是SpringDataJPA?什么是QueryDSL?@Mapp...
    99+
    2024-04-02
  • springdata jpa如何使用Example快速实现动态查询功能
    这篇文章将为大家详细讲解有关springdata jpa如何使用Example快速实现动态查询功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。Example官方介绍Query by Example (Q...
    99+
    2023-06-25
  • MariaDB中如何实现数据的插入、修改和删除
    小编给大家分享一下MariaDB中如何实现数据的插入、修改和删除,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!MariaDB数据库管理系统是 MySQL 的一个分支,主要由开源社区在维护,采用GPL授权许可 MariaDB...
    99+
    2023-06-27
  • springdata jpa使用Example快速实现动态查询功能
    目录Example官方介绍Example api的组成限制使用测试查询自定匹配器规则补充官方创建ExampleMatcher例子(1.8 lambda)StringMatcher 参...
    99+
    2024-04-02
  • 怎么使用JPA+querydsl实现多条件动态查询
    这篇文章将为大家详细讲解有关怎么使用JPA+querydsl实现多条件动态查询,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。JPA querydsl多条件动态查询相信很多人在做订单管理的时候会用到多条件的...
    99+
    2023-06-29
  • golang 如何使用反射动态修改变量值
    go 语言反射允许在运行时操控变量值,包括修改布尔值、整数、浮点数和字符串。通过获取变量的 value,可以调用 setbool、setint、setfloat 和 setstring ...
    99+
    2024-05-02
    反射 动态修改变量值 golang 字符串解析
  • 如何在Java中使用Agent动态修改代码
    今天就跟大家聊聊有关如何在Java中使用Agent动态修改代码,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。需要两个程序,一个是用来测试的程序,一个agent用于修改代码。1. 测试...
    99+
    2023-05-31
    java age agent
  • 如何使用.NET6实现动态API
    本篇文章为大家展示了如何使用.NET6实现动态API,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。ApiLite是基于.NET6直接将Service层生成动态api路由,可以不用添加Controll...
    99+
    2023-06-22
  • vue如何用DataTable插件实现表格动态刷新
    今天小编给大家分享一下vue如何用DataTable插件实现表格动态刷新的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。我这边...
    99+
    2023-07-04
  • Vue.set()如何实现动态新增与修改数据以及触发视图更新
    小编给大家分享一下Vue.set()如何实现动态新增与修改数据以及触发视图更新,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!参数...
    99+
    2024-04-02
  • 微信小程序中如何实现JS动态修改样式
    这篇文章主要为大家展示了“微信小程序中如何实现JS动态修改样式”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“微信小程序中如何实现JS动态修改样式”这篇文章吧。微...
    99+
    2024-04-02
  • Jpa 如何使用@EntityListeners 实现实体对象的自动赋值
    1、简介 1.1 @EntityListeners 官方解释:可以使用生命周期注解指定实体中的方法,这些方法在指定的生命周期事件发生时执行相应的业务逻辑。 简单来说,就是监听实体对象...
    99+
    2024-04-02
  • Java如何实现properties文件动态修改并自动保存工具类
    这篇文章主要为大家展示了“Java如何实现properties文件动态修改并自动保存工具类”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Java如何实现properties文件动态修改并自动保存...
    99+
    2023-05-30
    java properties
  • bootstrap如何实现table插件动态加载表头
    这篇文章主要为大家展示了“bootstrap如何实现table插件动态加载表头”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“bootstrap如何实现table...
    99+
    2024-04-02
  • JPA中的update如何使用@Query 实现
    今天就跟大家聊聊有关JPA中的update如何使用@Query 实现,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。使用JPA中@Query 注解实现update 操作,代码如下:@T...
    99+
    2023-05-31
    jpa @query update
  • 如何使用纯css实现动态边框
    小编给大家分享一下如何使用纯css实现动态边框,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!   CSS3 Backgroun...
    99+
    2024-04-02
  • 如何使用Quagga实现Linux动态路由
    这篇文章给大家分享的是有关如何使用Quagga实现Linux动态路由的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。OSPF 的意思是最短路径优先Open Shortest Path First。OSPF &nbs...
    99+
    2023-06-16
  • Java怎么实现pdf和Excel的生成及数据动态插入与导出
    这篇文章主要介绍“Java怎么实现pdf和Excel的生成及数据动态插入与导出”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Java怎么实现pdf和Excel的生成及数据动态插入与导出”文章能帮助大...
    99+
    2023-06-27
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作