2011-06-23 174 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

不幸的是它沒有工作 –