Java Code Examples for org.hibernate.LockMode#NONE

The following examples show how to use org.hibernate.LockMode#NONE . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private CompletionStage<Object> doOnLoad(
		final EntityPersister persister,
		final LoadEvent event,
		final LoadEventListener.LoadType loadType) {

	final EventSource session = event.getSession();
	final EntityKey keyToLoad = session.generateEntityKey( event.getEntityId(), persister );
	if ( loadType.isNakedEntityReturned() ) {
		//do not return a proxy!
		//(this option indicates we are initializing a proxy)
		return load( event, persister, keyToLoad, loadType );
	}
	//return a proxy if appropriate
	else if ( event.getLockMode() == LockMode.NONE ) {
		return proxyOrLoad( event, persister, keyToLoad, loadType );
	}
	else {
		return lockAndLoad( event, persister, keyToLoad, loadType, session );
	}
}
 
Example 2
public LockMode getCurrentLockMode(Object object) throws HibernateException {
	errorIfClosed();
	checkTransactionSynchStatus();
	if ( object == null ) {
		throw new NullPointerException( "null object passed to getCurrentLockMode()" );
	}
	if ( object instanceof HibernateProxy ) {
		object = ( (HibernateProxy) object ).getHibernateLazyInitializer().getImplementation(this);
		if ( object == null ) {
			return LockMode.NONE;
		}
	}
	EntityEntry e = persistenceContext.getEntry(object);
	if ( e == null ) {
		throw new TransientObjectException( "Given object not associated with the session" );
	}
	if ( e.getStatus() != Status.MANAGED ) {
		throw new ObjectDeletedException( 
				"The given object was deleted", 
				e.getId(), 
				e.getPersister().getEntityName() 
			);
	}
	return e.getLockMode();
}
 
Example 3
Source Project: lams   File: SessionImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public LockMode getCurrentLockMode(Object object) throws HibernateException {
	checkOpen();
	checkTransactionSynchStatus();
	if ( object == null ) {
		throw new NullPointerException( "null object passed to getCurrentLockMode()" );
	}
	if ( object instanceof HibernateProxy ) {
		object = ( (HibernateProxy) object ).getHibernateLazyInitializer().getImplementation( this );
		if ( object == null ) {
			return LockMode.NONE;
		}
	}
	EntityEntry e = persistenceContext.getEntry( object );
	if ( e == null ) {
		throw new TransientObjectException( "Given object not associated with the session" );
	}
	if ( e.getStatus() != Status.MANAGED ) {
		throw new ObjectDeletedException(
				"The given object was deleted",
				e.getId(),
				e.getPersister().getEntityName()
		);
	}
	return e.getLockMode();
}
 
Example 4
/**
 * @param lockModes a collection of lock modes specified dynamically via the Query interface
 */
protected LockMode[] getLockModes(Map lockModes) {

	if ( lockModes==null || lockModes.size()==0 ) {
		return defaultLockModes;
	}
	else {
		// unfortunately this stuff can't be cached because
		// it is per-invocation, not constant for the
		// QueryTranslator instance

		LockMode[] lockModeArray = new LockMode[entityAliases.length];
		for ( int i = 0; i < entityAliases.length; i++ ) {
			LockMode lockMode = (LockMode) lockModes.get( entityAliases[i] );
			if ( lockMode == null ) {
				//NONE, because its the requested lock mode, not the actual!
				lockMode = LockMode.NONE;
			}
			lockModeArray[i] = lockMode;
		}
		return lockModeArray;
	}
}
 
Example 5
@SuppressWarnings("unchecked")
protected List<R> doList() {
	if ( getMaxResults() == 0 ) {
		return Collections.EMPTY_LIST;
	}
	if ( lockOptions.getLockMode() != null && lockOptions.getLockMode() != LockMode.NONE ) {
		if ( !getProducer().isTransactionInProgress() ) {
			throw new TransactionRequiredException( "no transaction is in progress" );
		}
	}

	final String expandedQuery = getQueryParameterBindings().expandListValuedParameters( getQueryString(), getProducer() );
	return getProducer().list(
			expandedQuery,
			makeQueryParametersForExecution( expandedQuery )
	);
}
 
