force insert with spring data jpa

2019-07-08 09:22发布

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.

I'll try to give an example

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 (?, ?)

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=?

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

1条回答
叼着烟拽天下
2楼-- · 2019-07-08 10:06

Forcing insert for on entity whose id is not null is not allowed in Spring Data JPA.

Normally an Id generator is used for a primary key that ensures ids generated are unique. (e.g. @GeneratedValue(strategy = GenerationType.AUTO))

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.

But if you wish to try it anyway you can look into a custom @GenericGenerator.

http://www.georgestragand.com/jpaseq.html

查看更多
登录 后发表回答