【问题标题】:Spring Boot Data JPA default configuration and @JsonManagedReference @JsonBackReferenceSpring Boot Data JPA 默认配置和@JsonManagedReference @JsonBackReference
【发布时间】: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


【解决方案1】:

我相信问题出在序列化上。杰克逊不知道该停在哪里。例如:如果 Group 有 Account 并且 Account 有 Group (manyToMany),它会继续循环序列化。 @JsonManagedReference、@JsonBackReference 或 @JsonIdentityInfo 可以完成这项工作,但只能从一个方向。 我的建议是研究 Spring-data-rest 以及 Hateoas。它更干净,并且支持双向。

【讨论】:

  • 我不需要管理 Hateoas。 Json 应该管理延迟加载。如果惰性未加载,则集合应为 null 或为空。如果已经加载了相关集合,它应该以 json 格式显示。注释不仅为循环提供解决方案,还为 惰性问题 提供解决方案
猜你喜欢
  • 2015-09-27
  • 2018-09-17
  • 2017-06-13
  • 2017-11-29
  • 2016-09-20
  • 1970-01-01
  • 2020-12-12
  • 2012-05-10
相关资源
最近更新 更多