Search code examples
javahibernatehibernate-6.x

How to replace deprecated saveOrUpdate() method in Hibernate 6?


With Hibernate 6.0 the saveOrUpdate(entity) method is now deprecated. The Javadoc suggests to replace it with either merge() or persist().

But doing so breaks some of my tests with "A different object with the same identifier value was already associated with the session" (merge) or "Unique index or primary key violation" (persist).

How do I properly replace my saveOrUpdate() calls?


Solution

  • I've figured it out (thanks for the hint, Mar-Z!).

    if (Objects.isNull(session.find(MyEntity.class, entity.getId()))) {
        session.persist(entity);
    } else {
        session.merge(entity);
    }
    

    This starts by loading the entity from the database by its ID and checks if it is returned. If nothing is returned persist() inserts it as a new entity into the database, otherways the existing entry gets updated by merge().