首页 > 解决方案 > 如何序列化包含 LAZY 关联的 json

问题描述

我有一个与获取类型 LAZY的Person实体@ManyToOne关联的实体。Contact我正在使用 spring-boot 来公开 REST API。我的 POST 调用之一包含嵌套 JSON 以保存父实体Person以及关联Contact

由于Contactfetch 类型是 LAZY,我遇到了以下异常

    ERROR 17415 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 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) (through reference chain: com.example.rest.RestResultObject["results"]->java.util.ArrayList[0]->com.example.model.Person["contact"]->com.example.model.Contact_$$_jvst8d1_4["handler"])] with root cause

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 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) (through reference chain: com.example.rest.RestResultObject["results"]->java.util.ArrayList[0]->com.example.model.Person["contact"]->com.example.model.Contact_$$_jvst8d1_4["handler"])
at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77) ~[jackson-databind-2.9.3.jar:2.9.3]

无需将联系人更改为 EAGER。有没有最好的方法来解决这个问题?

更新:

人.java

public class Person {
    private long id;
    private String name;
    private String rno;
    @ManyToOne(fetch = FetchType.LAZY)
    private Contact contact;

    // Getters and setters
}

联系方式.java

public class Contact {
    private long id;
    private String info;
    @OneToMany
    private List<Person> persons;
}

标签: javaspring-bootjpaserializationjackson

解决方案


我添加了以下内容

  • 每个对象上的@Entity
  • 更改longLongin id,如果您使用 spring data JPA,这将对您有所帮助
  • 添加@Id以将 id 声明为主键
  • @JsonBackReference&@JsonManagedReference避免杰克逊的无限循环

人物类

@Entity
public class Person {

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;

 private String name;

 private String rno;

 @JsonManagedReference
 @ManyToOne(fetch = FetchType.LAZY)
 private Contact contact;

 //setter & getter

}

接触类

@Entity
public class Contact {

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;

 private String info;

 @JsonBackReference
 @OneToMany(cascade = CascadeType.ALL, mappedBy = "contact")
 private List<Person> persons;

 //setter & getter
}

并添加一个依赖

<dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-hibernate5</artifactId>
</dependency>

最后添加一个新配置

@Configuration
public class JacksonConfig {

@Bean
public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() {
    return new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
            jacksonObjectMapperBuilder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            jacksonObjectMapperBuilder.modules(new Hibernate5Module());
        }

    };
}
}

推荐阅读