java - Hibernate 组合实体

标签 java hibernate jpa jpa-2.1

我可能混淆了术语,但我所说的简单实体类似于客户产品,即具有自己身份的事物,并且我对其进行定义。正在使用整数 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,但这意味着将 CustomerProduct 序列化为 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/

相关文章:

java - 将动态 Web 项目转换为 JPA 项目?

java.lang.IllegalArgumentException : Unable to locate Attribute with the the given name

Java 8 分组并附加到集合

java - 在 Hibernate 中为 LocalDateTime 创建列类型 Datetime

java - 索引目录未出现

postgresql - 使用 JPA (EclipseLink) 创建 "text[]"等 PostgreSQL 数组类型

java - 使用 BigDecimal 限制有效数字的任何巧妙方法

大学 bash 中的 Java 因 NoClassDefFoundError 失败

java - Maven 在没有互联网连接的情况下无法执行目标

java - 使用 Hibernate 3.6 配置 Glassfish 3