fetch=FetchType.LAZY 时,spring boot jackson 返回数据时会出错。
可配置使用Hibernate4Module 帮助解决:
@Configuration
public class JacksonConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(jacksonMessageConverter());
super.configureMessageConverters(converters);
}
private MappingJackson2HttpMessageConverter jacksonMessageConverter() {
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Hibernate4Module());
messageConverter.setObjectMapper(mapper);
return messageConverter;
}
}
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate4</artifactId>
<version>2.4.6</version>
</dependency>
fetch=FetchType.EAGER,遇到查询很快,但hibernate 处理很慢的情况。
究其原因在于hibernate 默认使用FetchMode.JOIN,产生的sql 虽然执行很快,几十或几百毫秒,但是,结果记录有几万甚至几十万,hibernate 处理需要花费数秒或数十秒。
在属性上(实体集合)配置注解@Fetch(FetchMode.SUBSELECT),使用子查询方式查询子集合。结果花费时间为几百毫秒。
附上注解说明:
public enum FetchMode {
/**
* use a select for each individual entity, collection, or join load.
*/
SELECT,
/**
* use an outer join to load the related entities, collections or joins.
*/
JOIN,
/**
* use a subselect query to load the additional collections.
*/
SUBSELECT
}