我想强制 CrudRepository#save(entity) 插入一个新实体,而不是先选择实体并在主键已经存在时更新它。
我会试着举个例子
public class Lock
{
@Id
@Column
private UUID uuid;
...
}
UUID id = UUID.randomUUID();
Lock firstLock = new Lock(id);
Lock secondLock = new Lock(id);
repo.save(firstLock);
repo.save(secondLock);
发生的情况是,第一个保存操作执行以下两个语句
Hibernate: select lock0_.uuid as uuid5_0_, lock0_.expires as expires5_0_ from locks lock0_ where lock0_.uuid=?
Hibernate: insert into locks (expires, uuid) values (?, ?)
而第二次调用 save 执行更新语句
Hibernate: select lock0_.uuid as uuid5_0_, lock0_.expires as expires5_0_ from locks lock0_ where lock0_.uuid=?
Hibernate: update locks set expires=? where uuid=?
我如何确保第二次调用 save 不会简单地更新以前存储的记录?我希望它执行插入语句并失败,因为已经存在相同的主键