In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how to use jpa to implement dynamic insertion and modification. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Dynamic insertion and modification of jpa (rewriting save) 1. Dynamically insert @ 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 dynamic attribute private Integer cpuCore; / / cpu user utilization private Double cpuUseRate; / / cpu system utilization private Double cpuSysRate; / / cpu waiting rate private Double cpuWaitRate; / / cpu idle rate private Double cpuIdleRate; / / cpu total utilization private Double cpuCombineRate; private Long serverId }
Key notes:
@ DynamicInsert@EntityListeners (AuditingEntityListener.class) 2. Rewrite save (modification) @ SuppressWarnings (value = "all") public class JpaRepositoryReBuild extends SimpleJpaRepository {private final JpaEntityInformation entityInformation; private final EntityManager em; @ Autowired public JpaRepositoryReBuild (JpaEntityInformation entityInformation, EntityManager entityManager) {super (entityInformation, entityManager); this.entityInformation = entityInformation; this.em = entityManager } / * * General save method: add / selectively update * / @ Override @ Transactional public S save (S entity) {/ / get 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;} / * * get the empty attribute of the object * / private static String [] getNullProperties (Object src) {/ / 1. Get Bean BeanWrapper srcBean = new BeanWrapperImpl (src); / / 2. Get the attribute description of Bean PropertyDescriptor [] pds = srcBean.getPropertyDescriptors (); / / 3. Get the empty attributes of 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 String [0]);}} 3. Launch class @ 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);}}
Key comments:
Repository package scanned by EnableJpaRepositories
Save class overridden by repositoryBaseClass
EnableJpaAuditing makes @ EntityListeners (AuditingEntityListener.class) effective
Why ReFactor save by extending the JPA method and rewriting the save method?
The save method provided by jpa sets the original data to null, and in most cases we only want to update the parameters passed in by ourselves, so there is an override or a new save method.
In order to solve this problem, I searched a lot of solutions on the Internet, but I couldn't find a suitable one, so I studied the source code and first showed several important source codes.
1. SimpleJpaRepository method implementation class, because too much code only shows part of the source code
Public class SimpleJpaRepository implements JpaRepository, JpaSpecificationExecutor {private static final String ID_MUST_NOT_BE_NULL = "The given id must not be null!"; private final JpaEntityInformation entityInformation; private final EntityManager em; private final PersistenceProvider provider; @ Nullable private CrudMethodMetadata metadata; public SimpleJpaRepository (JpaEntityInformation 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 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 getDomainClass () {return this.entityInformation.getJavaType ();} private String getDeleteAllQueryString () {return QueryUtils.getQueryString ("delete from% s x", this.entityInformation.getEntityName ());} @ Transactional public 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 extends TransactionalRepositoryFactoryBeanSupport {@ Nullable private EntityManager entityManager; public JpaRepositoryFactoryBean (Class 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 ();}}
According to the source code and online information, the following schemes are summarized.
1. Rewrite save
Advantages: less invasive, disadvantages will cover the original method.
Create a JpaRepositoryReBuild method that inherits SimpleJpaRepository.
Go directly to the code
Public class JpaRepositoryReBuild extends SimpleJpaRepository {private final JpaEntityInformation entityInformation; private final EntityManager em; @ Autowired public JpaRepositoryReBuild (JpaEntityInformation entityInformation, EntityManager entityManager) {super (entityInformation, entityManager); this.entityInformation = entityInformation; this.em = entityManager } / * General save method: add / selectively update * / @ Override @ Transactional public S save (S entity) {/ / get 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;} / * get the empty attribute of the object * / private static String [] getNullProperties (Object src) {/ / 1. Get Bean BeanWrapper srcBean = new BeanWrapperImpl (src); / / 2. Get the attribute description of Bean PropertyDescriptor [] pds = srcBean.getPropertyDescriptors (); / / 3. Get the empty attributes of 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 String [0]);}}
Startup class plus JpaRepositoryReBuild method
@ EnableJpaRepositories (value = "com.XXX", repositoryBaseClass = JpaRepositoryReBuild.class) @ SpringBootApplication@EnableDiscoveryClient / that is, consumers also register public class SystemApplication {public static void main (String [] args) {SpringApplication.run (SystemApplication.class, args);}} II. Extend the jpa method
1. Create a new method API BaseRepository
@ NoRepositoryBeanpublic interface BaseRepository extends JpaRepository {/ * saves but does not overwrite the original data * @ param entity * @ return * / T saveNotNull (T entity);}
2. Create a BaseRepositoryImpl method
@ NoRepositoryBeanpublic class BaseRepositoryImpl extends SimpleJpaRepository implements BaseRepository {private final JpaEntityInformation entityInformation; private final EntityManager em; public BaseRepositoryImpl (JpaEntityInformation entityInformation, EntityManager entityManager) {super (entityInformation,entityManager); this.entityInformation = entityInformation; this.em = entityManager;} public BaseRepositoryImpl (Class domainClass, EntityManager em) {this (JpaEntityInformationSupport.getEntityInformation (domainClass, em), em) } @ Override @ Transactional public T saveNotNull (T entity) {/ / get 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. Get Bean BeanWrapper srcBean = new BeanWrapperImpl (src); / / 2. Get the attribute description of Bean PropertyDescriptor [] pds = srcBean.getPropertyDescriptors (); / / 3. Get the empty attributes of 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 String [0]);}}
3. Create a factory BaseRepositoryFactory
Public class BaseRepositoryFactory extends JpaRepositoryFactoryBean {public BaseRepositoryFactory (Class
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.