The
EJB spec says the following in section 3.4.2:
Quote:
An entity may access the state of its version field or property or export a method for use by the application to access the version, but must not modify the version value[17]. Only the persistence provider is permitted to set or update the value of the version attribute in the object.
However, in a web application I am developing I have a need to update an entity with a version number posted from a web form. The form in question does not contain all the fields belonging to the entity, so my workflow is as follows:
1. Retrieve entity from database
2. Update the fields provided by the web form (including version)
3. Persist entity
As per the spec, Hibernate notes that the version is dirty and updates the entity with the version last seen in the database, so optimistic locking is ineffective. There are two ways around this that I can think of:
1. Include all the entities fields in the web form, and therefore avoid the need to retrieve the entity from the database in step 1 - just create the entity from the fields provided. This is not an option - it's not acceptable to make everything in the database available to a user via hidden form fields, especially when dealing with user accounts and other security related entities.
2. Detach the entity before persisting it to the database. This works perfectly, except that the JPA spec does not provide a means to detach a single entity, and detaching everything via em.clear() does not seem like a good solution in terms of the control you have, and possibly some performance implications.
Anybody else run across this scenario? Suggestions on how to handle this? I would be willing to move over to Hibernate annotations rather than using the JPA interface, if that provides the cleanest solution.
Thanks!
Hibernate version:
hibernate-core: 3.2.6.ga
hibernate-annotations: 3.3.1.GA
hibernate-commons-annotations: 3.0.0.ga
ejb3-persistence: 1.0.1.GA
hibernate-entitymanager: 3.3.2.GA