如何在@Embeddable中使用@GenerateValue用作复合主键?

BOS*_*dis 3 hibernate composite primary-key auto-generate

我的数据库中有一张带有主组合键的表,当我使用 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]]
Run Code Online (Sandbox Code Playgroud)

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

我找到了一些像我这样的主题,但还没有找到我的问题的答案。

  1. 第一个例子

  2. 第二个例子

  3. 第三个例子

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

在此先感谢您的帮助。

Ste*_*rnK 7

  1. 看来你不能使用@GeneratedValuewith @EmbeddedId您可以在本文中找到一些解决方法,但它对我来说效果不佳。

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

  3. 正如文档的本节所述:

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

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

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

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