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

时间:2020-08-12 12:01:45

标签: java hibernate jpa

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

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

enter image description here

非常感谢您!

1 个答案:

答案 0 :(得分:0)

首先,您需要一个用于复合多个字段的类。

@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,它可能会生成引用您两个表的第三个表。