[英]@OneToMany relationship between two tables each having composite Primary Keys
首先,您需要一个 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.