我的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_id
和 product_id
都可以为空,当我尝试将DDL加载到SQL Server时会导致以下错误
无法在表'PRICE'中的可空列上定义PRIMARY KEY约束
我不明白为什么这些可以为空,因为在域模型中它们被注释 @ManyToOne(optional = false)
DDL是使用 org.hibernate.dialect.SQLServerDialect
SQL方言生成的 .
1 回答
这有点令人困惑,但我认为可选属性(@ManyToOne,@ Basic,...)不会被某些JPA实现用于模式生成 .
我认为你需要使用@JoinColumn注释并将nullable设置为false:http://download.oracle.com/javaee/6/api/javax/persistence/JoinColumn.html
(或非联合案例中的@Column:http://download.oracle.com/javaee/6/api/javax/persistence/Column.html)