2013-08-19 207 views
5

我有兩個實體DocumentBodyElement,並試圖用Hibernate 4.2持久化它們。 mtdt_t正確填充,但mtdt_body_t表中的外鍵docidNULL@OneToOne與休眠/ JPA映射的外鍵字段null

我看到休眠試圖插入沒有docid值。 insert into mtdt_body_t values ()

@Entity 
@Table(name = "mtdt_t") 
public class Document implements Serializable { 

    @Id 
    @Column(name = "docid", unique = true, nullable = false) 
    private String docid; 

    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) 
    @OrderColumn 
    @JoinColumn(name = "docid", nullable = false) 
    private BodyElement bodyElement; 

    public String getDocid() { 
     return docid; 
    } 

    public void setDocid(String docid) { 
     this.docid = docid; 
    } 

    public BodyElement getBodyElement() { 
     return bodyElement; 
    } 

    public void setBodyElement(BodyElement bodyElement) { 
     this.bodyElement = bodyElement; 
    } 

} 

@Entity 
@Table(name = "mtdt_body_t") 
public class BodyElement implements Serializable { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    @OneToOne 
    @JoinColumn(name = "docid", insertable = false, updatable = false, nullable = false) 
    private Document document; 

    public BodyElement() { 
    } 

    public Long getId() { 
     return id; 
    } 

    public void setId(Long id) { 
     this.id = id; 
    } 

    public Document getDocument() { 
     return document; 
    } 

    public void setDocument(Document document) { 
     this.document = document; 
    } 

} 

我離開了另一個領域。在Document我有,

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) 
@OrderColumn 
@JoinColumn(name = "docid", nullable = false) 
@XmlPath("head/meta/kb:keywords/kb:keyword") 
private Set<Keyword> keywords; 

Keyword類我都映射爲外鍵,

@ManyToOne 
@JoinColumn(name = "docid", insertable = false, updatable = false, nullable = false) 
@XmlTransient 
private Document document; 

docid領域是從來沒有NULL

@OneToOne Mapping與@OneToMany相比有什麼特別之處嗎?我只是模仿我在@OneToOne字段中爲@OneToMany所做的工作。

由於

回答

0
  1. 的OrderColumn註解上的一對多或多對多關係或上的元素集合中指定。 OrderColumn註釋是在引用要訂購的集合的關係的側面指定的。訂單列不可見作爲實體或可嵌入類的狀態的一部分。 link to documentation

  2. 您在映射中存在錯誤。你忘了關於mappedBy屬性。這意味着實體之間的關係已經被映射,所以你不會這樣做兩次。你只需使用mappedBy屬性(following by this post)就可以說「嘿它在那裏完成」。這裏是有用的例子:Hibernate – One-To-One Example (Annotation)

+0

我跟着mkyong的例子使用'mappedBy',但它仍然離開'docid'字段。這一次'docid'專欄甚至不存在。 – wsams