views:

113

answers:

2

I have an AbstractEntity class as superclass for all my entites that defines an optimistic lock column like this:

@Version
private long lockVersion;

Now I often get OptimisticLockingExceptions on entities, that are only changed in one the mappedBy relations similar to the following:

@OneToMany(mappedBy = Property.PROPERTY_DESCRIPTOR, cascade = { CascadeType.REMOVE })
private Set<Property> properties = new HashSet<Property>();

Is it possible to exclude those collections from Hibernate optimistic locking? The entity is not changed in the database at all... only others referencing it.

A: 

i think the accepted answer in this question should help you:link

I havn't tried it myself though, but it could be possible to detect changes not requiring version update and not increment the version.

Tomas
Hmm might be... but I've hoped for some kind of annotation or hibernate feature to solve this... we'll see.
Daniel Bleisteiner
Agreed, this is a bit hackish...
Tomas
+1  A: 

You can exclude a particular property (and / or collection) from increasing the version number if it's dirty by explicitly excluding it via @OptimisticLock annotation:

@OptimisticLock(excluded=true)
@OneToMany(mappedBy = Property.PROPERTY_DESCRIPTOR, cascade = { CascadeType.REMOVE })
private Set<Property> properties = new HashSet<Property>();

Be aware that it's a Hibernate extension to JPA standard.

ChssPly76
This looks promising... I'll check if it solves my problems.
Daniel Bleisteiner
I've added this annotation to all mappedBy Collections that don't cascade either merge or persist.An alternative solution is to distinguish between entity.getCollection().add(...) for unmanaged entities and em.refresh(entity) for managed entities. This avoids the locking probleme too.
Daniel Bleisteiner