栖梧桐 2020-07-08
今天在Spring Boot项目中使用JPA(Hibernate)进行数据库访问时,
spring: jpa: generate-ddl: false show-sql: true hibernate: ddl-auto: none open-in-view: true
查询一个实体对象时出现异常:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.xgclassroom.model.User$HibernateProxy$PpGM4JxY["hibernateLazyInitializer"])
仔细看了下报错信息,发现直接原因是:jackson在对hibernate的持久化实体类的代理对象进行序列化时,代理类中的"hibernateLazyInitializer"属性为空,触发了系列化规划SerializationFeature.FAIL_ON_EMPTY_BEANS,即“出现空Bean时触发序列化失败”!
"hibernateLazyInitializer"属性为空之所以为空是因为我们禁用了延迟加载(open-in-view: true),设为false又会引发no Session错误。
报错信息中告诉我们可以通过禁用jackson的SerializationFeature.FAIL_ON_EMPTY_BEANS这条系列化规则来避免该异常(异常信息中的红色字所示),我们可以通过以下方式使用禁用了SerializationFeature.FAIL_ON_EMPTY_BEANS规则的新ObjectMapper替换默认的ObjectMapper的方法来达到目的:
@SpringBootApplication @Configuration public class ProviderUserApplication { public static void main(String[] args) { SpringApplication.run(ProviderUserApplication.class, args); } @Bean public ObjectMapper objectMapper() { return new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); } }
当然,也可以直接在相应的要实体类上通过@JsonIgnoreProperties忽略掉为空的属性的系列化:
@Getter @Setter @Entity @JsonIgnoreProperties(value = {"hibernateLazyInitializer"}) public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column private String username; @Column private String name; @Column private Integer age; @Column private BigDecimal balance; }
下面来看一下两种方法重到的系列化结果样例:
{"id":1,"username":"account1","name":"张三","age":20,"balance":100.00,"hibernateLazyInitializer":{}}
{"id":1,"username":"account1","name":"张三","age":20,"balance":100.00}