@ SuppressWarnings ( "unchecked" ) protected < E > List < E > updateWithOptimisticLockInternal ( List < E > entities , PropertyMetadata versionMetadata ) { Transaction transaction = null ; try { entityManager . executeEntityListeners ( CallbackType . PRE_UPDATE , entities ) ; Entity [ ] nativeEntities = toNativeEntities ( entities , entityManager , Intent . UPDATE ) ; // The above native entities already have the version incremented by // the marshalling process Key [ ] nativeKeys = new Key [ nativeEntities . length ] ; for ( int i = 0 ; i < nativeEntities . length ; i ++ ) { nativeKeys [ i ] = nativeEntities [ i ] . getKey ( ) ; } transaction = datastore . newTransaction ( ) ; List < Entity > storedNativeEntities = transaction . fetch ( nativeKeys ) ; String versionPropertyName = versionMetadata . getMappedName ( ) ; for ( int i = 0 ; i < nativeEntities . length ; i ++ ) { long version = nativeEntities [ i ] . getLong ( versionPropertyName ) - 1 ; Entity storedNativeEntity = storedNativeEntities . get ( i ) ; if ( storedNativeEntity == null ) { throw new OptimisticLockException ( String . format ( "Entity does not exist: %s" , nativeKeys [ i ] ) ) ; } long storedVersion = storedNativeEntities . get ( i ) . getLong ( versionPropertyName ) ; if ( version != storedVersion ) { throw new OptimisticLockException ( String . format ( "Expecting version %d, but found %d" , version , storedVersion ) ) ; } } transaction . update ( nativeEntities ) ; transaction . commit ( ) ; List < E > updatedEntities = ( List < E > ) toEntities ( entities . get ( 0 ) . getClass ( ) , nativeEntities ) ; entityManager . executeEntityListeners ( CallbackType . POST_UPDATE , updatedEntities ) ; return updatedEntities ; } catch ( DatastoreException exp ) { throw DatastoreUtils . wrap ( exp ) ; } finally { rollbackIfActive ( transaction ) ; } }
Internal worker method for updating the entities using optimistic locking .