这是后续问题:
Spring Hibernate FetchType LazyInitializationException even when not calling association
我试图实施这个解决方案,但没有运气。我想知道我是否在某些地方犯了错误......
Avoid Jackson serialization on non fetched lazy objects
的applicationContext.xml
<context:annotation-config />
<context:component-scan base-package="com.app"></context:component-scan>
<tx:annotation-driven />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.app.service.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- Hibernate server settings -->
HibernateAwareObjectMapper
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
public class HibernateAwareObjectMapper extends ObjectMapper {
public HibernateAwareObjectMapper() {
Hibernate4Module hm = new Hibernate4Module();
registerModule(hm);
}
}
的pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.2.Final</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate4</artifactId>
<version>2.8.6</version>
</dependency>
我仍然收到以下错误
Hibernate: select this_.person_id as person_i1_1_0_, this_.age as age2_1_0_, this_.name as name3_1_0_ from person this_
[Person [person_id=1, name=eric, age=11]]
Jun 20, 2017 12:37:29 AM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpMessageNotWritable
WARNING: Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: failed to lazily initialize a collection of role: com.app.person.Person.phones, could not initialize proxy - no Session (through reference chain: java.util.HashMap["results"]->java.util.ArrayList[0]->com.app.person.Person["phones"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException:
请非常感谢任何见解或建议...
最后一件事,我不想把它作为JsonIgnore推销,因为它永远不会被序列化。有时候我需要检索Lazy对象。
谢谢
答案 0 :(得分:0)
解决这个问题有两种方法。第一个是通过使用@JsonIgnore在此请求中不需要此信息时忽略电话。
第二种方式是在关闭交易之前加载手机。要做到这一点,你可以使用Hibernate.initialize(person.getPhones())
。或者,您可以使用集合上的@OneToMany(fetch = FetchType.EAGER)
来获取此集合。