一:报错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"})这种方式只管当前字段属性的懒加载

1    @ManyToOne(fetch = FetchType.LAZY)
2     @JoinColumn(name="department_id")
3     @JsonIgnoreProperties(value = {"hibernateLazyInitializer","handler","fieldHandler"})
4     private Department department;

解决办法2:重写:ObjectMapper,然后在applicationContext-mvc.xml 配置这个映射(这个方法一劳永逸,之后在Spring集成JPA进行懒加载的时候,都会避免No serializer的错误)

第一步:

 

1 public class CustomMapper extends ObjectMapper {
2     public CustomMapper() {
3         this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
4         // 设置 SerializationFeature.FAIL_ON_EMPTY_BEANS 为 false
5         this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
6     }
7 }

 

第二步:配置spring-mvc.xml

 1 <!--注解支持-->
 2 <mvc:annotation-driven>
 3     <mvc:message-converters>
 4         <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
 5             <property name="supportedMediaTypes">
 6                 <list>
 7                     <value>application/json; charset=UTF-8</value>
 8                     <value>application/x-www-form-urlencoded; charset=UTF-8</value>
 9                 </list>
10             </property>
11             <!-- No serializer:配置 objectMapper 为我们自定义扩展后的 CustomMapper,解决了返回对象有关系对象的报错问题 -->
12             <property name="objectMapper">
13                 <bean class="com.logo.aisell.util.CustomMapper"></bean>
14             </property>
15         </bean>
16     </mvc:message-converters>
17 </mvc:annotation-driven>