Created
February 8, 2019 16:15
-
-
Save sebersole/a3b2501c17cde25aaafdbf3eb74b6a7b to your computer and use it in GitHub Desktop.
Test illustration isolation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.hibernate.testing.transaction.TransactionUtil2.inSession; | |
import static org.hibernate.testing.transaction.TransactionUtil2.inTransaction; | |
class TheTest { | |
@Test | |
public void testIsolation() { | |
// open the "writing Session" | |
inSession( | |
getTheSessionFactory(), | |
writingSession -> { | |
// start a transaction against the "writing Session" and update the data | |
inTransaction( | |
writingSession, | |
// get your entity and update its state | |
final YourEntity data = writingSession.find( YourData.class, theId ); | |
data.setYourAttribute( newValue ); | |
// flush "writing Session" (but do not commit!). This performs the UPDATE(s). | |
// However, because the transaction is not committed, other transactions will | |
// not yet be able to see it. This is called transaction-isolation and is a | |
// GoodThing(tm) | |
writingSession.flush(); | |
// meanwhile open the "reading Session" and start a transaction | |
inTransaction( | |
getTheSessionFactory(), | |
readingSession -> { | |
// try to read the updated | |
final YourEntity isolatedData = readingSession.find( YourData.class, theId ); | |
// the "reading Session" will not (yet) see the change (but uncommited) state. | |
// | |
// NOTE: based on the exact isolation configured for your driver/database | |
// this may also block until the "writing Session" transaction has committed | |
// releasing the database "resource locks" or may also throw a "deadlock" | |
// type exception | |
// | |
// Again, this is all called transaction isolation and is a GoodThing(tm). | |
// And a standard ANSI SQL thing. Not even close to a "Hibernate/Oracle bug" | |
assertFalse( newValue, isolatedData.getYourAttribute() ); | |
assertTrue( originalValue, isolatedData.getYourAttribute() ); | |
} | |
); | |
// assuming the attempted read above did not block or throw the exception, | |
// at this point the transaction associated with the "writing Session" has | |
// been committed and we should be able to open a "reading Session" and see | |
// the changed state... | |
} | |
); | |
final Session writingSession = openSession(); | |
final Session readingSession = openSession(); | |
inTransaction( | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment