I posted this earlier in the EJB3 form, but realise now that this is probably a more appropriate place for it. Apologies for the multiple posts!
I'm working on an EJB3 application using a JSP/Servlet front end on JBoss 4.2.2 GA against MySQL.
As part of a web based application process I'm persisting an entity within a session bean method. I then call flush() and refresh() on the entity manager so that the last modified and version column values are correct within the entity before I pass it back to the presentation layer, where it can potentially get updated and passed back to the session bean for updating.
My understanding of entity beans in EJB3 is that they would become detached in this scenario after the persisted bean is passed back to the presentation layer, so when I then send it back to a session bean to be merged via the entity manager, the entity manager should treat this as a detached entity and perform the operation successfully. However I'm seeing an OptimisticLockException being thrown by the entity manager. Just before the entity is merged I'm also setting a couple of values on it within the same session bean method. If I remove the setting of these values from the code then the merge operation works successfully. To me it seems like JBoss is potentially persisting the entity immediately after these values have been set, resulting in a stale version number existing within the entity that I then pass to the entity manager merge() method. Is this the right behaviour, and if so, does it mean that a merge is unnecessary? I thought that the entity would still be detached and therefore no database updates could take place until it became managed again after the called to the entity manager merge() method.
Maybe my understanding of when the entity actually becomes detached is the problem. If I'm using session bean with a transaction attribute of REQUIRED then I figured from what I've read that the entity would become detached when that transaction completes, so in this instance after the first method is called to persist and return the entity back to the presentation layer. Once I then start populating values within the detached entity in the presentation layer, prior to the session bean update method being called, then surely JBoss won't be persisting the entity before the method is actually called? So if it isn't then the version number on the detached entity should be in synch with the database.
If there anyone able to shed some light on this then I'd really appreciate it as I can't get my head round the behaviour and the correct pattern to use in this scenario.