这个问题在这里已有答案:
我的JPA模型中有以下类(省略了getter,setter和不相关的字段):
@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Currency {
@Id
private Integer ix;
}
@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Product {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
}
我需要定义一个类 Price
,这样当DDL is generated from the classes时,相应表的主键由 Product
和 Currency
的键组成 . 我尝试过以下方法:
@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;
}
但是这会为 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方言生成的 .
2 回答
最近我使用Composite Primary key和annotation创建了ManyToMany关系作为双向
@OneToMany
. 这段代码完美无瑕 . 也许它会有所帮助:Mapping ManyToMany with composite Primary key and Annotation:
由于您使用的是
@IdClass
,因此无需使用@Embeddable
注释标记PricePK
类 . http://www.java2s.com/Code/Java/JPA/SetIdClassforCompoundKey.htm给出了一个例子我尝试使用代码删除
PricePK
类上的@Embeddable
,以及在MYSQL数据库中生成的非空字段的价格表 .以下是如何使用
@EmbeddedId
来实现所需的结果:(省略了getters和setter)