【发布时间】:2016-11-07 18:45:12
【问题描述】:
我使用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 安全角色做一些事情,我的配置中有这一部分
@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");
}
}
所以我无法理解我应该初始化哪个角色集合,以防我的损坏对象没有任何相关实体。
【问题讨论】:
-
验证您的 spring.jpa.open-in-view 在 application.properties 中是否为真。如果它是假的,这正是你会看到的行为(默认应该是真的)
-
我将 spring.jpa.open-in-view 设置为 false。而且我相信如果没有 json 注释,这种行为可能会发生。但是我已经添加了
标签: spring-boot jackson lazy-loading spring-data-jpa fetch