【问题标题】:How to use @GeneratedValue inside @Embeddable used as composite primary key?如何在@Embeddable 中使用@GeneratedValue 作为复合主键?
【发布时间】:2021-05-27 22:04:00
【问题描述】:

我的数据库中有一个带有主复合键的表,当我使用 Hibernate 对其进行建模时,我使用 @EmbeddedId@Embedable。此复合主键的一列生成的值为@GeneratedValue(strategy = GenerationType.IDENTITY)

当我尝试在我的数据库中创建两个新对象时,出现如下错误:

org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [MyPackage#MyEmbedableClass [MyGeneratedPrimaryKeyValue=null, OtherPrimaryKey=21]]

但是当我查看我的数据库时,我的对象已经创建好了。我不明白我的错误,我不知道如何解决我的问题。

我找到了一些类似我的主题,但我还没有找到我的问题的答案。

  1. first exemple

  2. second exemple

  3. third exemple

@Entity(name = "Certification")
@Table(name = "CERTIFICATION")
public class Certification implements Serializable {

    static final long serialVersionUID = -4399907743392740963L;

    @EmbeddedId
    private CertificationPK certificationPK;

    // Others variables
    // constructors
    // Getter / Setter
    // toString
    // hashCode / equals
}

@Embeddable
public class CertificationPK implements Serializable {

    private static final long serialVersionUID = 1433990897506209802L;

    // MyGeneratedPrimaryKeyValue=null when I create
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NotNull
    @Column(name = "CERTIFICATION_ID")
    private Integer certificationId; 

    // Other variable
    // constructors
    // Getter / Setter
    // toString
    // hashCode / equals
}

提前感谢您的帮助。

【问题讨论】:

  • 请出示您的地图。
  • @SternK 映射是什么意思?
  • 当我使用 Hibernate 对其进行建模时,我使用 @EmbeddedId 和 @Embedable - 请展示您如何对其进行建模
  • @SternK 我更新了我的帖子,如果您需要更多我可以添加。

标签: hibernate primary-key composite auto-generate


【解决方案1】:
  1. 您似乎不能将@GeneratedValue@EmbeddedId 一起使用。您可以在 this article 中找到一些解决方法,但对我来说效果不佳。

  2. 正如文档的this 部分所述,应该可以将@GeneratedValue@IdClass 一起使用。但是,由于HHH-9662,它不起作用。

  3. 正如文档的this 部分所述:

使用复合标识符时,底层标识符属性必须由用户手动分配。

不支持使用自动生成的属性来生成构成复合标识符的基础属性的值。

因此,您不能使用generated properties 部分描述的任何自动属性生成器,例如@Generated@CreationTimestamp@ValueGenerationType 或数据库生成的值。

尽管如此,您仍然可以在构造复合标识符之前生成标识符属性。

【讨论】:

  • 感谢您的帮助和指正!
猜你喜欢
  • 2016-09-23
  • 2015-06-24
  • 2020-10-17
  • 2012-05-20
  • 2020-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多