2016-07-05 114 views
0

我使用spring引导默认配置。我的简单项目在关系映射中的Eager加载类型中正常工作。如果我尝试在OneToMany或ManyToMany关系中应用延迟加载,我会遇到问题。Spring引导数据JPA默认配置和@JsonManagedReference @JsonBackReference

他们告诉我们,如果使用特殊的注解来

// 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"]) 

我看,我应该修复无法懒洋洋地初始化工作收集角色。如果我必须做的带弹簧的安全角色的东西,我有这部分我的配置

@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

确认您的** spring.jpa.open-in-view **在application.properties中为true。这就是你会看到的行为,如果它是假的(默认应该是true) – jp86

+0

我设置** spring.jpa.open-in-view **为false。我相信这种行为可以是,如果没有json注释。但我已经加了 – Sergii

回答

1

我相信问题出在序列化中。杰克逊不知道该停在哪里。例如:如果组具有帐户和帐户有组(manyToMany),它将继续在循环中序列化。 @JsonManagedReference,@JsonBackReference或@JsonIdentityInfo可以做的工作,但只有从的一个方向。 我能建议的是看看Spring-data-rest,以及Hateoas。它更清洁,并且支持双向。

+0

我不需要管理** Hateoas **。 Json应该管理延迟加载。如果懒惰未加载收集应该为空或空。如果已经加载相关集合,它应该显示在json中。注释不仅为循环提供解决方案,而且也为_lazy问题提供解决方案 – Sergii