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?
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.
Commit will save the data to DB, so you cannot rollback anymore, in opposed to Flush.
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.
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With