Edited. Whilst extending the base repository class and adding an insert method would work an more elegant solution appears to be implementing Persistable in the entities.
Does this help?
Set updatable = false
on your PK column definition. Example:
@Id
@GeneratedValue
@Column(name = “id”, updatable = false, nullable = false)
private Long id;
Setting your id non updatable will stop JPA from doing updates on your primary key, so thing about it.
I never did that before, but a little hack, would maybe do the job.
There is a Persistable
interface for the entities. It has a method boolean isNew()
that when implemented will be used to "assess" if the Entity is new or not in the database. Base on that decision, EntityManager should decide to call .merge()
or .persist()
on that entity, after You call .save()
from Repository
.
Going that way, if You implement isNew()
to always return true, the .persist()
should be called no mater what, and error should be thrown after.
Correct me If I'm wrong. Unfortunately I can't test it on a live code right now.
Documentation about Persistable
: http://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/Persistable.html
Why not create a clone object which clones everything except your primary keys and then save this cloned object.
Since the PK will not be present, an insert happens, instead of an update