Alternative to using deprecated save method in hibernate

Viewed 2194

I am using the following code to save a person object into the database:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Main {

    public static void main(String[] args) {
        Person person = new Person();
        person.setID(1);
        person.setName("name-1");
        person.setAddress("address-1");

        Configuration configuration = new Configuration().configure().addAnnotatedClass(Person.class);
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        session.save(person);
        transaction.commit();
    }
}

I see that the save method is deprecated. What's the alternative approach that we are supposed to use?

2 Answers

save() is deprecated since Hibernate 6.0. The javadoc suggests to use persist() instead.

Deprecated.

use persist(Object)

Small print: save() and persist() are similar, but still different. save() immediately persist the entity and returns the generated ID. persist() just marks the entity for insertion. The ID, depending on the identifier generator, may be generated asynchronously, for example when the session is flushed.

save() was never part of JPA. Since hibernate came before JPA they continued with it and now deprecated and will be removed in the future.
persist(): Persist methods are used to save newly created entities
merge(): should be used to update detached entity object.
update(): It forces the transition of Entity obj from detached to persistent state. It doesn't make unnecessary SELECT calls unlike merge()
Note: INSERT statements will occur only upon committing the transaction, or flushing or closing the session.

Related