save vs persist in Hibernate

In Hibernate, both save and persist methods are used to save an object into the database, but there are subtle differences between the two that may influence which one you choose to use in different situations. In this post, we will discuss the difference between Session.save() and Session.persist() methods in Hibernate.

save Method 

Return Value: Returns the generated identifier (primary key) of the object. 

Behavior Outside a Transaction: If called outside of a transaction, save may still insert the object into the database, depending on the underlying configuration and flush settings. 

Identifier Generation: If the object's identifier is not set, Hibernate will generate one based on the defined generation strategy. 

Use Case: Use this method when you want to save a new entity and may need the generated identifier immediately after the save. 

persist Method 

Return Value: Returns void, not the identifier. 

Behavior Outside a Transaction: If called outside of a transaction, persist will generally not insert the object immediately but will wait for a transaction to be started. The object must be persisted by the time the transaction is committed, or an exception may be thrown. 

Identifier Generation: Similar to save, if the object's identifier is not set, Hibernate will generate one.

Guarantee of Synchronization: Ensures that the persisted state is synchronized with the current transaction. 

Use Case: Use this method when you want to save a new entity within the context of a transaction and do not need the identifier immediately.

save and persist Method Examples

    Session.save() method example: 

    In the below example, Session.save() method is called after the transaction.commit() but it executes the INSERT statement and it will insert the record into the database:
    public void saveExample(Student student) {
        Transaction transaction = null;
        try (Session session = HibernateJavaConfig.getSessionfactory().openSession()) {
    
            // start the transaction
            transaction = session.beginTransaction();
    
            // commit transaction
            transaction.commit();
    
            // save student entity
            Serializable id = session.save(student);
            System.out.println("database table id -> " + id);
    
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
        }
    }

    Session.persist() method example: 

    In the below example, the Session.persist() method is called after the transaction.commit() but it does not execute the INSERT statement and it won't insert the record into the database:
    public void persistExample(Student student) {
        Transaction transaction = null;
    
        // try with resource statement to auto close session object
        try (Session session = HibernateJavaConfig.getSessionfactory().openSession()) {
    
            // start the transaction
            transaction = session.beginTransaction();
    
            // commit transaction
            transaction.commit();
    
            // persist student entity
            session.persist(student);
    
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
        }
    }

    Summary

    Here's a table summarizing the key differences:
    Feature save() Method persist() Method
    Return Value Returns the generated identifier Returns void
    Behavior Outside Transaction May insert immediately Waits for a transaction
    Identifier Generation Generates if not set Generates if not set
    Guarantee of Synchronization No specific guarantee Ensures synchronization with the current transaction
    Use Case When an immediate identifier is needed Within the transaction context, no immediate identifier is needed

    Related Posts

    Comments