介绍
这篇文章主要介绍SpringBoot如何实现JPA的保存方法不更新零属性,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
<强>核心思路强>
如果现在保存某用户对象,首先根据主键查询这个用户的最新对象,然后将此用户对象的非空属性覆盖到最新对象。
<强>核心代码强>
直接修改通用JpaRepository的实现类,然后在启动类标记此实现类即可。
一、通用CRUD实现类
public class SimpleJpaRepositoryImpl, extends SimpleJpaRepository , { private 才能;final  JpaEntityInformation , S 保存(S 实体),{ ,,,//获取ID ,,,ID entityId =, (ID), entityInformation.getId(实体); ,,,Optional , optionalT; ,,,if (StringUtils.isEmpty (entityId)), { ,,,,,String uuid =, UUID.randomUUID () .toString (); ,,,,,//防止UUID重复 ,,,,,if (findById ((ID), uuid) .isPresent ()), { ,,,,,,,uuid =, UUID.randomUUID () .toString (); ,,,,,} ,,,,,//若ID为空,则设置为UUID ,,,,,new BeanWrapperImpl(实体).setPropertyValue (entityInformation.getIdAttribute () . getname (),, uuid); ,,,,,//标记为新增数据 ,,,,,optionalT =, Optional.empty (); ,,,},{else ,,,,,//若ID非空,则查询最新数据 ,,,,,optionalT =, findById (entityId); ,,,} ,,,//获取空属性并处理成空 ,,,String [], nullProperties =, getNullProperties(实体); ,,,//若根据ID查询结果为空 ,,,if (! optionalT.isPresent ()), { ,,,,,em.persist(实体);//新增 ,,,,,return 实体; ,,,},{else ,,,,,//1。获取最新对象 ,,,,,T target =, optionalT.get (); ,,,,//2。将非空属性覆盖到最新对象 ,,,,,BeanUtils.copyProperties(实体,,目标,nullProperties); ,,,,,//3。更新非空属性 ,,,,,em.merge(目标); ,,,,,return 实体; ,,,} ,,} ,/* * ,,*,获取对象的空属性 ,,*/private 才能;static  String [], getNullProperties (Object src), { ,,,//1。获取Bean ,,,BeanWrapper srcBean =, new BeanWrapperImpl (src); ,,,//2。获取Bean的属性描述 ,,,PropertyDescriptor [], pds =, srcBean.getPropertyDescriptors (); ,,,//3。获取Bean的空属性 ,,,Set , 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 字符串[0]); ,,} }
二,启动类
@EnableJpaRepositories (=value “com.hehe.repository",, repositoryBaseClass =, SimpleJpaRepositoryImpl.class) @SpringBootApplication public class  JpaApplication { public 才能;static  void main (String [], args), { ,,,SpringApplication.run (JpaApplication.class, args); ,,} }
三,实体类和通用保存
@ entity null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null nullSpringBoot如何实现JPA的保存方法不更新零属性