简体   繁体   English

休眠5,将外键作为主键,单向一对一

[英]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.

相关问题 带有反向主外键级联的零到一单向休眠 - Hibernate Zero to One unidirectional with reverse primary foreign key cascade 休眠外键一对一单向 - Hibernate One-to-One unidirectional on foreign key Hibernate批注使用复合主键一对一映射单向关联 - Hibernate annotations to map one to one unidirectional association with composite primary key JPA / Hibernate使用共享主键进行单向一对一映射 - JPA / Hibernate unidirectional one-to-one mapping with shared primary key 休眠一对一单向主键XML映射 - Hibernate One to One Unidirectional Primary key XML mapping 休眠中具有相同主键的一对一单向映射 - One to One unidirectional mapping with same primary key in hibernate 如何在非主键上使用休眠注释设置单向一对一关系? - how to set unidirectional one-to-one relationship using hibernate annotation on a non-primary key? 如何在外键与联接表和单向休眠状态下进行一对一关联 - How to do One to One association in hibernate with foreign key and join table and unidirectional 一对一的单向hibernate映射不会在创建表时创建外键 - one-to-one unidirectional hibernate mapping is not creating foreign key while table creation 在外键上一对一休眠 - hibernate one to one on foreign key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM