Difference save vs saveOrUpdate persist

Difference save vs saveOrUpdate and persist

1.  save() Method

  • Definition : The save() method is used to insert a new record into the database. It generates an identifier for the entity and saves it immediately.
  • Characteristics
  • Returns the generated identifier.
  • Works with transient entities only.
  • Entity is immediately persisted in the database.
  • Usage : Suitable for inserting new records.

2.  saveOrUpdate() Method

Definition

The saveOrUpdate() method is used to either save a new entity or update an existing one. It checks if the entity has an identifier; if it does, it updates the corresponding record, otherwise, it inserts a new record.

Characteristics

  • Combines the functionality of save() and update().
  • Suitable for both transient and detached entities.
  • Can handle new and existing entities.
  • Usage : Useful when you are not sure if the entity is new or needs to be updated.

3.  persist() Method

Definition

  • The persist() method is used to make a transient entity persistent. It does not return an identifier and is designed to be used within the context of a long-running transaction.

Characteristics

  • Does not return the identifier.
  • Entity is not immediately persisted in the database.
  • The entity becomes managed and will be persisted when the transaction is committed.
  • Usage : Suitable for scenarios where immediate persistence is not required.

save vs saveOrUpdate persist

Example
Example in Java:
java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateMethodsExample {
    public static void main(String[] args) {
        // Create SessionFactory
        SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml")
                .addAnnotatedClass(Student.class)
                .buildSessionFactory();

        // Use save() method
        Session session1 = sessionFactory.openSession();
        session1.beginTransaction();
        Student studentSave = new Student("John", "Doe", "john.doe@example.com");
        Integer id = (Integer) session1.save(studentSave);
        System.out.println("Saved student ID: " + id);
        session1.getTransaction().commit();
        session1.close();

        // Use saveOrUpdate() method
        Session session2 = sessionFactory.openSession();
        session2.beginTransaction();
        studentSave.setFirstName("Jane");
        session2.saveOrUpdate(studentSave);
        System.out.println("Updated student: " + studentSave);
        session2.getTransaction().commit();
        session2.close();

        // Use persist() method
        Session session3 = sessionFactory.openSession();
        session3.beginTransaction();
        Student studentPersist = new Student("Alice", "Smith", "alice.smith@example.com");
        session3.persist(studentPersist);
        System.out.println("Persisted student: " + studentPersist);
        session3.getTransaction().commit();
        session3.close();

        sessionFactory.close();
    }
}

@Entity
@Table(name = "student")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    // Constructors
    public Student() {}
    public Student(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    // Getters and setters
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    
    @Override
    public String toString() {
        return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
    }
}


In this example

  • save() Method : A new Student entity is created and saved, generating an identifier.
  • saveOrUpdate() Method : The same entity is updated, demonstrating both save and update operations.
  • persist() Method : Another new Student entity is created and persisted without immediately saving to the database.

Homepage

Readmore