2015-09-02 240 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; 
}