Java Hibernate:插入集合时为每个关系记录创建唯一的GenerateValue

Java Hibernate:插入集合时为每个关系记录创建唯一的GenerateValue,java,postgresql,hibernate,jpa,primary-key,Java,Postgresql,Hibernate,Jpa,Primary Key,我使用Hibernate插入实体,如下所示: 我正在插入一个post实体,它拥有一组comment实体。我试图插入一个新的post,其中包含两个新的comment实体,但无法为每个comment实体生成唯一的ID // Create post. final String title = "unit test TITLE"; final String content = "unit test CONTENT"; Post post = new Post();

我使用Hibernate插入实体,如下所示:

我正在插入一个
post
实体,它拥有一组
comment
实体。我试图插入一个新的
post
,其中包含两个新的
comment
实体,但无法为每个
comment
实体生成唯一的ID

    // Create post.

    final String title = "unit test TITLE";
    final String content = "unit test CONTENT";

    Post post = new Post();

    post.setTitle(title);
    post.setContent(content);

    // Crate comments.

    final String author1 = "unit test AUTHOR 1";
    final String content1 = "unit test CONTENT 1";
    final String author2 = "unit test AUTHOR 2";
    final String content2 = "unit test CONTENT 2";

    Comment comment1 = new Comment();
    Comment comment2 = new Comment();

    comment1.setAuthor(author1);
    comment1.setContent(content1);
    comment2.setAuthor(author2);
    comment2.setContent(content2);

    // Add comments to post

    post.getComments().add(comment1);
    post.getComments().add(comment2);

    // Save posts.

    postRepository.save(post);
每个实体都有一个
id
字段,如下所示:

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
由于插入是在单个事务中完成的,因此每个注释的
id
都是相同的,从而导致错误:

ERROR: duplicate key value violates unique constraint "comments_pkey"
我应该如何注释或配置
注释
实体中的
id
字段,以便我可以插入多个注释,而无需为每个注释使用相同的自动生成的id?

我想到的一个解决方案是使用
UUID
s,但即使这样,我也不确定它们是否会有所不同

注意:默认序列来自
hibernate\u序列
。两条记录都来自这个序列并不是问题,我可以从它们的表特定序列中获取这些序列(
comment\u id\u seq
post\u id\u seq
),但是这并不能解决每个注释都插入相同的
id
的问题


注意:在仅插入一条注释的情况下执行上述插入操作不会导致错误。

“由于插入是在单个事务中完成的,因此每个注释的id都是相同的”-这根本不是它的工作方式。请发布
post
Comment
实体,您的映射可能有问题。另外,共享表注释和实体映射的DDL