繁体   English   中英

@OneToMany 两个表之间的关系,每个表都有复合主键

[英]@OneToMany relationship between two tables each having composite Primary Keys

有人可以提供一个工作示例,说明如何使用 JPA/Hibernate map 在两个表之间建立@OneToMany 关系,每个表都具有如下复合主键:

为此目的在 Oracle 中创建表 B 时是否需要创建 FK 约束? 会怎么样?

在此处输入图像描述

非常感谢您!

首先,您需要一个 class 来复合多字段。

@Embeddable
public class CompoundKey implements Serializable {

  @Column(name = "PK1", columnDefinition = "INT", nullable = false)
  private Long pk1;

  @Column(name = "PK2", columnDefinition = "INT", nullable = false)
  private Long pk2;
}

然后像这样使用它:

@Entity
@Table(name = "TableA")
public class A implements Serializable {

  private static final long serialVersionUID = -1239386304051447322L;

  @EmbeddedId
  private CompoundKey pKey;

  private String name;

  @OneToMany(mappedBy = "a")
  private List<B> bList;
}
@Entity
@Table(name = "TableB")
public class B implements Serializable {

  private static final long serialVersionUID = -589397418901916036L;

  @Id
  @GeneratedValue(strategy= GenerationType.AUTO)
  private String id;

  @ManyToOne
  private A a;

  private LocalDateTime date;
}

最后生成的 ddl 应该是:

Hibernate: drop table tablea if exists
Hibernate: drop table tableb if exists
Hibernate: drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: create table tablea (pk1 INT not null, pk2 INT not null, name varchar(255), primary key (pk1, pk2))
Hibernate: create table tableb (id varchar(255) not null, date timestamp, a_pk1 INT, a_pk2 INT, primary key (id))
Hibernate: alter table tableb add constraint FKs0bksprwc7qy2dll3ihn795cr foreign key (a_pk1, a_pk2) references tablea

好吧,我还没有运行任何 CRUD 测试。 只是一个建议:小心@OneToMany ,它可能会生成一个引用您的两个表的第三个表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM