简体   繁体   中英

Update Object with optimistic locking without incrementing the version

We have a Java EE application which uses JPA and Eclipselink. We use optimistic locking for all our entities. One of our main entities has a "lastConnected" attribute which is updated everytime we get a request from the client. Asynchronously there might be other update to any of the other attributes, so from time to time this causes an OptimisticLockException.

Is there any possibility to to update the "lastConnected" attribute without incrementing the version field of the entity? I don't realy care if my "big" update overrides the "lastConnected" changes, so don't want this small update to cause an OptimisticLockException.

Of course it would be possible to move the "lastConnected" attribute into its own entity, but I don'r realy like this solution.

Unless I misunderstand you can just add the @Version to the lastConnected.

@Version
private Date lastConnected;

Or a better way for your requirement is to add an interceptor

public class MyInterceptor extends EmptyInterceptor {

    private static final long serialVersionUID = 1L;

    @Override
    public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
            String[] propertyNames, Type[] types) {
// here you have the current state and previous state so you can add logic here
            return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
        }
    }

Add to you jpa properties

<prop key="hibernate.ejb.interceptor">com.greg.MyInterceptor</prop>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM