使用jpa之動(dòng)態(tài)插入與修改(重寫save)_第1頁
使用jpa之動(dòng)態(tài)插入與修改(重寫save)_第2頁
使用jpa之動(dòng)態(tài)插入與修改(重寫save)_第3頁
使用jpa之動(dòng)態(tài)插入與修改(重寫save)_第4頁
使用jpa之動(dòng)態(tài)插入與修改(重寫save)_第5頁
已閱讀5頁,還剩8頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

第使用jpa之動(dòng)態(tài)插入與修改(重寫save)目錄jpa之動(dòng)態(tài)插入與修改(重寫save)1.動(dòng)態(tài)插入2.重寫save(修改)3.啟動(dòng)類擴(kuò)展JPA方法,重寫save方法為什么要重構(gòu)save?一、重寫save二、擴(kuò)張jpa方法

jpa之動(dòng)態(tài)插入與修改(重寫save)

1.動(dòng)態(tài)插入

@Data

@Entity

@DynamicInsert

@Table(name="cpu_dynamics_information")

@EntityListeners(AuditingEntityListener.class)

publicclassCpuDynamicsInformationextendsCommonEntityimplementsSerializable{

privatestaticfinallongserialVersionUID=-662804563658253624L;

//cpu動(dòng)態(tài)屬性

privateIntegercpuCore;

//cpu用戶使用率

privateDoublecpuUseRate;

//cpu系統(tǒng)使用率

privateDoublecpuSysRate;

//cpu等待率

privateDoublecpuWaitRate;

//cpu空閑率

privateDoublecpuIdleRate;

//cpu總的使用率

privateDoublecpuCombineRate;

privateLongserverId;

關(guān)鍵注解:

@DynamicInsert

@EntityListeners(AuditingEntityListener.class)

2.重寫save(修改)

@SuppressWarnings(value="all")

publicclassJpaRepositoryReBuildT,IDextendsSimpleJpaRepositoryT,ID{

privatefinalJpaEntityInformationT,entityInformation;

privatefinalEntityManagerem;

@Autowired

publicJpaRepositoryReBuild(

JpaEntityInformationT,entityInformation,EntityManagerentityManager){

super(entityInformation,entityManager);

this.entityInformation=entityInformation;

this.em=entityManager;

/**通用save方法:新增/選擇性更新*/

@Override

@Transactional

publicSextendsTSsave(Sentity){

//獲取ID

IDentityId=(ID)this.entityInformation.getId(entity);

TmanagedEntity;

TmergedEntity;

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;

returnentity;

/**獲取對(duì)象的空屬性*/

privatestaticString[]getNullProperties(Objectsrc){

//1.獲取Bean

BeanWrappersrcBean=newBeanWrapperImpl(src);

//2.獲取Bean的屬性描述

PropertyDescriptor[]pds=srcBean.getPropertyDescriptors();

//3.獲取Bean的空屬性

SetStringproperties=newHashSet();

for(PropertyDescriptorpropertyDescriptor:pds){

StringpropertyName=propertyDescriptor.getName();

ObjectpropertyValue=srcBean.getPropertyValue(propertyName);

if(StringUtils.isEmpty(propertyValue)){

srcBean.setPropertyValue(propertyName,null);

properties.add(propertyName);

returnproperties.toArray(newString[0]);

3.啟動(dòng)類

@EnableJpaAuditing

@SpringBootApplication(exclude=MongoAutoConfiguration.class)

@EnableJpaRepositories(

value={"com.fooww.research.repository","com.fooww.research.shiro.repository"},

repositoryBaseClass=JpaRepositoryReBuild.class)

publicclassMonitorServerApplication{

publicstaticvoidmain(String[]args){

SpringApplication.run(MonitorServerApplication.class,args);

關(guān)鍵注釋:

EnableJpaRepositories掃描的repository包

repositoryBaseClass重寫的save類

EnableJpaAuditing使@EntityListeners(AuditingEntityListener.class)生效

擴(kuò)展JPA方法,重寫save方法

為什么要重構(gòu)save?

jpa提供的save方法會(huì)將原有數(shù)據(jù)置為null,而大多數(shù)情況下我們只希望跟新自己傳入的參數(shù),所以便有了重寫或者新增一個(gè)save方法。

本著解決這個(gè)問題,網(wǎng)上搜了很多解決方案,但是沒有找到合適的,于是自己研究源碼,先展示幾個(gè)重要源碼

1、SimpleJpaRepository方法實(shí)現(xiàn)類,由于代碼過多只展示部分源碼

publicclassSimpleJpaRepositoryT,IDimplementsJpaRepositoryT,ID,JpaSpecificationExecutorT{

privatestaticfinalStringID_MUST_NOT_BE_NULL="Thegivenidmustnotbenull!";

privatefinalJpaEntityInformationT,entityInformation;

privatefinalEntityManagerem;

privatefinalPersistenceProviderprovider;

@Nullable

privateCrudMethodMetadatametadata;

publicSimpleJpaRepository(JpaEntityInformationT,entityInformation,EntityManagerentityManager){

Assert.notNull(entityInformation,"JpaEntityInformationmustnotbenull!");

Assert.notNull(entityManager,"EntityManagermustnotbenull!");

this.entityInformation=entityInformation;

this.em=entityManager;

vider=PersistenceProvider.fromEntityManager(entityManager);

publicSimpleJpaRepository(ClassTdomainClass,EntityManagerem){

this(JpaEntityInformationSupport.getEntityInformation(domainClass,em),em);

publicvoidsetRepositoryMethodMetadata(CrudMethodMetadatacrudMethodMetadata){

this.metadata=crudMethodMetadata;

@Nullable

protectedCrudMethodMetadatagetRepositoryMethodMetadata(){

returnthis.metadata;

protectedClassTgetDomainClass(){

returnthis.entityInformation.getJavaType();

privateStringgetDeleteAllQueryString(){

returnQueryUtils.getQueryString("deletefrom%sx",this.entityInformation.getEntityName());

@Transactional

publicSextendsTSsave(Sentity){

if(this.entityInformation.isNew(entity)){

this.em.persist(entity);

returnentity;

}else{

returnthis.em.merge(entity);

}

2、JpaRepositoryFactoryBean

publicclassJpaRepositoryFactoryBeanTextendsRepositoryS,ID,S,IDextendsTransactionalRepositoryFactoryBeanSupportT,S,ID{

@Nullable

privateEntityManagerentityManager;

publicJpaRepositoryFactoryBean(ClassextendsTrepositoryInterface){

super(repositoryInterface);

@PersistenceContext

publicvoidsetEntityManager(EntityManagerentityManager){

this.entityManager=entityManager;

publicvoidsetMappingContext(MappingContext,mappingContext){

super.setMappingContext(mappingContext);

protectedRepositoryFactorySupportdoCreateRepositoryFactory(){

Assert.state(this.entityManager!=null,"EntityManagermustnotbenull!");

returnthis.createRepositoryFactory(this.entityManager);

protectedRepositoryFactorySupportcreateRepositoryFactory(EntityManagerentityManager){

returnnewJpaRepositoryFactory(entityManager);

publicvoidafterPropertiesSet(){

Assert.state(this.entityManager!=null,"EntityManagermustnotbenull!");

super.afterPropertiesSet();

}

根據(jù)源碼及網(wǎng)上資料總結(jié)如下方案

一、重寫save

優(yōu)勢(shì):侵入性小,缺點(diǎn)將原方法覆蓋。

創(chuàng)建JpaRepositoryReBuild方法繼承SimpleJpaRepository。

直接上代碼

publicclassJpaRepositoryReBuildT,IDextendsSimpleJpaRepositoryT,ID{

privatefinalJpaEntityInformationT,entityInformation;

privatefinalEntityManagerem;

@Autowired

publicJpaRepositoryReBuild(JpaEntityInformationT,entityInformation,EntityManagerentityManager){

super(entityInformation,entityManager);

this.entityInformation=entityInformation;

this.em=entityManager;

*通用save方法:新增/選擇性更新

@Override

@Transactional

publicSextendsTSsave(Sentity){

//獲取ID

IDentityId=(ID)this.entityInformation.getId(entity);

TmanagedEntity;

TmergedEntity;

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;

returnentity;

*獲取對(duì)象的空屬性

privatestaticString[]getNullProperties(Objectsrc){

//1.獲取Bean

BeanWrappersrcBean=newBeanWrapperImpl(src);

//2.獲取Bean的屬性描述

PropertyDescriptor[]pds=srcBean.getPropertyDescriptors();

//3.獲取Bean的空屬性

SetStringproperties=newHashSet();

for(PropertyDescriptorpropertyDescriptor:pds){

StringpropertyName=propertyDescriptor.getName();

ObjectpropertyValue=srcBean.getPropertyValue(propertyName);

if(StringUtils.isEmpty(propertyValue)){

srcBean.setPropertyValue(propertyName,null);

properties.add(propertyName);

returnproperties.toArray(newString[0]);

}

啟動(dòng)類加上JpaRepositoryReBuild方法

@EnableJpaRepositories(value="com.XXX",repositoryBaseClass=JpaRepositoryReBuild.class)

@SpringBootApplication

@EnableDiscoveryClient//即消費(fèi)也注冊(cè)

publicclassSystemApplication{

publicstaticvoidmain(String[]args){

SpringApplication.run(SystemApplication.class,args);

}

二、擴(kuò)張jpa方法

1、新建新增方法接口BaseRepository

@NoRepositoryBean

publicinterfaceBaseRepositoryT,IDextendsSerializableextendsJpaRepositoryT,ID{

*保存但不覆蓋原有數(shù)據(jù)

*@paramentity

*@return

TsaveNotNull(Tentity);

}

2、創(chuàng)建BaseRepositoryImpl方法

@NoRepositoryBean

publicclassBaseRepositoryImplT,IDextendsSerializableextendsSimpleJpaRepositoryT,IDimplementsBaseRepositoryT,ID{

privatefinalJpaEntityInformationT,entityInformation;

privatefinalEntityManagerem;

publicBaseRepositoryImpl(JpaEntityInformationT,entityInformation,EntityManagerentityManager){

super(entityInformation,entityManager);

this.entityInformation=entityInformation;

this.em=entityManager;

publicBaseRepositoryImpl(ClassTdomainClass,EntityManagerem){

this(JpaEntityInformationSupport.getEntityInformation(domainClass,em),em);

@Override

@Transactional

publicTsaveNotNull(Tentity){

//獲取ID

IDentityId=(ID)this.entityInformation.getId(entity);

TmanagedEntity;

TmergedEntity;

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;

returnmergedEntity;

privatestaticString[]getNullProperties(Objectsrc){

//1.獲取Bean

BeanWrappersrcBean=newBeanWrapperImpl(src);

//2.獲取Bean的屬性描述

PropertyDescriptor[]pds=srcBean.getPropertyDescriptors();

//3.獲取Bean的空屬性

SetStringproperties=newHashSet();

for(PropertyDescriptorpropertyDescriptor:pds){

StringpropertyName=propertyDescriptor.getName();

ObjectpropertyValue=srcBean.getPropertyValue(propertyName);

if(StringUtils.isEmpty(propertyValue)){

srcBean.setPropertyValue(propertyName,null);

properties.add(propertyName);

returnproperties.toArray(newString[0]);

}

3、創(chuàng)建工廠BaseRepositoryFactory

publicclassBaseRepositoryFactoryRextendsJpaRepositoryT,ID,T,ID

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論