我使用spring boot默认配置。我的简单项目与关系映射中的Eager加载类型一起正常工作。如果我尝试在OneToMany或ManyToMany关系中应用延迟加载,我会遇到问题而不是。
如果使用特殊注释
,它们可以解决问题// to mark class field
@JsonManagedReference
@JsonBackReference
// to mark class
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
但由于其他问题
,它无效Hibernate: select projectinf0_.id as id1_4_, projectinf0_.description as descript2_4_, projectinf0_.name as name3_4_ from project_info projectinf0_
2016-07-05 22:32:45 [http-nio-8080-exec-1] WARN o.s.w.s.m.s.DefaultHandlerExceptionResolver.handleHttpMessageNotWritable(400) - Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: failed to lazily initialize a collection of role: com.vl.pmanager.domain.model.ProjectInfo.tags, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.vl.pmanager.domain.model.ProjectInfo["tags"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.vl.pmanager.domain.model.ProjectInfo.tags, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.vl.pmanager.domain.model.ProjectInfo["tags"])
我明白了,我应该修复懒得初始化角色集合。如果我必须对spring security角色做一些事情,我在配置中有这个部分
@Configuration
static class SecurityConfig extends GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("user").roles("USER").and()
.withUser("hero").password("hero").roles("USER", "HERO");
}
}
所以我无法理解我应该初始化哪个角色集合,如果我没有任何相关实体到我的损坏对象。
答案 0 :(得分:1)
我认为问题在于序列化。杰克逊不知道在哪里停下来。例如:如果Group有Account和Account有Group(manyToMany),它会继续循环序列化。 @JsonManagedReference,@ JsonBackReference或@JsonIdentityInfo可以完成工作,但只能从一个方向开始。 我建议的是调查 Spring-data-rest 以及 Hateoas 。它更清洁,并支持双向。