如何使用一对一关系将一个表主存储为另一个表外键

时间:2019-05-12 19:11:43

标签: spring-data-jpa

我有两个具有一对一关系的实体,我希望将父实体的主键与子实体的主键一起作为子实体的外键

我一直在尝试使用JPA @MapsId(),但无法成功

我的父实体

 @Id
    @SequenceGenerator(initialValue=10000, name = "parent_seq")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, 
     generator="parent_seq")
    @Column(name = "parent_id")
    private long parentid;

    @OneToOne(mappedBy="parentEntity", cascade = CascadeType.ALL)
    private ChildEntity childEntity;


    and in my child entity 



         @SequenceGenerator(initialValue=10000, name = "child_seq")
            @GeneratedValue(strategy = GenerationType.SEQUENCE, 
            generator="child_seq")
            @Column(name = "child_id")
            private long childid;

            @MapsId("parent_id")
            @OneToOne
            private ParentEntity parentEntity;

在这里,我想使用我给出的JPA创建表 spring.jpa.hibernate.ddl-auto =创建 这项工作正常,但是我希望应该在childEntity表中创建parent_id列,但不能创建,并且应该将parent_id插入子表parent_id列中。

1 个答案:

答案 0 :(得分:0)

当您要使用@MapsId功能时,您的“子”实体应具有“简单”标识符,且不生成任何代号。例如:

@Entity
@Table(name = "parents")
public class Parent {
    @Id
    @GeneratedValue(...)
    private Long id;
    // other stuff...
}
@Entity
@Table(name = "children")
public class Child {
    @Id
    private Long id;

    @MapsId
    @OneToOne(fetch = FetchType.LAZY)
    private Parent parent;

    // other stuff...
}

在这种情况下,children表将如下所示:

create table children (
  parent_id bigint not null constraint children_pkey primary key,
  -- other stuff...
  constraint fk_children_parent_id foreign key (parent_id) references parents(id)
);

更多信息:The best way to map a @OneToOne relationship with JPA and Hibernate

相关问题