我正在使用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都允许为null:
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中运行脚本时,我得到以下(不奇怪)错误:
不成功:create table store.PRICE(version int null,amount numeric(19,2)null,currency_id int null,product_id int null,primary key(currency_id,product_id))无法在表'PRICE中的可空列上定义PRIMARY KEY约束” .
知道为什么正在生成的DDL为这两个外键列指定'null'吗?
1 回答
您可以通过在PricePK的字段/ getter上使用@Column(nullable = false)的某些变体来解决此问题 .