我正在使用 hbm2ddl(来自 hibernate3-maven-plugin 2.2)基于我的 JPA 注释实体生成 DDL。通常,这可以正常工作,但我最近介绍了一个使用由两个外键组成的复合键的实体,这导致 DDL 生成出现问题。
具体来说,生成的 DDL 指定主键列可以为空,而主键列不应该是这种情况。因此,MSSQL 无法创建主键约束,因为该列可以为空。
这是实体
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@IdClass(PricePK.class)
public class Price extends PersistentEntity {
@Id
@ManyToOne(optional = false)
private Product product;
@Id
@ManyToOne(optional = false)
private Currency currency;
@Column(nullable = false)
private BigDecimal amount;
...etc...
}
该实体指定它使用 PricePK 作为其主键类,更重要的是,构成主键的两个 ManyToOne 实体不是可选的(这应该意味着 DDL 中的列“非空”)。这是 PricePK 类:
@Embeddable
public class PricePK implements Serializable {
Integer product;
Integer currency;
...etc...
}
为 Price 表生成的 DDL 如下 - 请注意,currency_id 和 product_id 都允许为空:
create table PRICE (
version int null,
amount numeric(19,2) not null,
currency_id int null,
product_id int null,
primary key (currency_id, product_id)
);
当我尝试在 MSSql 中运行脚本时,出现以下(不足为奇)错误:
不成功:创建表 store.PRICE (version int null, amount numeric(19,2) null, currency_id int null, product_id int null, 主键 (currency_id, product_id)) 无法在表 'PRICE' 中的可空列上定义 PRIMARY KEY 约束.
知道为什么正在生成的 DDL 为这两个外键列指定“null”吗?