Spring集成JPA配置懶加載報錯解決方案
一:報錯no session
因為entitymanager對象在事物提交后就關(guān)閉了 報錯的 no session相當(dāng)于sql的session
解決辦法:解決辦法 在web.xmL配置一個過濾器 使其在這個session中的manager在結(jié)束后再關(guān)閉open
<!--配置openmanager--> <filter> <filter-name>openEntity</filter-name> <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openEntity</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
在完成上面的配置后會報第二個錯誤
二 報錯no serializer報錯
解決辦法1:在需要配置懶加載的字段上加 @JsonIgnoreProperties(value = {"hibernateLazyInitializer","handler","fieldHandler"})這種方式只管當(dāng)前字段屬性的懶加載
@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="department_id") @JsonIgnoreProperties(value = {"hibernateLazyInitializer","handler","fieldHandler"}) private Department department;
解決辦法2:重寫:ObjectMapper,然后在applicationContext-mvc.xml 配置這個映射(這個方法一勞永逸,之后在Spring集成JPA進(jìn)行懶加載的時候,都會避免No serializer的錯誤)
第一步:
public class CustomMapper extends ObjectMapper { public CustomMapper() { this.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 設(shè)置 SerializationFeature.FAIL_ON_EMPTY_BEANS 為 false this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); } }
第二步:配置spring-mvc.xml
<!--注解支持--> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json; charset=UTF-8</value> <value>application/x-www-form-urlencoded; charset=UTF-8</value> </list> </property> <!-- No serializer:配置 objectMapper 為我們自定義擴(kuò)展后的 CustomMapper,解決了返回對象有關(guān)系對象的報錯問題 --> <property name="objectMapper"> <bean class="com.logo.aisell.util.CustomMapper"></bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring源碼解析之循環(huán)依賴的實(shí)現(xiàn)流程
這篇文章主要介紹了Spring源碼解析之循環(huán)依賴的實(shí)現(xiàn)流程,文章基于Java的相關(guān)內(nèi)容展開循環(huán)依賴的實(shí)現(xiàn)流程,需要的小伙伴可以參考一下2022-07-07記一次用IDEA打開java項目后不能運(yùn)行的解決方法
這篇文章主要介紹了記一次用IDEA打開java項目后不能運(yùn)行的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03Java Class.forName()用法和newInstance()方法原理解析
這篇文章主要介紹了Java Class.forName()用法和newInstance()方法原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08SpringBoot實(shí)現(xiàn)WebSocket即時通訊的示例代碼
本文主要介紹了SpringBoot實(shí)現(xiàn)WebSocket即時通訊的示例代碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04