I have a managed entity which has a EntityListener attached to it. The EntityListener on PostUpdate and PostPersist adds the entity to a JMS queue to do some more processing. So here is the scenario, I have a session bean which updates the Entity and merges the changes, which in turn triggers the PostUpdate on the listener. But at that point when the MDB starts to consume the JMS message it gets the Entity out of the EntityManager but the Entity it is getting is the old values for that object. Here is the basic code of what I am doing.
Session Bean MethodCode:
@Override
public void updateEntity(Integer entityId, String name) {
Entity entity = getEntity(entityId);
entity.setName(name);
em.merge(entity);
}
Listener MethodCode:
@PostPersist
@PostUpdate
public void afterUpsert(Entity entity) {
this.entity = entity;
JMSSubmitter submitter = getSubmitterBean();
submitter.submit(entity.getEntityId());
}
MDB CodeCode:
@Override
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
processMessage(textMessage);
} catch (Exception ex) {
logger.error("Unable to process the Entity message", ex);
}
}
private void processMessage(TextMessage message) throws Exception {
Integer entityId = new Integer(message.getText());
//Right here I am getting stale data.
Entity entity = entityBean.getEntity(entityId);
// ...
//Some processing is done here
// ...
entity.setSomeOtherValue("blah");
entityBean.updateEntity(entity);
}
So my question really is why am I having this problem, I think it is a transaction problem. I think my initial update transaction hasn't commit before the JMS starts consuming the message.