我用这些注解在 ManyToMany 关联中映射了两个类:
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class TechnicalItem extends GenericBusinessObject implements Resumable{
@SequenceGenerator(name="TECHNICAL_ITEM_ID_GEN", sequenceName="TECHNICAL_ITEM_ID_SEQ")
@Id
@Column(name = "\"ID\"", nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TECHNICAL_ITEM_ID_GEN")
private int id;
@ManyToMany(mappedBy = "referencePerformanceItems", fetch=FetchType.LAZY)
private List<TestingRate> testingRates;
}
@Entity
@DiscriminatorValue("T")
public class TestingRate extends Rate {
@ManyToMany(fetch=FetchType.LAZY)
@JoinTable(name="ecc.\"TESTING_RATE_TECHNICAL_ITEM\"",
joinColumns = {@JoinColumn(name = "\"TESTING_RATE_ID\"")},
inverseJoinColumns = {@JoinColumn(name = "\"TECHNICAL_ITEM_ID\"")})
//@ManyToMany(mappedBy = "testingRates", fetch=FetchType.LAZY)
private List<TechnicalItem> referencePerformanceItems;
}
创建关联表生成的sql是:
create table ecc."TESTING_RATE_TECHNICAL_ITEM" (
"TESTING_RATE_ID" int4 not null,
"TECHNICAL_ITEM_ID" int4 not null
);
alter table ecc."TESTING_RATE_TECHNICAL_ITEM"
add constraint FKC5D64DF6A2FE2698
foreign key ("TESTING_RATE_ID")
references ecc."RATE";
没有提到第二个外键“TECHNICAL_ITEM_ID”(应该在关联表中的复合外键的第二部分)。 这是正常行为吗? 如果我希望我的 2 列是引用我的 2 个相关表的主键的 2 个外键,我应该在映射中做什么。
我使用 PostGreSQL 数据库和 Hibernate 作为 JPA 提供程序。
最佳答案
确保您没有错过第二个限制条件。我有类似的情况,Hibernate 可以很好地生成 DB 模式
@ManyToMany(targetEntity = Two.class, cascade = {
CascadeType.ALL
})
@JoinTable(name = "ONE_M2MJT_TWO", joinColumns = {
@JoinColumn(name = "ONE_ID")
}, inverseJoinColumns = {
@JoinColumn(name = "TWO_ID")
}, uniqueConstraints = {
@UniqueConstraint(columnNames = {
"ONE_ID",
"TWO_ID"
})
})
public List<Two> getManyToManyJoinTable() { ... }
create table ONE (MY_SUPER_ID bigint generated by default as identity (start with 1), VALUE_ varchar(255), primary key (MY_SUPER_ID))
create table ONE_M2MJT_TWO (ONE_ID bigint not null, TWO_ID bigint not null, unique (ONE_ID, TWO_ID))
create table TWO (MY_SUPER_ID bigint generated by default as identity (start with 1), VALUE_ varchar(255), primary key (MY_SUPER_ID))
alter table ONE_M2MJT_TWO add constraint FKA575066C950B44B foreign key (TWO_ID) references TWO
alter table ONE_M2MJT_TWO add constraint FKA575066C045060B foreign key (ONE_ID) references ONE
关于hibernate - JPA : many-to-many - only one foreign key in the association table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2635898/