【问题标题】:Hibernate composed entityHibernate 组合实体
【发布时间】:2015-09-02 23:13:26
【问题描述】:

我可能混淆了术语,但我所说的简单实体是 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

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

我跑题了吗?

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

【问题讨论】:

    标签: java hibernate jpa jpa-2.1


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以使用@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;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-15
        • 2017-10-22
        • 2016-01-29
        相关资源
        最近更新 更多