Hibernate
session.persist
session.save
Java
ORM

What's the difference between session.persist and session.save in Hibernate?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Hibernate is an Object-Relational Mapping (ORM) framework commonly used in Java applications to interact with databases. Two of the functions available in Hibernate for saving an object to a database are session.persist() and session.save(). Although they may appear similar, they have distinct behaviors and purposes. Understanding the differences between these two methods is crucial for developers working with Hibernate.

Overview

Both session.persist() and session.save() are used to store Java objects in a database table. However, they differ in terms of behavior, return type, and usage.

session.save()

  1. Functionality:
    • The session.save() method is used to save a transient instance by assigning it a database identifier and persist it to the datastore.
  2. Return Type:
    • The primary distinction of the save() method is that it returns a serializable identifier of the entity object that gets saved to the database.
  3. Generation of SQL:
    • An immediate SQL INSERT statement is executed as soon as save() is called.
  4. Use Case:
    • It is typically used when you need the generated identifier immediately after the save operation.

session.persist()

  1. Functionality:
    • The persist() method makes a transient instance persistent. It does not return any identifier.
  2. Return Type:
    • Unlike save(), persist() does not have a return value, hence no identifier is returned.
  3. Generation of SQL:
    • No SQL INSERT is executed immediately after calling persist(). The SQL is deferred and usually executed during a flush operation.
  4. Cascade Type:
    • The entity gets managed by the Hibernate Session only after it is persisted, not immediately.
    • Often used where there is no need for an immediate identifier and delayed execution can optimize performance.

Technical Differences

Here's a detailed breakdown of technical differences between session.persist() and session.save():

Aspectsession.persist()session.save()
Return TypevoidSerializable (ID)
Immediate SQL InsertNo, executed on flush/commitYes, executes immediately
Transient ObjectBecomes persistent, but no identifier returned immediatelyBecomes persistent identifier returned
BehaviorCascades when CascadeType.PERSIST usedCascades when saving an instance
Usage ScenarioSerialization not needed Performance optimization with deferred SQL executionWhen the primary key is required after saving

Example

java
1@Entity
2class Employee {
3   @Id @GeneratedValue(strategy=GenerationType.AUTO)
4   private Long id;
5   private String name;
6
7   // Constructors, getters, setters omitted
8}
9
10Session session = sessionFactory.openSession();
11session.beginTransaction();
12
13// Using save()
14Employee emp1 = new Employee();
15emp1.setName("John Doe");
16Serializable id = session.save(emp1); // returns the identifier
17System.out.println("Employee ID: " + id);
18
19// Using persist()
20Employee emp2 = new Employee();
21emp2.setName("Jane Doe");
22session.persist(emp2); // no identifier is returned
23// ID is retrieved after flush or commit, if necessary
24
25session.getTransaction().commit();
26session.close();

Additional Considerations

Transaction Management

  • Transaction Boundaries: Both session.save() and session.persist() require an active transaction. Declaring transaction boundaries is important to ensure that the changes are committed to the database.

merge() Overlap

It's worth noting that another method, session.merge(), often gets confused with these methods. The merge() function is used for merging the state of a detached entity into the persistence context, which differs from both save() and persist().

Flush Behavior

Flushing clears the persistence context and synchronizes the state with the database:

  • persist(): More aligned with flush behavior, optimizing SQL operations.
  • save(): Immediate flush-oriented as it executes the SQL right away.

Conclusion

The choice between session.persist() and session.save() depends on the specific requirements of the application, such as immediate identifier needs or when controlling the flush behavior is preferred. Understanding how each operates enables developers to use Hibernate more effectively, tailoring solutions to application performance needs and data integrity requirements.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.