2016-07-03 28 views
0

我擔心之前可能會提出這個問題,但我沒有找到或不能理解類似問題的答案。JPA OneToOne關係自動創建

我有這樣的一個表offerte

@Entity 
public class Offerte extends BaseEntity{ 

    @OneToOne(fetch=FetchType.LAZY) 
    @JoinColumn(name="dossier") 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @NotNull 
    private Dossier dossier; 

具有OneToOne連接表檔案,並在創建一個offerte我希望有自動卷宗創建的。

@Entity 
public class Dossier extends BaseEntity{ 

    @OneToOne(fetch=FetchType.LAZY, mappedBy="dossier") 
    @NotNull 
    private Offerte offerte; 

我已經試過與generationtype自動做到這一點,但我一直在剛開違反

List of constraint violations:[ 
ConstraintViolationImpl{interpolatedMessage='may not be null', 

是否有可能使這種關係自動有效嗎?

編輯

河提出的Java解決方案

@Entity 
public class Offerte extends BaseEntity{ 
    @OneToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL) 
    @JoinColumn(name="dossier") 
    @NotNull 
    private Dossier dossier = new Dossier(); 

提供了以下錯誤

javax.validation.ConstraintViolationException: Validation failed for classes [be.ugent.lca.data.entities.Dossier] during persist time for groups [javax.validation.groups.Default, ] 
List of constraint violations:[ 
ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=offerte, rootBeanClass=class be.ugent.lca.data.entities.Dossier, messageTemplate='{javax.validation.constraints.NotNull.message}'} 
] 
+0

能否請您介紹與列名相關的表? –

+0

你是怎麼表達的@Column(name =「dossier,... annotation?因爲@OneToOne關係不允許這樣做,而且這個關係的兩個列名只是檔案和結果 – turoni

+0

GeneratedValue是非法的在一個關係字段中...它是長,整數,字符串等 –

回答

0

爲了擁有,只要你建立新的檔案對象offerte創造的 - 你應該只是下降down to java解決方案:

public class Dosier { 
    @OneToOne(cascade = CascadeType.ALL) 
    @NotNull 
    private Offerte offerte = new Offerte(....); 
} 

這將有以下後果:

  • 每當新Dosier對象(通過調用構造函數)offerte變量,創建將被填充爲建設新Offerte對象的一部分。
  • 當您保存Dosier這樣說,這將節省offerte對象創建(這就是級聯選項是)
  • 當加載創建檔案 - JPA將加載offerte對象並初始化檔案正確
+0

我想做相反的事,並得到在保存對象之前必須完成的錯誤: org.hibernate.TransientPropertyValueException:非空屬性引用瞬態值 - 在當前操作之前必須保存瞬態實例:be.ugent。 lca.data。entities.Offerte.dossier - > be.ugent.lca.data.entities.Dossier – turoni

+0

確保您添加(cascade = CascadeType.ALL)到Offerte#dossier字段。 – river

+0

也請看看[答案](http://stackoverflow.com/a/10687818/6529383)來幫助你正確映射一對一關聯。 – river