Transactions
Understand when Hibernate writes, and why it doesn't always write what you think.
Transactions and Cache Management
Every JPA developer has an experience they never forget: modifying an entity without ever calling a save method, and finding that the database was updated anyway. Or the reverse: explicitly calling save() and seeing nothing change. In both cases the cause is the same: you don't know whether the object you're handling is managed by the persistence context.
The persistence context is the heart of how JPA works. It is an in-memory registry, bounded by the transaction, that holds every entity loaded or created during that transaction. Hibernate also keeps a snapshot of each entity's state at the moment it was loaded. At the end of the transaction, it compares the objects to their snapshots and issues an UPDATE for each difference it finds. This mechanism, called dirty checking, is why a simple setPrix() is enough to write to the database.
This elegance comes at a price: the moment the SQL is sent is no longer determined by your code, but by Hibernate. Writes are accumulated and sent at the last moment, in an order Hibernate chooses. Understanding this deferral is what separates the developer who endures @Transactional from the one who masters it.
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion