休眠-JPA:多对多-关联表中只有一个外键

我使用以下注释在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可以很好地生成数据库架构

@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

转载注明原文:休眠-JPA:多对多-关联表中只有一个外键 - 代码日志