Spring集成JPA配置懒加载报错解决方案

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring集成JPA配置懒加载报错解决方案

  2021-04-02 我要评论

一:报错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","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);
    // 设置 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>
您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们