Im trying to write a small application which should offer a restful interface. This at it's own works together with the current hibernate-version relatively good.
When trying to test, my serverside code for modifying like this:
EntityManager manager = // [...]
manager.getTransaction.begin();
AEntity entity1 = manager.find(AEntity.class, 4711);
entity1.setSomething("whatever");
manager.merge(entity1);
manager.getTransaction.commit();
manager.close();
Normally this should work. But when testing with JUnit it does not.
EntityManager manager = // [...]
// insert some test data
Response r1 = target(url).request().put(someAEntityChangeInfo);
assertEquals(200, r1.getStatus());
manager.refresh(mAEntity);
assertEquals("whatever", mAEntity.getSomething()); // was set and commited on server-side
The last assert fails saying that mAEntity
(which should be updated) contains the old data. I'm also not sure whether this behaviour may be a race condition, since once (but only once) the assert was okay.
How to make sure that data got really commited before asserting?
Using MariaDB, MariaDB Connector/J, Hibernate 5.0.7 and Jersey 2.22.1.
The issue seems to be a mix of flushing transactions and connection isolation.
To resolve this:
manager.setFlushMode(FlushModeType.COMMIT);
READ_COMMITED
so that the test-connection is able to see the changes made by tested code with another EntityManager. For production a higher isolation my be better. JPA-property:<property name="hibernate.connection.isolation" value="2" />
There is also hibernate's
autocommit
property. Set tofalse
for keeping more control about the behaviour.