如何序列化包含LAZY关联的json [英] How to serialize a json containing LAZY associations

查看:189
本文介绍了如何序列化包含LAZY关联的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having an Person entity which has @ManyToOne association with Contact entity with fetch type LAZY. I am using spring-boot to expose REST API. One of my POST call contains nested JSON to save the parent entity Person along with association Contact

由于Contact提取类型为LAZY,我遇到了以下异常

Since Contact fetch type is LAZY, I am encountering into following exception

    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]

不将Contact更改为EAGER.有什么最佳方法可以解决此问题?

Without changing Contact to EAGER. Is there any best way to solve this problem?

已更新:

Person.java

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

    // Getters and setters
}

Contact.java

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

推荐答案

我添加了以下内容

  • 每个对象上的@Entity
  • 将ID中的long改为Long,如果您使用spring数据jpa,这将为您提供帮助
  • 添加@Id以将id声明为主键
  • @JsonBackReference& @JsonManagedReference避免jacson造成无限循环

人员班

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

    };
}
}

这篇关于如何序列化包含LAZY关联的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