解决使用jpa的实体对象转json符串时懒加载问题

解决转json符串时懒加载问题方法(1)

1.导入hibernate5转json的Maven依赖:

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

2.配置MappingJackson2HttpMessageConverter对象:

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    Hibernate5Module module = new Hibernate5Module();
	module.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
	module.enable(Hibernate5Module.Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS);
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
	ObjectMapper mapper = converter.getObjectMapper();
	mapper.registerModule(module);
        return converter;
}

3.在实体类中使用@JsonIgnore加关联属性上,在序列化时忽略掉该属性即可:

@OneToMany
@JoinColumn(name = "fk_uid")
@JsonIgnore
private Set<Comment> comments;

解决转json符串时懒加载问题方法(2)

1.配置MappingJackson2HttpMessageConverter对象:

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
	ObjectMapper mapper = converter.getObjectMapper();
	mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
    return converter;
}

2.在实体类中使用@JsonIgnore加关联属性上,在序列化时忽略掉该属性即可:

@OneToMany
@JoinColumn(name = "fk_uid")
@JsonIgnore
private Set<Comment> comments;
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页