溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring集成JPA配置懶加載報錯如何解決

發(fā)布時間:2021-06-15 15:11:25 來源:億速云 閱讀:267 作者:Leah 欄目:編程語言

Spring集成JPA配置懶加載報錯如何解決,針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

一:報錯no session

因為entitymanager對象在事物提交后就關(guān)閉了 報錯的 no session相當于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"})這種方式只管當前字段屬性的懶加載

    @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name="department_id")
   @JsonIgnoreProperties(value = {"hibernateLazyInitializer","handler","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);
    // 設(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 為我們自定義擴展后的 CustomMapper,解決了返回對象有關(guān)系對象的報錯問題 -->
      <property name="objectMapper">
        <bean class="com.logo.aisell.util.CustomMapper"></bean>
      </property>
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>

關(guān)于Spring集成JPA配置懶加載報錯如何解決問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI