我可能混淆了术语,但我所说的简单实体类似于客户
或产品
,即具有自己身份的事物,并且我对其进行定义。正在使用整数 ID
。
组合实体类似于CustomerProduct
,允许创建 m:n 映射并将一些数据与其关联。我创建了
class CustomerProduct extends MyCompositeEntity {
@Id @ManyToOne private Customer;
@Id @ManyToOne private Product;
private String someString;
private int someInt;
}
我收到消息了
Composite-id class must implement Serializable
这直接引导我到这些two questions 。我可以简单地实现 Serialized
,但这意味着将 Customer
和 Product
序列化为 CustomerProduct
的一部分,并且这对我来说没有意义。我需要的是一个包含两个 Integer
的复合键,就像普通键只是一个 Integer
一样。
我是否偏离了轨道?
如果没有,我如何仅使用注释(和/或代码)来指定它?
最佳答案
Hibernate session 对象需要可序列化,这意味着所有引用的对象也必须可序列化。即使您使用原始类型作为复合键,您也需要添加序列化步骤。
您可以在 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;
}
您的主键类必须是公共(public)的,并且必须有一个公共(public)的无参数构造函数。它还必须是可序列化
。
您还可以使用@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;
}
关于java - Hibernate 组合实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32364639/