异常“非法尝试将集合与两个会话关联”是众所周知的,并且当在两个不同的会话中引用同一实体时会发生这种情况。我有一个 spring mvc 集成测试,它发生在哪里,需要一个建议如何使它正常工作。
另外值得注意的是,我正在使用https://github.com/FasterXML/jackson-datatype-hibernate,这有助于在将域对象转换为 json 时避免 LazyInitializationException。我的猜测是它在内部打开 Hibernate 会话以获取惰性关系。
这是一个测试:
@RunWith(SpringJunit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({
@ContextConfiguration(name = "root", locations = "classpath:application.xml"),
@ContextConfiguration(name = "servlet", locations = "classpath:servlet.xml")
})
@TransactionalConfiguration
public class IntegrationTest {
private MockMvc mockMvc;
//some initialization and autowiring
@Test
@Transactional // It is important to rollback all the db changes after the test. So, it's a common pattern to make all tests transactional.
// So here we have HibernateSession#1
public void testController() {
// repository is spring-data-jpa repository
// but you may think of it as a DAO which returns persisted
// hibernate entity
ChildEntity child = new ChildEntity();
child = childRepository.save();
MyEntity entity = new MyEntity();
entity.setChildEntities(Collections.singletoneList(child));
entity = repository.save(entity);
// entity and its child are still preserved in the HibernateSession#1
mockMvc.perform(get("/entity/by_child_id/" + child.getId()).andExpect(status().is("200"));
}
}
@RestController
@RequestMapping("/entity")
public class MyController {
@RequestMapping("by_child_id/{id}")
// My guess: Jackson hibernate mapper will open another session
// and try to fetch children
// So here we have HibernateSession#2
public MyEntity getByChildId(@PathVariable("id") childId) {
return repository.findByChildrenId(childId);
}
}
@Entity
public class MyEntity {
@OneToMany(fetch = FetchType.EAGER)
private List<ChildEntity> children;
}
//and finally here is a piece of servlet.xml
<mvc:annotation-driven>
<mvc:message-converters>
<!-- Use the HibernateAware mapper instead of the default -->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="path.to.your.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
我的例外是:
Caused by org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions: [MyEntity.children#1]
at com.fasterxml.jackson.datatype.hibernate4.PersistentCollectionSerializer.inistializeCollection(PersistentCollectionSerializer.java:195)
at com.fasterxml.jackson.datatype.hibernate4.PersistentCollectionSerializer.findLazyValue(PersistentCollectionSerializer.java:160)
at com.fasterxml.jackson.datatype.hibernate4.PersistentCollectionSerializer.serialize(PersistentCollectionSerializer.java:115)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:505)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase:639)
jackson-databind-2.4.2.jar
那么,除了避免使用 jackson-hibernate-mapper 进行测试外,有什么方法可以避免这个问题?使用 DTO 和 Dozer 代替域对象不被视为解决方案(它将在未来完成,但不是现在)。
提前致谢