Java Hibernate:插入集合时为每个关系记录创建唯一的GenerateValue
我使用Hibernate插入实体,如下所示: 我正在插入一个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();
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