0

What is the behavior for Spring's Transactional when writing-then-reading?

Let's say I have a method annotated with @Transactional, and the first thing it does is modify an object. Then, I read that object. Will the fetched object be the old, unmodified version or the modified one? Or, does it consider this a dirty read?

@Transactional
public Item writeThenRead(Item something) {
    myDao.writeSomething(something);
    Item fetched = myDao.readThatThing(something.getId());

    return fetched;
}
1
  • That totally depends on the way the data is stored? JDBC, JPA or even is it a classical database. Commented Nov 30, 2023 at 7:40

1 Answer 1

0

From what I understood you are interested if the values of objects are the same compared to Item something and Item fetched

That statement is true

But what is not true is the fact that they are not allocating the same memory, so it is a different object but it still has the same values or from your question "modified version". Whatever you updated and saved or called writeSomething, those values after that method will be reflected in Item fetched, only the memory location will be different.

You can check that in the debugger, you will see in debugger something like

something = {Item@5555} "Item{id=14,name='UpdatedName'}"
fetched = {Item@9504} "Item{id=14,name='UpdatedName'}"

Values will be the latest, but memory location will not point to the same object. Keep in mind that moment after you step over your "writeSomething" your changes will be present in your database, so when your code reaches "readThatThing" it will be reading the data from your database, not your memory.

The best way to test that is to simply update the data and put debug on readThatThing method, go to your database, alter the data with query, and then step over readThatThing and allow it to be called, you will see that the data is being called from what is in the database and the data in fetched will be whatever you wrote in your query in the database.

Now as for "dirty read" that is opinion-based, if it meets your requirement to check the values if they have been updated and propagated to the database, that is commpletely fine approach and even makes a good test case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.