1

我有一张婚姻状况表,其中包含“单身”、“已婚”等值。

我有一个以 marital_status_id 作为外键的 Person 表。

我如何映射这个?任何帮助将不胜感激,因为我是 Hibernate 的新手。或者我不需要这个,因为人与婚姻状况之间没有关系,而只是一个参考?

4

4 回答 4

2

首先,婚姻状况不需要单独的表格(是吗?真的吗?)。可以用单个字符处理(非常高效)

但是,在您的情况下,

@Entity
@Table(name="PERSON")
Class Person(){
    @Id
    @Column(name = "ID", unique = true, nullable = false, precision = 15, scale = 0)
    private Long id;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="MARITAL_STATUS_ID")
    MaritalStatus maritalStatus;
}

@Entity
@Table(name="MARITAL_STATUS")
Class MaritalStatus(){
    @Id
    @Column(name = "ID", unique = true, nullable = false, precision = 15, scale = 0)
    private Long id;

    @OneToMany(mappedBy="maritalStatus")
    Set<Person> persons;
}
于 2012-12-17T07:16:01.383 回答
1

Marital Status 应该在 Java 中表示为枚举,以排除不必要的连接,因为没有那么多选项,它们永远不会改变。
检查@Enumerated(EnumType.STRING)注释:http ://docs.oracle.com/javaee/6/api/javax/persistence/Enumerated.html

于 2012-12-17T06:56:12.633 回答
0

您还没有指定是坚持建立一对一的关系还是不在乎,以及是否更喜欢使用 Enum 而不是 Class。

这个链接提供了一些关于休眠中一对一映射的有用信息,如果你想在你的表之间有这样的关系:一对一的例子

但是不推荐使用休眠的一对一映射,您可以像这样简单地使用一对多映射:

@Entity
@Table(name = "Person")
public class Person {

    @Id
    @GeneratedValue
    int id; 

    @OneToMany(mappedBy = "Person", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    Private MaritalStatus;
}

@Entity
@Table(name = "MaritalStatus")
public class Person {

    @Id
    @GeneratedValue
    int id; 

    @ManyToOne
    Person person = new Person();
}

这种方法非常简单,但您可能更喜欢使用枚举而不是类并使用枚举映射表。这种方法实施起来有点困难,这篇文章为您提供了您需要的所有东西:将枚举映射到表

于 2012-12-17T06:59:54.197 回答
0

我会在下面做

个人实体:

@Entity
@Table(schema = "Person")
public class Person {
    @Id
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "marital_status_id")
    private MaritalStatus  maritalStatus;

}

婚姻状况实体:

@Entity
@Table(schema = "MaritalStatus")
public class MaritalStatus {
    @Id
    private String id;

    @Column(name = "status")
    private String status;
}
于 2012-12-17T07:00:49.933 回答