Example 6
SQLQueryImpl(
		final String sql,
        final String returnAliases[],
        final Class returnClasses[],
        final LockMode[] lockModes,
        final SessionImplementor session,
        final Collection querySpaces,
        final FlushMode flushMode,
        ParameterMetadata parameterMetadata) {
	// TODO : this constructor form is *only* used from constructor directly below us; can it go away?
	super( sql, flushMode, session, parameterMetadata );
	queryReturns = new ArrayList(returnAliases.length);
	for ( int i=0; i<returnAliases.length; i++ ) {
		NativeSQLQueryRootReturn ret = new NativeSQLQueryRootReturn(
				returnAliases[i],
				returnClasses[i].getName(),
				lockModes==null ? LockMode.NONE : lockModes[i]
		);
		queryReturns.add(ret);
	}
	this.querySpaces = querySpaces;
	this.callable = false;
}
 
Example 7
@Override
public void cascade(
		EventSource session,
		Object child,
		String entityName,
		Object anything,
		boolean isCascadeDeleteEnabled) {
	LOG.tracev( "Cascading to lock: {0}", entityName );
	LockMode lockMode = LockMode.NONE;
	LockOptions lr = new LockOptions();
	if ( anything instanceof LockOptions ) {
		LockOptions lockOptions = (LockOptions) anything;
		lr.setTimeOut( lockOptions.getTimeOut() );
		lr.setScope( lockOptions.getScope() );
		lr.setFollowOnLocking( lockOptions.getFollowOnLocking() );
		if ( lockOptions.getScope() ) {
			lockMode = lockOptions.getLockMode();
		}
	}
	lr.setLockMode( lockMode );
	session.buildLockRequest( lr ).lock( entityName, child );
}
 
Example 8
public CollectionElementLoader(
		QueryableCollection collectionPersister,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
	super( factory, loadQueryInfluencers );

	this.keyType = collectionPersister.getKeyType();
	this.indexType = collectionPersister.getIndexType();
	this.persister = (OuterJoinLoadable) collectionPersister.getElementPersister();
	this.entityName = persister.getEntityName();

	JoinWalker walker = new EntityJoinWalker(
			persister,
			ArrayHelper.join(
					collectionPersister.getKeyColumnNames(),
					collectionPersister.toColumns( "index" )
			),
			1,
			LockMode.NONE,
			factory,
			loadQueryInfluencers
	);
	initFromWalker( walker );

	postInstantiate();

	if ( LOG.isDebugEnabled() ) {
		LOG.debugf( "Static select for entity %s: %s", entityName, getSQLString() );
	}

}
 
Example 9
Source Project: lams   File: CustomLoader.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected String applyLocks(
		String sql,
		QueryParameters parameters,
		Dialect dialect,
		List<AfterLoadAction> afterLoadActions) throws QueryException {
	final LockOptions lockOptions = parameters.getLockOptions();
	if ( lockOptions == null ||
			( lockOptions.getLockMode() == LockMode.NONE && lockOptions.getAliasLockCount() == 0 ) ) {
		return sql;
	}

	// user is request locking, lets see if we can apply locking directly to the SQL...

	// 		some dialects wont allow locking with paging...
	afterLoadActions.add(
			new AfterLoadAction() {
				private final LockOptions originalLockOptions = lockOptions.makeCopy();

				@Override
				public void afterLoad(SharedSessionContractImplementor session, Object entity, Loadable persister) {
					( (Session) session ).buildLockRequest( originalLockOptions ).lock(
							persister.getEntityName(),
							entity
					);
				}
			}
	);
	parameters.getLockOptions().setLockMode( LockMode.READ );

	return sql;
}
 
