解決使用jpa的實體物件轉json符串時懶載入問題

weixin_49091968發表於2020-12-01

解決轉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;

相關文章