我可能会混淆一些术语,但是我所谓的简单实体是CustomerProduct之类的东西,即具有自己的身份并且我正在使用Integer id的事物。

组合实体类似于CustomerProduct,它允许创建m:n映射并将某些数据与其关联。我创建

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


我得到消息


  Composite-id类必须实现Serializable


这些直接将我引向这些two questions。我可以轻松实现Serializable,但这意味着将CustomerProduct序列化为CustomerProduct的一部分,这对我来说毫无意义。我需要的是一个包含两个Integer的复合键,就像普通的键只是一个Integer一样。

我走了吗?

如果没有,如何仅使用注释(和/或代码)来指定?

最佳答案

Hibernate会话对象需要可序列化,这意味着所有引用的对象也必须可序列化。即使您使用原始类型作为组合键,也需要添加序列化步骤。

您可以在Hibernate中使用带有注释@EmbeddedId@IdClass的复合主键。

使用IdClass可以进行以下操作(假设您的实体使用整数键):

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;
}

07-28 02:39
查看更多