Example 10
Source Project: lams   File: Loader.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected boolean shouldUseFollowOnLocking(
		QueryParameters parameters,
		Dialect dialect,
		List<AfterLoadAction> afterLoadActions) {
	if ( ( parameters.getLockOptions().getFollowOnLocking() == null && dialect.useFollowOnLocking( parameters ) ) ||
			( parameters.getLockOptions().getFollowOnLocking() != null && parameters.getLockOptions().getFollowOnLocking() ) ) {
		// currently only one lock mode is allowed in follow-on locking
		final LockMode lockMode = determineFollowOnLockMode( parameters.getLockOptions() );
		final LockOptions lockOptions = new LockOptions( lockMode );
		if ( lockOptions.getLockMode() != LockMode.UPGRADE_SKIPLOCKED ) {
			if ( lockOptions.getLockMode() != LockMode.NONE ) {
				LOG.usingFollowOnLocking();
			}
			lockOptions.setTimeOut( parameters.getLockOptions().getTimeOut() );
			lockOptions.setScope( parameters.getLockOptions().getScope() );
			afterLoadActions.add(
					new AfterLoadAction() {
						@Override
						public void afterLoad(SharedSessionContractImplementor session, Object entity, Loadable persister) {
							( (Session) session ).buildLockRequest( lockOptions ).lock(
									persister.getEntityName(),
									entity
							);
						}
					}
			);
			parameters.setLockOptions( new LockOptions() );
			return true;
		}
	}
	return false;
}
 
Example 11
Source Project: lams   File: Loader.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected LockMode determineFollowOnLockMode(LockOptions lockOptions) {
	final LockMode lockModeToUse = lockOptions.findGreatestLockMode();

	if ( lockOptions.hasAliasSpecificLockModes() ) {
		if ( lockOptions.getLockMode() == LockMode.NONE && lockModeToUse == LockMode.NONE ) {
			return lockModeToUse;
		}
		else {
			LOG.aliasSpecificLockingWithFollowOnLocking( lockModeToUse );
		}
	}
	return lockModeToUse;
}
 
Example 12
public CollectionLoader byKey() {
	// capture current values in a new instance of QueryBuildingParametersImpl
	final QueryBuildingParameters currentBuildingParameters = new QueryBuildingParametersImpl(
			influencers,
			batchSize,
			LockMode.NONE,
			null
	);
	return new CollectionLoader( collectionPersister, currentBuildingParameters ) ;
}
 
Example 13
Source Project: lams   File: QueryLoader.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param lockOptions a collection of lock modes specified dynamically via the Query interface
 */
@Override
protected LockMode[] getLockModes(LockOptions lockOptions) {
	if ( lockOptions == null ) {
		return defaultLockModes;
	}

	if ( lockOptions.getAliasLockCount() == 0
			&& ( lockOptions.getLockMode() == null || LockMode.NONE.equals( lockOptions.getLockMode() ) ) ) {
		return defaultLockModes;
	}

	// unfortunately this stuff can't be cached because
	// it is per-invocation, not constant for the
	// QueryTranslator instance

	LockMode[] lockModesArray = new LockMode[entityAliases.length];
	for ( int i = 0; i < entityAliases.length; i++ ) {
		LockMode lockMode = lockOptions.getEffectiveLockMode( entityAliases[i] );
		if ( lockMode == null ) {
			//NONE, because its the requested lock mode, not the actual!
			lockMode = LockMode.NONE;
		}
		lockModesArray[i] = lockMode;
	}

	return lockModesArray;
}
 
Example 14
private EntityLoader createUniqueKeyLoader(Type uniqueKeyType, String[] columns, Map enabledFilters) {
	if ( uniqueKeyType.isEntityType() ) {
		String className = ( ( EntityType ) uniqueKeyType ).getAssociatedEntityName();
		uniqueKeyType = getFactory().getEntityPersister( className ).getIdentifierType();
	}

	return new EntityLoader( this, columns, uniqueKeyType, 1, LockMode.NONE, getFactory(), enabledFilters );
}
 
