hibernate普通字段懶加載及實現PersistentAttributeInterceptor後產生的集合關聯無法保存的解決方法,及hibernate字節增強插件的使用

首先請查看https://blog.csdn.net/windsigirl123/article/details/60957632,通過模仿這篇文章確實可以產生效果,但是出現ManyToMany的集合關聯時,即存在集合關聯懶加載時,不能單純的模仿博文提到的普通字段的修改方式。

 

該情況下會產生兩個問題:

        1.多對多懶加載關聯無法保存數據,其他集合懶加載關聯類似

        2.如果編寫代碼失誤會導致懶加載的字段無法序列化,即便使用了Hibernate5Module(該情況在使用hibernate字節增強插件時尤其明顯,下面講)。

 

解決方法:

使用hibernate-enhance-maven-plugin字節增強插件,該插件會在編譯時會修改實體到目標值,可以查看反序列化後的效果。

 

使用方法:

maven:

 <plugin>
        <groupId>org.hibernate.orm.tooling</groupId>
        <artifactId>hibernate-enhance-maven-plugin</artifactId>
        <version>4.3.5.Final</version>
        <configuration>
               <failOnError>true</failOnError>
               <enableLazyInitialization>true</enableLazyInitialization>//必須要
               <enableDirtyTracking>true</enableDirtyTracking>
               <enableAssociationManagement>true</enableAssociationManagement>//存在懶加載集合關聯需要加上這個配置
        </configuration>
        <executions>
            <execution>
                <goals>
                    <goal>enhance</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

     然後運行

mvn install -Dmaven.test.skip=true

可反編譯編譯的class文件進行查看確認。

 

問題:

     使用字節增強會導致序列化問題,如果有更好的方法可以分享下。

     我幾番嘗試,無奈,只能將反彙編的替換掉原來的類,再在需要懶加載字段的get方法中加上了判斷session是否有效的語句,如下:

   (注:this.$$_hibernate_getInterceptor())是使用字節增強會在class文件中加上去的)

if (this.$$_hibernate_getInterceptor() instanceof LazyAttributeLoadingInterceptor
  &&
  (
    ((LazyAttributeLoadingInterceptor) this.$$_hibernate_getInterceptor()).getLinkedSession() == null)
  || ((LazyAttributeLoadingInterceptor) this.$$_hibernate_getInterceptor()).getLinkedSession().isClosed()
) {
  return this.filed;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章