Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between save() and commit() in a database while using hibernate

Tags:

java

hibernate

I came across this example from a book while learning about the Hibernate framework.

public class BasicMovieManager()
{
    private void persistMovie(Movie movie)
    {
        Session session=sessionFactory.getCurrentSession();
        session.beginTransaction();
        session.save(movie);
        session.getTransaction().commit();
    }
}

I can understand that the Movie object has to be mapped and written to the database. I also understand that the commit step will write to the database. But what is the purpose of save() here? A few sources I referred say that save() persists the data. Doesn't persist mean writing to a permanent storage? If not,what exactly does it mean?

like image 997
Rameshwar Bhaskaran Avatar asked Jan 18 '26 20:01

Rameshwar Bhaskaran


2 Answers

I Believe the comparison is misplaced,you should compare

Commit vs Flush

and

Save vs Persist

Edited:

You should know this:

transient: never persistent, not associated with any Session.    
persistent: associated with a unique Session.
detached: previously persistent, not associated with any Session.
  1. Commit will save the data to DB, so you cannot rollback anymore, in opposed to Flush.

  2. Save will generate and return identifier prior to writing the object, later upon Flush or Commit it writes the data to the database.

    Where Persist will not return a value,as you only mark the object as dirty in the cache, so upon flush or commit it will be saved, this is useful when persisting multiple objects in a transaction.

like image 82
shaydel Avatar answered Jan 20 '26 10:01

shaydel


Quick answer: save() stores the data in the database. commit() makes it visible to others (cf. isolation levels).

Slightly longer answer: Database operations should obey the ACID principle, (A)tomicity being the operative element here. If you are doing more than one change/insert, you can wrap it in a transaction and commit/reject the entire set of operations as a whole.

In your example it doesn't make much sense to start a transaction, but in real-life situations it very much makes sense.

Cheers,

like image 22
Anders R. Bystrup Avatar answered Jan 20 '26 10:01

Anders R. Bystrup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!