Spring Data JPA inserting instead of Update
By default Spring Data JPA inspects the identifier property of the given entity. If the identifier property is null
, then the entity will be assumed as new, otherwise as not new. It's Id-Property inspection
Reference
If you are using Spring JPA with EntityManager
calling .merge()
will update your entity and .persist()
will insert.
@PersistenceContext
private EntityManager em;
@Override
@Transactional
public User save(User user) {
if (user.getId() == null) {
em.persist(user);
return user;
} else {
return em.merge(user);
}
}
There is no need to implement the Persistable
interface.
I ran into this issue, tried to implement Persistable
to no avail, and then looked into the Spring Data JPA source. I don't necessarily see this in your example code, but I have a @Version
field in my entity. If there is a @Version
field Spring Data will test that value to determine if the entity is new or not. If the @Version
field is not a primitive and is null then the entity is considered new.
This threw me for a long time in my tests because I was not setting the version field in my representation but only on the persisted entity. I also don't see this documented in the otherwise helpful Spring Data docs (which is another issue...).
Hope that helps someone!