插入Comment子实体时主键冲突:为何INSERT包含id_comment字段?
问题:为Book添加Comment时触发主键冲突
DB Schema(H2数据库)
create table book ( id_book bigint auto_increment not null primary key, title varchar(255) not null, id_author bigint not null, id_genre bigint not null ); create table comment ( id_comment bigint auto_increment not null primary key, id_book bigint not null, comment_text varchar(255) not null );
领域类
Book类
public class Book { @Id @Column("id_book") private Long id; private String title; @Column("id_author") AggregateReference<Author, Long> author; @Column("id_genre") AggregateReference<Genre, Long> genre; @MappedCollection(idColumn = "id_book", keyColumn = "id_comment") List<Comment> comments = new ArrayList<>(); public void addComment(String commentText) { comments.add(new Comment(commentText)); } // getters and setters }
Comment类
public class Comment { @Column("id_comment") private Long id; @Column("comment_text") private String text; public Comment(String text) { this.text = text; } public Comment() { } // getters and setters }
添加评论的方法
@Override @Transactional public String addComment(long bookId, String commentText) { var book = bookRepository.findById(bookId); return book.map(b -> { b.addComment(commentText); b = bookRepository.save(b); return bookConverter.convertToString(b); }).orElse("Book not found!"); }
生成的SQL语句
Executing SQL batch update [INSERT INTO "COMMENT" ("comment_text", "id_book", "id_comment") VALUES (?, ?, ?)]
插入时id_comment会被填入0、1、2、3这类值,与现有记录重复,触发主键冲突。疑问:为什么INSERT语句会包含id_comment字段?
原因及解决方案
核心原因
- Comment类未正确标记主键属性:
Comment类的id字段仅加了@Column("id_comment"),但未声明它是主键且自增。Spring Data JDBC无法识别该字段为数据库自增主键,因此会使用字段默认值(Long类型默认0,后续新增时递增为1、2...)作为插入值,导致主键冲突。 - @MappedCollection配置错误:对于
List类型的集合关联,@MappedCollection的keyColumn参数是用于Map类型集合的键映射,而非子表的主键列。错误指定keyColumn = "id_comment",会让Spring Data JDBC将Comment的id当作集合关联的标识字段,强制在INSERT语句中包含该字段。
修复步骤
- 修正Comment类的主键注解:
public class Comment { @Id // 标记为主键 @Column("id_comment") @GeneratedValue(strategy = GenerationType.IDENTITY) // 指定自增策略 private Long id; @Column("comment_text") private String text; public Comment(String text) { this.text = text; } public Comment() { } // getters and setters }
- 修正Book类的@MappedCollection配置:
public class Book { // ... 其他字段省略 @MappedCollection(idColumn = "id_book") // 移除错误的keyColumn参数 List<Comment> comments = new ArrayList<>(); // ... 其他方法省略 }
修改后,Spring Data JDBC会自动忽略INSERT语句中的id_comment字段,由数据库的自增机制生成主键值,避免冲突。
内容的提问来源于stack exchange,提问作者Alexander Popov
相关产品推荐
相关产品推荐

