Skip to content
Advertisement

Alternative to using deprecated save method in hibernate

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement