使用Hibernate / JPA的@OneToOne映射中的外键字段为null

时间:2013-08-19 13:45:30

标签: hibernate one-to-one

我有两个实体DocumentBodyElement,并尝试使用Hibernate 4.2保留它们。 mtdt_t填充正确,但docid表中的外键mtdt_body_tNULL

我看到hibernate试图在没有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相比,@OneToMany映射有什么特别之处吗?我只是模仿我在@OneToMany字段上为@OneToOne所做的工作。

由于

1 个答案:

答案 0 :(得分:0)

  1. OrderColumn注释在OneToMany或ManyToMany关系或元素集合上指定。 OrderColumn注释在关系的一侧指定,该注释引用要订购的集合。订单列在实体或可嵌入类的状态中不可见。 link to documentation

  2. 您在映射时出错。你忘记了mappedBy属性。这意味着entites之间的关系已经被映射,所以你不要这样做两次。你只需使用mappedBy属性(following by this post)说“嘿,它在那里完成”。这是一个有用的例子:Hibernate – One-To-One Example (Annotation)