解决noSerializer问题

在Spring系列和JPA集成的时候配置了懒加载后报以下错误:

No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )

这是由于Jpa底层处理的时候机制问题

这是由于hibernate底层在添加一些字段然后转换成json处理时出现的一个问题

解决办法一:在配置了懒加载的字段上面加上注解

@JsonIgnoreProperties(value={“hibernateLazyInitializer”,”handler”,”fieldHandler”})

解决方法二

创建一个类CustomMapper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.ifueen.aishell.commons;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

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);
}
}

然后在applicationContext-mvc.xml中加入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<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.ifueen.aishell.commons.CustomMapper"></bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
❤赏点钱让我买杯快乐水8❤