Spring整合JPA配置懶載入報錯解決方案
阿新 • • 發佈:2020-01-07
一:報錯no session
因為entitymanager物件在事物提交後就關閉了 報錯的 no session相當於sql的session
解決辦法:解決辦法 在web.xmL配置一個過濾器 使其在這個session中的manager在結束後再關閉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"})這種方式只管當前欄位屬性的懶載入
@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="department_id") @JsonIgnoreProperties(value = {"hibernateLazyInitializer","fieldHandler"}) private Department department;
解決辦法2:重寫:ObjectMapper,然後在applicationContext-mvc.xml 配置這個對映(這個方法一勞永逸,之後在Spring整合JPA進行懶載入的時候,都會避免No serializer的錯誤)
第一步:
public class CustomMapper extends ObjectMapper { public CustomMapper() { this.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 設定 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 為我們自定義擴充套件後的 CustomMapper,解決了返回物件有關係物件的報錯問題 --> <property name="objectMapper"> <bean class="com.logo.aisell.util.CustomMapper"></bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。