I'm having some flaky issues with transactional hibernate. As shown in the example below the entity is persisted with persist()
, I retrieve the entity with find()
and return the Id from the method. But when the Id is used later to retrieve the entity again, it sometimes (1/2000) cannot find the entity again.
- I thought when leaving the first
@Transactional
create method that hibernate would commit? - Could it be that hibernate has yet to be able to commit before the
getById()
is ran? - Could it be that
@TransactionManagement(TransactionManagementType.CONTAINER)
is affecting how and when hibernate commits?
@TransactionManagement(TransactionManagementType.CONTAINER)
public class MDB implements MessageListener {
@Inject
private MyService service;
@Override
public void onMessage(final Message message) {
Id id = service.create(message);
...
// Will not find entity on next method call.
MyEntity myEntity = service.getById(id);
}
}
public class MyServiceImpl implements MyService {
@Override
@Transactional(Transactional.TxType.REQUIRED)
public Id create(Message message) {
MyEntity myEntity = new MyEntity();
Id id = new Id(message);
myEntity.setId(id);
entityManager().perisist(myEntity);
MyEntity myEntityFromEm = entityManager().find(MyEntity.class, id);
return myEntityFromEm.getId();
}
@Override
@Transactional(Transactional.TxType.REQUIRED)
public MyEntity getById(Id id) {
return entityManager().find(MyEntity.class, id);
// Exception here - Cannot find entity with this id.
}
}
Have omitted to recreate how the class gets its injected EntityManager, and how the MessageListener is configered. In the real program there is multiple lines in-between create()
and getById()
.
I expected that hibernate did a commit on the persisted entity when leaving the method. I have tried to log the EntityManager HashCode, suspecting that different "sessions" caused the issues. I have tried to manually flush()
, but since I cannot reproduce the issue in pilot/test, it is very hard to test.