JPA复合主键

Dón*_*nal 9 java sql-server maven-2 hibernate jpa

我的JPA模型中有以下类(省略了getter,setter和不相关的字段):

@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Currency {

    @Id
    private Integer ix;
}

@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Product {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
}
Run Code Online (Sandbox Code Playgroud)

我需要定义一个类Price,使得当从所述类生成DDL时,相应的表的主键被由密钥ProductCurrency.我尝试过以下方法:

@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@IdClass(PricePK.class)
public class Price {

    @Id @ManyToOne(optional = false)
    private Product product;

    @Id
    @ManyToOne(optional = false)
    private Currency currency;
}

@Embeddable
public class PricePK implements Serializable {

    Integer product;        
    Integer currency;
}
Run Code Online (Sandbox Code Playgroud)

但是这会为PRICE表生成以下内容:

create table PRICE (
    currency_id int null,
    product_id int null,
    primary key (currency_id, product_id)
);
Run Code Online (Sandbox Code Playgroud)

请注意,两个currency_idproduct_id是空的,这会导致以下错误,当我尝试了DDL加载到SQL Server

无法在表'PRICE'中的可空列上定义PRIMARY KEY约束

我不明白为什么这些可以为空,因为在域模型中它们是注释的 @ManyToOne(optional = false)

DDL是使用org.hibernate.dialect.SQLServerDialectSQL方言生成的.

dan*_*nik 4

最近,我使用复合主键和注释作为双向创建了多对多关系@OneToMany。这段代码运行完美。也许会有帮助:

使用复合主键和注释映射多对​​多: