我使用这些注释在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提供程序。
答案 0 :(得分:4)
确保您没有错过第二个约束。我有类似的情况,Hibernate生成数据库架构很好
@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