Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Session vs Transaction

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?

like image 645
dev8872 Avatar asked Sep 10 '25 12:09

dev8872


1 Answers

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.

like image 147
Stanislav Bashkyrtsev Avatar answered Sep 13 '25 01:09

Stanislav Bashkyrtsev