Hibernate加入表

时间:2016-01-07 14:43:10

标签: java oracle hibernate

我有两张桌子:

ID | NAME | EMAIL_ID (foreign key of Email.ID)

电子邮件

ID | EMAIL_ADDRESS

我需要将数据撤回到以下实体中,但我不确定如何使用注释将PERSON.EMAIL_ID加入EMAIL.ID

@Entity
@Table(name = "PERSON")
public class PersonEntity {
    @Column(name = "ID")
    private String id;

    @Column(name = "NAME")
    private String name;

    // How do I do a one to one join here?
    private String emailAddress;
}

如何正确使用注释,以便emailAddress字段映射到EMAIL.EMAIL_ADDRESS列?

2 个答案:

答案 0 :(得分:2)

您的Person实体应该直接加入Email实体而不是emailAddress属性。

@Entity
@Table(name = "PERSON")
public class PersonEntity {
    @Column(name = "ID")
    private String id;

    @Column(name = "NAME")
    private String name;

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "person", cascade = CascadeType.ALL)
    private Email email;
}

但是只有电子邮件才有实体。您是否只确保电子邮件是唯一的?在这种情况下,Person实体可以拥有一个@Column(unique = true)的电子邮件地址。

@Entity
@Table(name = "PERSON")
public class PersonEntity {
    @Column(name = "ID")
    private String id;

    @Column(name = "NAME")
    private String name;

    @Column(unique = true)
    private String emailAddress;
}

答案 1 :(得分:0)

你通常不会在Hibernate中加入。而是使用映射和HQL。 这里有一个很好的例子: http://viralpatel.net/blogs/hibernate-one-to-one-mapping-tutorial-using-annotation/