强制插入弹簧数据 jpa [英] force insert with spring data jpa
问题描述
我想强制 CrudRepository#save(entity) 插入一个新实体,而不是先选择实体并在主键已经存在时更新它.
I'd like to force CrudRepository#save(entity) to insert a new entity instead of selecting the entity first and updating it if the primary key already exists.
我会试着举个例子
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);
发生的事情是,第一个保存操作执行以下两条语句
what happens is, that the first save operation executes the following two statements
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 执行更新语句
while the second call to save executes an update statement
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 不会简单地更新先前存储的记录?我希望它执行插入语句并失败,因为相同的主键已经存在
How do I make sure, that the second call to save does not simply update the previously stored record? I want it to execute an insert statement and fail because the same primary key already exists
推荐答案
Spring Data JPA 中不允许强制插入 id 不为 null 的实体.
Forcing insert for on entity whose id is not null is not allowed in Spring Data JPA.
通常,Id 生成器用于主键,以确保生成的 id 是唯一的.(例如@GeneratedValue(strategy = GenerationType.AUTO))
Normally an Id generator is used for a primary key that ensures ids generated are unique. (e.g. @GeneratedValue(strategy = GenerationType.AUTO))
我认为这种行为是正确的.在 ORM 中,使用 new 运算符表示有意创建一个新实体,并隐含要求为其分配唯一 id.
This behavior in my opinion is correct. In an ORM, use of new operator indicates intention to create a new entity with an implicit requirement to assign it a unique id.
但是如果您无论如何都想尝试一下,您可以查看自定义@GenericGenerator.
But if you wish to try it anyway you can look into a custom @GenericGenerator.
http://www.georgestragand.com/jpaseq.html
这篇关于强制插入弹簧数据 jpa的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!