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;
}
From what I understood you are interested if the values of objects are the same compared to
Item somethingandItem fetchedThat 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
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
readThatThingmethod, go to your database, alter the data with query, and then step overreadThatThingand allow it to be called, you will see that the data is being called from what is in the database and the data infetchedwill 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.