Example 15
private void checkVersion(
		ResultSet resultSet,
		ResultSetProcessingContext context,
		EntityKey entityKey,
		Object existing) {
	final LockMode requestedLockMode = context.resolveLockMode( entityReference );
	if ( requestedLockMode != LockMode.NONE ) {
		final LockMode currentLockMode = context.getSession().getPersistenceContext().getEntry( existing ).getLockMode();
		final boolean isVersionCheckNeeded = entityReference.getEntityPersister().isVersioned()
				&& currentLockMode.lessThan( requestedLockMode );

		// we don't need to worry about existing version being uninitialized because this block isn't called
		// by a re-entrant load (re-entrant loads *always* have lock mode NONE)
		if ( isVersionCheckNeeded ) {
			//we only check the version when *upgrading* lock modes
			checkVersion(
					context.getSession(),
					resultSet,
					entityReference.getEntityPersister(),
					entityReferenceAliases.getColumnAliases(),
					entityKey,
					existing
			);
			//we need to upgrade the lock mode to the mode requested
			context.getSession().getPersistenceContext().getEntry( existing ).setLockMode( requestedLockMode );
		}
	}
}
 
Example 16
Source Project: lams   File: SessionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void applyQuerySettingsAndHints(Query query) {
	if ( lockOptions.getLockMode() != LockMode.NONE ) {
		query.setLockMode( getLockMode( lockOptions.getLockMode() ) );
	}
	Object queryTimeout;
	if ( (queryTimeout = getProperties().get( QueryHints.SPEC_HINT_TIMEOUT ) ) != null ) {
		query.setHint( QueryHints.SPEC_HINT_TIMEOUT, queryTimeout );
	}
	Object lockTimeout;
	if( (lockTimeout = getProperties().get( JPA_LOCK_TIMEOUT ))!=null){
		query.setHint( JPA_LOCK_TIMEOUT, lockTimeout );
	}
}
 
Example 17
/**
 * The entity instance is not in the session cache
 */
private Object instanceNotYetLoaded(
        final ResultSet rs,
        final int i,
        final Loadable persister,
        final String rowIdAlias,
        final EntityKey key,
        final LockMode lockMode,
        final EntityKey optionalObjectKey,
        final Object optionalObject,
        final List hydratedObjects,
        final SessionImplementor session) 
throws HibernateException, SQLException {

	final String instanceClass = getInstanceClass( 
			rs, 
			i, 
			persister, 
			key.getIdentifier(), 
			session 
		);

	final Object object;
	if ( optionalObjectKey != null && key.equals( optionalObjectKey ) ) {
		//its the given optional object
		object = optionalObject;
	}
	else {
		// instantiate a new instance
		object = session.instantiate( instanceClass, key.getIdentifier() );
	}

	//need to hydrate it.

	// grab its state from the ResultSet and keep it in the Session
	// (but don't yet initialize the object itself)
	// note that we acquire LockMode.READ even if it was not requested
	LockMode acquiredLockMode = lockMode == LockMode.NONE ? LockMode.READ : lockMode;
	loadFromResultSet( 
			rs, 
			i, 
			object, 
			instanceClass, 
			key, 
			rowIdAlias, 
			acquiredLockMode, 
			persister, 
			session 
		);

	//materialize associations (and initialize the object) later
	hydratedObjects.add( object );

	return object;
}
 
