从JPA注释生成DDL



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

@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;
}
@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Currency extends PersistentEntity {
    @Id
    private Integer ix;
}
@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Product extends AutoIdPersistentEntity {
}
@MappedSuperclass
public abstract class AutoIdPersistentEntity extends PersistentEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
} 

我使用hibernate3 Maven插件的hbm2ddl目标从这些类生成DDL。它为对应于Price类的表生成以下内容

create table PRICE (
    currency_id int null,
    product_id int null,
    primary key (currency_id, product_id)
);

请注意,currency_idproduct_id都可以为null,当我尝试将DDL加载到SQLServer中时,会导致以下错误

无法在表"PRICE"中可为Null的列上定义PRIMARY KEY约束

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

DDL是使用org.hibernate.dialect.SQLServerDialect SQL方言生成的。

这有点令人困惑,但我认为一些JPA实现没有将可选属性(@ManyToOne,@Basic,…)用于模式生成。

我认为您需要使用@JoinColumn注释并将nullable设置为false:http://download.oracle.com/javaee/6/api/javax/persistence/JoinColumn.html

(或者在非联接情况下@列:http://download.oracle.com/javaee/6/api/javax/persistence/Column.html)

最新更新