2011-06-23 258 views
9

我在JPA模型以下类(吸气剂,setter以及不相干字段中省略):JPA复合主键

@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,主对应表的密钥由ProductCurrency的密钥组成。我已经试过如下:

@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_idproduct_id是空的,当我尝试加载这会导致以下错误将DDL转换为SQL Server

无法定义表'PRICE'中可空列的PRIMARY KEY约束条件

我不明白为什么这些都是空的,因为在域模型,他们被注释 @ManyToOne(optional = false)

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

回答

0

由于您使用@IdClass,该PricePK类不需要打上@Embeddable 注解。 http://www.java2s.com/Code/Java/JPA/SetIdClassforCompoundKey.htm

我试过你的代码,删除PricePK类中的@Embeddable类,并在MYSQL数据库中生成非空字段的价格表。

以下是您如何使用@EmbeddedId以达到所需的结果: (getter和setter略)

@Entity 
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) 
public class Price { 

    @EmbeddedId 
    PricePK pricePk; 
} 

@Embeddable 
public class PricePK implements Serializable { 

    @ManyToOne(optional = false) 
    private Product product; 

    @ManyToOne(optional = false) 
    private Currency currency; 
} 
+0

我想你的建议,但它并没有任何区别 –

+0

你想使用试用'@ EmbeddedId'方法? –

+0

不幸的是它没有工作 –