Example 18
Source Project: lams   File: QueryLoader.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
protected String applyLocks(
		String sql,
		QueryParameters parameters,
		Dialect dialect,
		List<AfterLoadAction> afterLoadActions) throws QueryException {
	// can't cache this stuff either (per-invocation)
	// we are given a map of user-alias -> lock mode
	// create a new map of sql-alias -> lock mode

	final LockOptions lockOptions = parameters.getLockOptions();

	if ( lockOptions == null ||
			( lockOptions.getLockMode() == LockMode.NONE && lockOptions.getAliasLockCount() == 0 ) ) {
		return sql;
	}


	// user is request locking, lets see if we can apply locking directly to the SQL...

	// 		some dialects wont allow locking with paging...
	if ( shouldUseFollowOnLocking( parameters, dialect, afterLoadActions ) ) {
		return sql;
	}

	//		there are other conditions we might want to add here, such as checking the result types etc
	//		but those are better served after we have redone the SQL generation to use ASTs.


	// we need both the set of locks and the columns to reference in locks
	// as the ultimate output of this section...
	final LockOptions locks = new LockOptions( lockOptions.getLockMode() );
	final Map<String, String[]> keyColumnNames = dialect.forUpdateOfColumns()
			? new HashMap<>()
			: null;

	locks.setScope( lockOptions.getScope() );
	locks.setTimeOut( lockOptions.getTimeOut() );

	for ( Map.Entry<String, String> entry : sqlAliasByEntityAlias.entrySet() ) {
		final String userAlias = entry.getKey();
		final String drivingSqlAlias = entry.getValue();
		if ( drivingSqlAlias == null ) {
			throw new IllegalArgumentException( "could not locate alias to apply lock mode : " + userAlias );
		}
		// at this point we have (drivingSqlAlias) the SQL alias of the driving table
		// corresponding to the given user alias.  However, the driving table is not
		// (necessarily) the table against which we want to apply locks.  Mainly,
		// the exception case here is joined-subclass hierarchies where we instead
		// want to apply the lock against the root table (for all other strategies,
		// it just happens that driving and root are the same).
		final QueryNode select = (QueryNode) queryTranslator.getSqlAST();
		final Lockable drivingPersister = (Lockable) select.getFromClause()
				.findFromElementByUserOrSqlAlias( userAlias, drivingSqlAlias )
				.getQueryable();
		final String sqlAlias = drivingPersister.getRootTableAlias( drivingSqlAlias );

		final LockMode effectiveLockMode = lockOptions.getEffectiveLockMode( userAlias );
		locks.setAliasSpecificLockMode( sqlAlias, effectiveLockMode );

		if ( keyColumnNames != null ) {
			keyColumnNames.put( sqlAlias, drivingPersister.getRootTableIdentifierColumnNames() );
		}
	}

	// apply the collected locks and columns
	return dialect.applyLocksToSql( sql, locks, keyColumnNames );
}
 
Example 19
/** 
 * Handle the given load event.
 *
 * @param event The load event to be handled.
 * @throws HibernateException
 */
public void onLoad(LoadEvent event, LoadEventListener.LoadType loadType) throws HibernateException {

	final SessionImplementor source = event.getSession();

	EntityPersister persister;
	if ( event.getInstanceToLoad() != null ) {
		persister = source.getEntityPersister( null, event.getInstanceToLoad() ); //the load() which takes an entity does not pass an entityName
		event.setEntityClassName( event.getInstanceToLoad().getClass().getName() );
	}
	else {
		persister = source.getFactory().getEntityPersister( event.getEntityClassName() );
	}

	if ( persister == null ) {
		throw new HibernateException( 
				"Unable to locate persister: " + 
				event.getEntityClassName() 
			);
	}

	if ( persister.getIdentifierType().isComponentType() && EntityMode.DOM4J == event.getSession().getEntityMode() ) {
		// skip this check for composite-ids relating to dom4j entity-mode;
		// alternatively, we could add a check to make sure the incoming id value is
		// an instance of Element...
	}
	else {
		Class idClass = persister.getIdentifierType().getReturnedClass();
		if ( idClass != null && ! idClass.isInstance( event.getEntityId() ) ) {
			throw new TypeMismatchException(
					"Provided id of the wrong type. Expected: " + idClass + ", got " + event.getEntityId().getClass()
			);
		}
	}

	EntityKey keyToLoad = new EntityKey( event.getEntityId(), persister, source.getEntityMode()  );

	try {
		if ( loadType.isNakedEntityReturned() ) {
			//do not return a proxy!
			//(this option indicates we are initializing a proxy)
			event.setResult( load(event, persister, keyToLoad, loadType) );
		}
		else {
			//return a proxy if appropriate
			if ( event.getLockMode() == LockMode.NONE ) {
				event.setResult( proxyOrLoad(event, persister, keyToLoad, loadType) );
			}
			else {
				event.setResult( lockAndLoad(event, persister, keyToLoad, loadType, source) );
			}
		}
	}
	catch(HibernateException e) {
		log.info("Error performing load command", e);
		throw e;
	}
}
 
Example 20
private LockMode getNullSafeLockMode(LockMode lockMode) {
	return lockMode == null ? LockMode.NONE : lockMode;
}