I'm a bit confused about the concept of Sessions and Transactions in Hibernate. As far as i understand, Hibernate uses Sessions (Persistence Context), which is basically a Cache for Entitys that need to be persist, deleted or whatever in the Database. Sessions encapsulate Transactions, so i start a Session, followed by creating a Transaction. After the Transaction is closed, everything from the Persistence Context is flushed to the Database.The same thing will happen, if i close the Session.
Why do i need both? Can i do the same without creating a Transaction?
First of all, you can open more than 1 transaction within the same session.
Now, flushing doesn't necessarily relate to transaction commit. When you save()
an entity - it'll be flushed if you use Identity generation strategy. When you select
something - Session will also flush (if flush mode is AUTO). And you can even tell Hibernate not to flush before transaction commits (flush mode MANUAL).
Transactions are only responsible for ACID, it's a DB feature. While Session is responsible for managing entities, generating SQL, handling events. It's a Java thing.
PS: Session isn't just a "cache". It's also a way to track which entities are changed. So it's more than just an optimization trick.
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