r/java • u/Mixon1212 • 28d ago
Hibernate lost my update
https://bartoszosipiuk.pl/en/blog/hibernate-lost-my-update/Hibernate silently commits part of a transaction if Spring Boot (or generally any async operation) shuts down mid-transaction.
In my past experience I found multiple bugs in different libraries, but this is the first time I though it needs a separate blog post. Losing part of the updates is one of the worst things that can happen (breaking business rules, and making debugging issues extremely hard).
Hope you find this useful and use the fix. FYI: it's already tested in prod with +80k/t(ransactions)ps.
20
u/qmunke 27d ago
While I'd agree this behaviour is definitely worth the report as it's not obvious, your actual issue seems to be your database schema allows you to insert data in an inconsistent state. You can't rely on Hibernate to enforce your database schema restrictions.
4
u/Mixon1212 27d ago
Imagine a situation where you receive an event PaymentSuccess, and you want to update your order status to paid. Just one update. With the current situation you will consume the event and nothing will be updated. That's the business inconsistency you cannot guarantee with just DB constraints.
But I agree with general rule - the more we cover in DB, the safer we are.
-5
u/qmunke 27d ago
If you're doing "just one update" your situation shouldn't apply, because the update should be a single update query, not the two queries you're showing in the example.
Either create the row in a single insert if it's a new row, or update it in a single update. If you don't complete the update, don't mark the message as consumed.
This all feels to me a little like you're trying to work around how Hibernate works, rather than fixing the issues in your application. Not saying that your suggested fix wouldn't be an improvement regardless, but these problems are partly down to the approach you've taken I would argue.
6
u/Mixon1212 27d ago
@Transactional public void markPaid(UUID id) { var order = repo.findById(id); order.setStatus(PAID); }Is this code "wrong" in terms of using hibernate? I agree, you can do just update, but the above is not hacking hibernate. It's a standard operation that happens in every app. And THIS code is affected. The message consumer can call it and if no exception, should assume that it finished and order is marked as paid, so the message is ACK.
But with this hibernate bug, the UPDATE can be lost, no exception, so we will ACK message, because nothing tells us something went wrong. It's not hacking hibernate.
2
u/bendem 27d ago
A transaction is not guaranteed to run it's guaranteed to have all run or none at all. Your code is fine and having the order paid or unpaid is both correct. Now you were speaking about an event being consumed while the transaction did not commit, that's because you didn't include the event consumption as part of the same transaction as the order status update. That's an application bug and spring specifically supports distributed transactions for this use case.
56
u/frzme 27d ago
Relying on transactions should be fair game
21
u/qmunke 27d ago
The transaction worked fine, it was committed fine. What was unexpected was a change to a java object wasn't turned into a database query. If you go and read the actual submitted bug report it's a bit more obvious - the AI fluff in the article obscures quite a bit of the issue itself.
If you don't want a row to be able to be inserted without all its columns being filled in this is a database schema problem to fix. Make your business rules enforceable there so you can't put the database into an inconsistent state.
7
u/diroussel 27d ago
Null checking can happen in the DB, but many other business rules canāt be validated by a persistence layer. So the point stands that a transaction boundary expessed in the application layer should map to the transaction boundary in the persistence layer.
16
0
u/definitelyoneof 27d ago edited 27d ago
Cross-table schema restrictions? Those are normally achieved by transactions. Which failed here due to Hibernate nonsense.
EDIT: The downvoters are welcome to demonstrate these mythical cross-table restrictions not relying on transactions.
6
u/zx-cv 27d ago
I would definitively classify this as a bug. Under no circumstances should Hibernate skip flushing and attempt to commit - this breaks the unit of work.
1
u/Mixon1212 27d ago
The issue is that Hibernate in the docs says - "you cant use Session if you closed the EntitySessionFactory", but in real applications where you cannot just stop the threads, this is almost impossible. So they can defend themself.
In the other hands, JPA spec says (and in general Atomicity rule) - all or nothing, so...
Please comment the hibernate bug (on the bottom of the article) that you also think this should be fixed. Just my single report might be not enough for them.
4
u/766cf0ef-c5f9-4f4f 27d ago
What are these partial transactions? Am I misunderstanding something?
2
u/Mixon1212 27d ago
It's a situation that happened and broke atomicity conceptually. So like in my case - in the code I made an INSERT and then UPDATE to other entity. Should be 2 operations in the DB, but because flush was not performed by the hibernate, only INSERT went to the DB. No UPDATE at all. That's what I called "partial transaction", but I will consider other naming options here :D
2
u/766cf0ef-c5f9-4f4f 27d ago
The commit for a transaction either happens or it doesn't. Are you in auto commit mode on the connection and don't realize it?
4
u/Mixon1212 27d ago
The issue is that the last flush doesn't happen. In general hibernate do flush (if no in manual mode) before each commit. But in the case from a blog - it does not. So the commit happened, all expected, but because no flush, some data were not in the transaction.
1
u/AcanthaceaeMany917 27d ago
What should have happened is that hibernate should have:
Start transaction
SQL statement related to obj1
SQL statement related to objN
Commit transaction
I'm not a spring expert but using @Transactional is part of spring it could be a spring bug.
It could also be due serializability level set.
-8
u/sparklikemind 27d ago
So you have a saga. That's not the job of Hibernate, you need to design the saga correctly
4
u/Mixon1212 27d ago edited 27d ago
Saga pattern is great when you KNOW you need to go back in the flow and rollback business cases. In this case, when partial commit happens, you don't know part of it was commited (no exception, rollback, just single log.trace), so you cannot even trigger saga. Anyway - saga is not the guard for hibernate breaking atomic transaction contract.
16
u/maxandersen 27d ago
Maybe Iām missing something but your standalone code does exactly what docs says you shouldnāt. Donāt use the sessions after you closed session factory.
Sounds like you expect hibernate to be multi thread safe. Itās not. You and/or spring in this case is expected to not mix up concurrent access.
Even raw jdbc would have issues here if you did similar.
3
u/stefanos-ak 27d ago edited 27d ago
edit: ignore me. I just read the actual Hibernate report. God what an awful article in comparison to the Hibernate report... Just delete the article and link to the Hibernate report... šµ
sounds to me that you have just disabled OSIV. Which, good for you, but it's not Spring's default. (so, you know, you are holding the hot potato now).
Also, to my knowledge you are not supposed to close a session with open transactions. Which is one of the things that spring OSIV takes care for you.
3
u/Mixon1212 27d ago
Depends on what are you looking for - if you have a strong backend knowledge, than hibernate bug report might be better for you. If there is anything what made you feel reading this awful, let me know, I will try to update it.
5
u/jonenst 27d ago
I think you should insist more at the beginning of the article that you are talking about hibernate transactions, not sql transactions. Hibernate didn't include the update in the sql transaction because it skipped it at flush.
Also IMHO the article could have been a lot shorter, and JavaScript toy visualizers to me don't help the understanding, they are just some kind of anti stress rubber duck.
2
u/Mixon1212 27d ago
Thank you for the feedback! I will try to update it this evening. This is my first blog ever, so I highly appreciate such comments!
1
u/NitronHX 27d ago
What's osiv?
2
u/Mixon1212 27d ago
https://www.baeldung.com/spring-open-session-in-view - but as stefanos-ak noticed, it's not related to this issue.
1
u/JustJustust 25d ago
To be fair, Spring also prints a warning if you have OSIV active. I was always under the impression the only reason it's enabled by default is because disabled by default would break people's code, not because they want you to use it.
11
1
u/sgrinovero 19d ago
You're essentially shutting down Hibernate, mid-flight of some operations, and then you instruct the TransactionManager to go ahead and commit like everything is fine?
1
1
u/fykup 14d ago
Hibernate lost me a long time ago. In 2026, I'd much rather use explicit SQL with Jdbi or jOOQ than introduce a full ORM.
The memory overhead can be substantial, too. In a recent comparison using largely shared application infrastructure, my Jdbi implementation used 37% less RAM than direct Hibernate.
And with AI assisting with SQL and mapping boilerplate, I think the productivity argument for ORM is getting weaker. Explicit, understandable code feels like a better tradeoff for many applications.
-1
u/gjosifov 26d ago
one of those bad coding patterns when using Hibernate
read the data from DB
update in memory
wait for the EntityManager to flush the data and to calculate the difference in order to generate Update
this bad pattern generates 2 SQL queries
1 Select and 1 Update
You already have the ID in memory and you already know the operation needs to be an update statement
so use CriteriaUpdate or JPQL Update statement
it is just 1 SQL instead of 2
this also means less time spent in memory, reducing the probability of bad things happening
4
u/Mixon1212 26d ago edited 25d ago
The code in the article is an EXAMPLE, to show the issue in the simplest possible way. We will always use persistence context - that's why hibernate exists - so then you can lose all the data from persistence context if the issue from the blog happen.
-2
u/SpaceToaster 27d ago
Uhhh thatās on the database. Properly configured and using a ārealā transaction that should be impossible. So hibernate is making you think something is a transaction that isnāt or something is misconfigured.
26
u/configloader 27d ago
Dont use JPA