JMS Message is getting stale data from Hibernate
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 Method
@Override public void updateEntity(Integer entityId, String name) { Entity entity = getEntity(entityId); entity.setName(name); em.merge(entity); }
Listener Method
@PostPersist @PostUpdate public void afterUpsert(Entity entity) { this.entity = entity; JMSSubmitter submitter = getSubmitterBean(); submitter.submit(entity.getEntityId()); }
MDB Code
@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开发者_C百科 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.
It could be that you are either not using JTA to coordinate the JPA and JMS transactions, or if you are, you are running into the two-phase commit race condition (see: Delivery of JMS message before the transaction is committed).
精彩评论