[英]hibernate 5, foreign key as primary key, unidirectional one to one
I have two entities: 我有两个实体:
First entity: 第一实体:
@Entity
@Table(name = "first")
public class First {
@Id
private Long id;
// other properties
// getters & setters
}
Second entity: 第二实体:
@Entity
@Table(name = "second")
public class Second {
@OneToOne
@JoinColumn(name = "first_id")
private First first;
// other properties
// getters & setters
}
I want to make first field in Second entity will be primary key. 我想使第二实体中的第一个字段成为主键。
First first = new First()
repository.save(first);
(first.id = 1) must be (first.id = 1)必须是
Second second = new Second()
second.setFirst(first); // as primary key
repository.save(second);
(second.first = first) must be (second.first = first)必须是
Use @MapsId
and add an @Id
field to the second entity: 使用
@MapsId
并将@Id
字段添加到第二个实体:
@Entity
@Table(name = "second")
public class Second {
@Id
private Long Id;
@MapsId
@OneToOne
@JoinColumn(name = "first_id")
private First first;
// other properties
// getters & setters
}
See page 37 from JPA 2 spec : 请参阅JPA 2规范的第37页:
Case (b): The dependent entity has a single primary key attribute corresponding to the relationship attribute.
情况(b):从属实体具有与该关系属性相对应的单个主键属性。 The primary key attribute is of the same basic type as the primary key of the parent entity.
主键属性与父实体的主键具有相同的基本类型。 The MapsId annotation applied to the relationship attribute indicates that the primary key is mapped by the relationship attribute.
应用于关系属性的MapsId批注指示主键由关系属性映射。
@Entity public class MedicalHistory { @Id String id; // overriding not allowed ... // default join column name is overridden @MapsId @JoinColumn(name="FK") @OneToOne Person patient; ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.