我可能会混淆一些术语,但是我所谓的简单实体是Customer
或Product
之类的东西,即具有自己的身份并且我正在使用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
,但这意味着将Customer
和Product
序列化为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;
}