【发布时间】:2023-04-02 20:29:01
【问题描述】:
我有一个婚姻状态表,其中包含“单身”、“已婚”等值。
我有一个表 Person,其中 marital_status_id 作为外键。
我如何映射这个?任何帮助将不胜感激,因为我是 Hibernate 的新手。或者我不需要这个,因为 Person 和 Marital Status 之间没有关系,而只是一个参考?
【问题讨论】:
我有一个婚姻状态表,其中包含“单身”、“已婚”等值。
我有一个表 Person,其中 marital_status_id 作为外键。
我如何映射这个?任何帮助将不胜感激,因为我是 Hibernate 的新手。或者我不需要这个,因为 Person 和 Marital Status 之间没有关系,而只是一个参考?
【问题讨论】:
首先,婚姻状况不需要单独的表格(是吗?真的吗?)。可以用单个字符处理(非常高效)
但是,在你的情况下,
@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;
}
【讨论】:
婚姻状况在 Java 中应表示为枚举,以排除不必要的连接,因为没有那么多选项,它们永远不会改变。
检查@Enumerated(EnumType.STRING)注解:http://docs.oracle.com/javaee/6/api/javax/persistence/Enumerated.html
【讨论】:
你没有具体说明你是坚持建立一对一的关系还是不关心,以及你是否更喜欢使用 Enum 而不是 Class。
这个链接提供了一些关于休眠中一对一映射的有用信息,如果你想在你的表之间建立这样的关系:one-to-one example不过不推荐使用 hibernate 的一对一映射,您可以像这样简单地使用一对多映射:
@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();
}
这种方法非常简单,但您可能更喜欢使用枚举而不是类,并使用枚举映射表。这种方法实施起来有点困难,这篇文章为你提供了你需要的所有东西:Mapping enum to a table
【讨论】:
@OneToMany 和 @ManyToOne 注释颠倒了。
我想在下面做
个人实体:
@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;
}
【讨论】: