michi.0x5d February 2016

Hibernate: Commiting MariaDB via JPA

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.

Answers


michi.0x5d February 2016

The issue seems to be a mix of flushing transactions and connection isolation.

To resolve this:

  • Set the flush-mode to commit: manager.setFlushMode(FlushModeType.COMMIT);
  • Set connection isolation for testing to 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 to false for keeping more control about the behaviour.

Post Status

Asked in February 2016
Viewed 3,405 times
Voted 10
Answered 1 times

Search




Leave an answer