2016-07-05 111 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