我的JPA模型中有以下类(省略了getters,setters和无关字段):
@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; }
我需要定义一个类Price,使得当从所述类生成DDL时,相应的表的主键被由密钥Product和Currency。我尝试了以下方法:
Price
Product
Currency
@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; }
但这会为PRICE表生成以下内容:
PRICE
create table PRICE ( currency_id int null, product_id int null, primary key (currency_id, product_id) );
请注意,currency_id和product_id都是可为空的,当我尝试将DDL加载到SQL Server时会导致以下错误
currency_id
product_id
无法在表“ PRICE”中的可为空的列上定义PRIMARY KEY约束
我不明白为什么这些可以为空,因为在域模型中它们是带注释的 @ManyToOne(optional = false)
@ManyToOne(optional = false)
DDL使用org.hibernate.dialect.SQLServerDialectSQL方言生成。
org.hibernate.dialect.SQLServerDialect
最近,我使用Composite Primary键和双向注解创建了ManyToMany关系@OneToMany。这段代码完美无瑕。也许会有所帮助:
@OneToMany