2015-09-02 234 views
0

我可能混淆了術語,但我稱之爲簡單實體的東西類似於CustomerProduct,即具有其自身身份並且我正在使用Integer id的東西。休眠組合實體

一個組合的實體類似CustomerProduct,允許創建一個m:n映射並將一些數據與它關聯。我創建

class CustomerProduct extends MyCompositeEntity { 
    @Id @ManyToOne private Customer; 
    @Id @ManyToOne private Product; 
    private String someString; 
    private int someInt; 
} 

,我收到消息

複合-ID類必須實現Serializable

導致我直接把這些twoquestions。我可以實現Serializable,但這意味着將CustomerProduct作爲CustomerProduct的一部分進行序列化,這對我來說沒有任何意義。我需要的是一個包含兩個Integer的複合密鑰,就像普通的密鑰只是一個Integer一樣。

我離開賽道嗎?

如果不是,我該如何使用註釋(和/或代碼)來指定它?

回答

2

Hibernate會話對象需要可序列化,這意味着所有引用的對象也必須是可序列化的。即使您將原始類型用作組合鍵,您也需要添加序列化步驟。

您可以在休眠中使用複合主鍵,註釋@EmbeddedId@IdClass

隨着IdClass你可以做follwing(假設你的實體使用整數鍵):

public class CustomerProduckKey implements Serializable { 
    private int customerId; 
    private int productId; 

    // constructor, getters and setters 
    // hashCode and equals 
} 

@Entity 
@IdClass(CustomerProduckKey.class) 
class CustomerProduct extends MyCompositeEntity { // MyCompositeEntity implements Serializable 
    @Id private int customerId; 
    @Id private int productId; 

    private String someString; 
    private int someInt; 
} 

你的主鍵類必須是公共的,必須有一個公共的無參數的構造函數。它也必須是serializable

您還可以使用@EmbeddedId@Embeddable,這有點清晰,可以在其他地方重複使用PK。

@Embeddable 
public class CustomerProduckKey implements Serializable { 
    private int customerId; 
    private int productId; 
    //... 
} 

@Entity 
class CustomerProduct extends MyCompositeEntity { 
    @EmbeddedId CustomerProduckKey customerProductKey; 

    private String someString; 
    private int someInt; 
} 
0

您可以使用@EmbeddedId@MapsId

@Embeddable 
public class CustomerProductPK implements Serializable { 
    private Integer customerId; 
    private Integer productId; 
    //... 
} 

@Entity 
class CustomerProduct { 
    @EmbeddedId 
    CustomerProductPK customerProductPK; 

    @MapsId("customerId") 
    @ManyToOne 
    private Customer; 

    @MapsId("productId") 
    @ManyToOne 
    private Product; 

    private String someString; 
    private int someInt; 
}