我的 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;
}
我使用hbm2ddl hibernate3 Maven 插件的目标是从这些类生成 DDL。它为与 Price
类对应的表生成以下内容
create table PRICE (
currency_id int null,
product_id int null,
primary key (currency_id, product_id)
);
请注意,currency_id
和 product_id
都可以为 null,这会在我尝试将 DDL 加载到 SQL Server 时导致以下错误
Cannot define PRIMARY KEY constraint on nullable column in table 'PRICE'
我不明白为什么这些可以为空,因为在域模型中它们被注释了
@ManyToOne(可选 = false)
DDL 是使用 org.hibernate.dialect.SQLServerDialect
SQL 方言生成的。
最佳答案
这有点令人困惑,但我认为可选属性(@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)
关于java - 从 JPA 注释生成 DDL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6444687/