Java Code Examples for org.hibernate.persister.entity.EntityPersister#isVersioned()

The following examples show how to use org.hibernate.persister.entity.EntityPersister#isVersioned() . 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
Source File: AbstractReactiveSaveEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Perform any property value substitution that is necessary
 * (interceptor callback, version initialization...)
 *
 * @param entity The entity
 * @param id The entity identifier
 * @param values The snapshot entity state
 * @param persister The entity persister
 * @param source The originating session
 *
 * @return True if the snapshot state changed such that
 *         reinjection of the values into the entity is required.
 */
protected boolean substituteValuesIfNecessary(
		Object entity,
		Serializable id,
		Object[] values,
		EntityPersister persister,
		SessionImplementor source) {
	boolean substitute = source.getInterceptor().onSave(
			entity,
			id,
			values,
			persister.getPropertyNames(),
			persister.getPropertyTypes()
	);

	//keep the existing version number in the case of replicate!
	if ( persister.isVersioned() ) {
		substitute = Versioning.seedVersion(
				values,
				persister.getVersionProperty(),
				persister.getVersionType(),
				source
		) || substitute;
	}
	return substitute;
}
 
Example 2
Source File: StatelessSessionImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void update(String entityName, Object entity) {
	errorIfClosed();
	EntityPersister persister = getEntityPersister(entityName, entity);
	Serializable id = persister.getIdentifier(entity, EntityMode.POJO);
	Object[] state = persister.getPropertyValues(entity, EntityMode.POJO);
	Object oldVersion;
	if ( persister.isVersioned() ) {
		oldVersion = persister.getVersion(entity, EntityMode.POJO);
		Object newVersion = Versioning.increment( oldVersion, persister.getVersionType(), this );
		Versioning.setVersion(state, newVersion, persister);
		persister.setPropertyValues(entity, state, EntityMode.POJO);
	}
	else {
		oldVersion = null;
	}
	persister.update(id, state, null, false, null, oldVersion, entity, null, this);
}
 
Example 3
Source File: StatelessSessionImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Serializable insert(String entityName, Object entity) {
	checkOpen();
	EntityPersister persister = getEntityPersister( entityName, entity );
	Serializable id = persister.getIdentifierGenerator().generate( this, entity );
	Object[] state = persister.getPropertyValues( entity );
	if ( persister.isVersioned() ) {
		boolean substitute = Versioning.seedVersion(
				state,
				persister.getVersionProperty(),
				persister.getVersionType(),
				this
		);
		if ( substitute ) {
			persister.setPropertyValues( entity, state );
		}
	}
	if ( id == IdentifierGeneratorHelper.POST_INSERT_INDICATOR ) {
		id = persister.insert( state, entity, this );
	}
	else {
		persister.insert( id, state, entity, this );
	}
	persister.setIdentifier( entity, id, this );
	return id;
}
 
Example 4
Source File: StatelessSessionImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Serializable insert(String entityName, Object entity) {
	errorIfClosed();
	EntityPersister persister = getEntityPersister(entityName, entity);
	Serializable id = persister.getIdentifierGenerator().generate(this, entity);
	Object[] state = persister.getPropertyValues(entity, EntityMode.POJO);
	if ( persister.isVersioned() ) {
		boolean substitute = Versioning.seedVersion(state, persister.getVersionProperty(), persister.getVersionType(), this);
		if ( substitute ) {
			persister.setPropertyValues( entity, state, EntityMode.POJO );
		}
	}
	if ( id == IdentifierGeneratorFactory.POST_INSERT_INDICATOR ) {
		id = persister.insert(state, entity, this);
	}
	else {
		persister.insert(id, state, entity, this);
	}
	persister.setIdentifier(entity, id, EntityMode.POJO);
	return id;
}
 
Example 5
Source File: AbstractSaveEventListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Perform any property value substitution that is necessary
 * (interceptor callback, version initialization...)
 *
 * @param entity The entity
 * @param id The entity identifier
 * @param values The snapshot entity state
 * @param persister The entity persister
 * @param source The originating session
 *
 * @return True if the snapshot state changed such that
 *         reinjection of the values into the entity is required.
 */
protected boolean substituteValuesIfNecessary(
		Object entity,
		Serializable id,
		Object[] values,
		EntityPersister persister,
		SessionImplementor source) {
	boolean substitute = source.getInterceptor().onSave(
			entity,
			id,
			values,
			persister.getPropertyNames(),
			persister.getPropertyTypes()
	);

	//keep the existing version number in the case of replicate!
	if ( persister.isVersioned() ) {
		substitute = Versioning.seedVersion(
				values,
				persister.getVersionProperty(),
				persister.getVersionType(),
				source
		) || substitute;
	}
	return substitute;
}
 
Example 6
Source File: DefaultMergeEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean isVersionChanged(Object entity, EventSource source, EntityPersister persister, Object target) {
	if ( ! persister.isVersioned() ) {
		return false;
	}
	// for merging of versioned entities, we consider the version having
	// been changed only when:
	// 1) the two version values are different;
	//      *AND*
	// 2) The target actually represents database state!
	//
	// This second condition is a special case which allows
	// an entity to be merged during the same transaction
	// (though during a seperate operation) in which it was
	// originally persisted/saved
	boolean changed = ! persister.getVersionType().isSame(
			persister.getVersion( target, source.getEntityMode() ),
			persister.getVersion( entity, source.getEntityMode() ),
			source.getEntityMode()
	);

	// TODO : perhaps we should additionally require that the incoming entity
	// version be equivalent to the defined unsaved-value?
	return changed && existsInDatabase( target, source, persister );
}
 
Example 7
Source File: DefaultReactiveFlushEntityEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Convenience method to retrieve an entities next version value
 */
private Object getNextVersion(FlushEntityEvent event) throws HibernateException {

	EntityEntry entry = event.getEntityEntry();
	EntityPersister persister = entry.getPersister();
	if ( persister.isVersioned() ) {

		Object[] values = event.getPropertyValues();

		if ( entry.isBeingReplicated() ) {
			return Versioning.getVersion( values, persister );
		}
		else {
			int[] dirtyProperties = event.getDirtyProperties();

			final boolean isVersionIncrementRequired = isVersionIncrementRequired(
					event,
					entry,
					persister,
					dirtyProperties
			);

			final Object nextVersion = isVersionIncrementRequired ?
					Versioning.increment( entry.getVersion(), persister.getVersionType(), event.getSession() ) :
					entry.getVersion(); //use the current version

			Versioning.setVersion( values, nextVersion, persister );

			return nextVersion;
		}
	}
	else {
		return null;
	}

}
 
Example 8
Source File: DefaultFlushEntityEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Convience method to retreive an entities next version value
 */
private Object getNextVersion(FlushEntityEvent event) throws HibernateException {
	
	EntityEntry entry = event.getEntityEntry();
	EntityPersister persister = entry.getPersister();
	if ( persister.isVersioned() ) {

		Object[] values = event.getPropertyValues();
	    
		if ( entry.isBeingReplicated() ) {
			return Versioning.getVersion(values, persister);
		}
		else {
			int[] dirtyProperties = event.getDirtyProperties();
			
			final boolean isVersionIncrementRequired = isVersionIncrementRequired( 
					event, 
					entry, 
					persister, 
					dirtyProperties 
				);
			
			final Object nextVersion = isVersionIncrementRequired ?
					Versioning.increment( entry.getVersion(), persister.getVersionType(), event.getSession() ) :
					entry.getVersion(); //use the current version
					
			Versioning.setVersion(values, nextVersion, persister);
			
			return nextVersion;
		}
	}
	else {
		return null;
	}
	
}
 
Example 9
Source File: TwoPhaseLoad.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Register the "hydrated" state of an entity instance, after the first step of 2-phase loading.
 *
 * Add the "hydrated state" (an array) of an uninitialized entity to the session. We don't try
 * to resolve any associations yet, because there might be other entities waiting to be
 * read from the JDBC result set we are currently processing
 *
 * @param persister The persister for the hydrated entity
 * @param id The entity identifier
 * @param values The entity values
 * @param rowId The rowId for the entity
 * @param object An optional instance for the entity being loaded
 * @param lockMode The lock mode
 * @param session The Session
 */
public static void postHydrate(
		final EntityPersister persister,
		final Serializable id,
		final Object[] values,
		final Object rowId,
		final Object object,
		final LockMode lockMode,
		final SharedSessionContractImplementor session) {
	final Object version = Versioning.getVersion( values, persister );
	session.getPersistenceContext().addEntry(
			object,
			Status.LOADING,
			values,
			rowId,
			id,
			version,
			lockMode,
			true,
			persister,
			false
		);

	if ( version != null && LOG.isTraceEnabled() ) {
		final String versionStr = persister.isVersioned()
				? persister.getVersionType().toLoggableString( version, session.getFactory() )
				: "null";
		LOG.tracef( "Version: %s", versionStr );
	}
}
 
Example 10
Source File: TwoPhaseLoad.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Register the "hydrated" state of an entity instance, after the first step of 2-phase loading.
 * 
 * Add the "hydrated state" (an array) of an uninitialized entity to the session. We don't try
 * to resolve any associations yet, because there might be other entities waiting to be
 * read from the JDBC result set we are currently processing
 */
public static void postHydrate(
	final EntityPersister persister, 
	final Serializable id, 
	final Object[] values, 
	final Object rowId,
	final Object object, 
	final LockMode lockMode,
	final boolean lazyPropertiesAreUnfetched, 
	final SessionImplementor session) 
throws HibernateException {
	
	Object version = Versioning.getVersion(values, persister);
	session.getPersistenceContext().addEntry( 
			object, 
			Status.LOADING,
			values, 
			rowId, 
			id, 
			version, 
			lockMode, 
			true, 
			persister, 
			false, 
			lazyPropertiesAreUnfetched 
		);

	if ( log.isTraceEnabled() && version!=null ) {
		String versionStr = persister.isVersioned()
				? persister.getVersionType().toLoggableString( version, session.getFactory() )
		        : "null";
		log.trace( "Version: " + versionStr );
	}

}
 
Example 11
Source File: DefaultFlushEntityEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Convenience method to retrieve an entities next version value
 */
private Object getNextVersion(FlushEntityEvent event) throws HibernateException {

	EntityEntry entry = event.getEntityEntry();
	EntityPersister persister = entry.getPersister();
	if ( persister.isVersioned() ) {

		Object[] values = event.getPropertyValues();

		if ( entry.isBeingReplicated() ) {
			return Versioning.getVersion( values, persister );
		}
		else {
			int[] dirtyProperties = event.getDirtyProperties();

			final boolean isVersionIncrementRequired = isVersionIncrementRequired(
					event,
					entry,
					persister,
					dirtyProperties
			);

			final Object nextVersion = isVersionIncrementRequired ?
					Versioning.increment( entry.getVersion(), persister.getVersionType(), event.getSession() ) :
					entry.getVersion(); //use the current version

			Versioning.setVersion( values, nextVersion, persister );

			return nextVersion;
		}
	}
	else {
		return null;
	}

}
 
Example 12
Source File: DefaultFlushEntityEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private boolean isCollectionDirtyCheckNecessary(EntityPersister persister, Status status) {
	return status==Status.MANAGED && 
			persister.isVersioned() && 
			persister.hasCollections();
}
 
Example 13
Source File: AbstractLockUpgradeEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Performs a pessimistic lock upgrade on a given entity, if needed.
 *
 * @param object The entity for which to upgrade the lock.
 * @param entry The entity's EntityEntry instance.
 * @param requestedLockMode The lock mode being requested for locking.
 * @param source The session which is the source of the event being processed.
 * @throws HibernateException
 */
protected void upgradeLock(Object object, EntityEntry entry, LockMode requestedLockMode, SessionImplementor source)
throws HibernateException {

	if ( requestedLockMode.greaterThan( entry.getLockMode() ) ) {
		// The user requested a "greater" (i.e. more restrictive) form of
		// pessimistic lock

		if ( entry.getStatus() != Status.MANAGED ) {
			throw new ObjectDeletedException(
					"attempted to lock a deleted instance",
					entry.getId(),
					entry.getPersister().getEntityName()
			);
		}

		final EntityPersister persister = entry.getPersister();

		if ( log.isTraceEnabled() )
			log.trace(
					"locking " +
					MessageHelper.infoString( persister, entry.getId(), source.getFactory() ) +
					" in mode: " +
					requestedLockMode
			);

		final CacheConcurrencyStrategy.SoftLock lock;
		final CacheKey ck;
		if ( persister.hasCache() ) {
			ck = new CacheKey( 
					entry.getId(), 
					persister.getIdentifierType(), 
					persister.getRootEntityName(), 
					source.getEntityMode(), 
					source.getFactory() 
			);
			lock = persister.getCache().lock( ck, entry.getVersion() );
		}
		else {
			ck = null;
			lock = null;
		}
		
		try {
			if ( persister.isVersioned() && requestedLockMode == LockMode.FORCE ) {
				// todo : should we check the current isolation mode explicitly?
				Object nextVersion = persister.forceVersionIncrement(
						entry.getId(), entry.getVersion(), source
				);
				entry.forceLocked( object, nextVersion );
			}
			else {
				persister.lock( entry.getId(), entry.getVersion(), object, requestedLockMode, source );
			}
			entry.setLockMode(requestedLockMode);
		}
		finally {
			// the database now holds a lock + the object is flushed from the cache,
			// so release the soft lock
			if ( persister.hasCache() ) {
				persister.getCache().release(ck, lock );
			}
		}

	}
}
 
Example 14
Source File: DefaultFlushEntityEventListener.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private boolean isCollectionDirtyCheckNecessary(EntityPersister persister, Status status) {
	return ( status == Status.MANAGED || status == Status.READ_ONLY ) &&
			persister.isVersioned() &&
			persister.hasCollections();
}
 
Example 15
Source File: AbstractLockUpgradeEventListener.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Performs a pessimistic lock upgrade on a given entity, if needed.
 *
 * @param object The entity for which to upgrade the lock.
 * @param entry The entity's EntityEntry instance.
 * @param lockOptions contains the requested lock mode.
 * @param source The session which is the source of the event being processed.
 */
protected void upgradeLock(Object object, EntityEntry entry, LockOptions lockOptions, EventSource source) {

	LockMode requestedLockMode = lockOptions.getLockMode();
	if ( requestedLockMode.greaterThan( entry.getLockMode() ) ) {
		// The user requested a "greater" (i.e. more restrictive) form of
		// pessimistic lock

		if ( entry.getStatus() != Status.MANAGED ) {
			throw new ObjectDeletedException(
					"attempted to lock a deleted instance",
					entry.getId(),
					entry.getPersister().getEntityName()
			);
		}

		final EntityPersister persister = entry.getPersister();

		if ( log.isTraceEnabled() ) {
			log.tracev(
					"Locking {0} in mode: {1}",
					MessageHelper.infoString( persister, entry.getId(), source.getFactory() ),
					requestedLockMode
			);
		}

		final boolean cachingEnabled = persister.canWriteToCache();
		SoftLock lock = null;
		Object ck = null;
		try {
			if ( cachingEnabled ) {
				EntityDataAccess cache = persister.getCacheAccessStrategy();
				ck = cache.generateCacheKey( entry.getId(), persister, source.getFactory(), source.getTenantIdentifier() );
				lock = cache.lockItem( source, ck, entry.getVersion() );
			}

			if ( persister.isVersioned() && requestedLockMode == LockMode.FORCE  ) {
				// todo : should we check the current isolation mode explicitly?
				Object nextVersion = persister.forceVersionIncrement(
						entry.getId(), entry.getVersion(), source
				);
				entry.forceLocked( object, nextVersion );
			}
			else {
				persister.lock( entry.getId(), entry.getVersion(), object, lockOptions, source );
			}
			entry.setLockMode(requestedLockMode);
		}
		finally {
			// the database now holds a lock + the object is flushed from the cache,
			// so release the soft lock
			if ( cachingEnabled ) {
				persister.getCacheAccessStrategy().unlockItem( source, ck, lock );
			}
		}

	}
}
 
Example 16
Source File: DefaultReplicateEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Handle the given replicate event.
 *
 * @param event The replicate event to be handled.
 *
 * @throws TransientObjectException An invalid attempt to replicate a transient entity.
 */
public void onReplicate(ReplicateEvent event) {
	final EventSource source = event.getSession();
	if ( source.getPersistenceContext().reassociateIfUninitializedProxy( event.getObject() ) ) {
		log.trace( "uninitialized proxy passed to replicate()" );
		return;
	}

	Object entity = source.getPersistenceContext().unproxyAndReassociate( event.getObject() );

	if ( source.getPersistenceContext().isEntryFor( entity ) ) {
		log.trace( "ignoring persistent instance passed to replicate()" );
		//hum ... should we cascade anyway? throw an exception? fine like it is?
		return;
	}

	EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity );

	// get the id from the object
	/*if ( persister.isUnsaved(entity, source) ) {
		throw new TransientObjectException("transient instance passed to replicate()");
	}*/
	Serializable id = persister.getIdentifier( entity, source.getEntityMode() );
	if ( id == null ) {
		throw new TransientObjectException( "instance with null id passed to replicate()" );
	}

	final ReplicationMode replicationMode = event.getReplicationMode();

	final Object oldVersion;
	if ( replicationMode == ReplicationMode.EXCEPTION ) {
		//always do an INSERT, and let it fail by constraint violation
		oldVersion = null;
	}
	else {
		//what is the version on the database?
		oldVersion = persister.getCurrentVersion( id, source );			
	}

	if ( oldVersion != null ) { 			
		if ( log.isTraceEnabled() ) {
			log.trace(
					"found existing row for " +
							MessageHelper.infoString( persister, id, source.getFactory() )
			);
		}

		/// HHH-2378
		final Object realOldVersion = persister.isVersioned() ? oldVersion : null;
		
		boolean canReplicate = replicationMode.shouldOverwriteCurrentVersion(
				entity,
				realOldVersion,
				persister.getVersion( entity, source.getEntityMode() ),
				persister.getVersionType()
		);

		if ( canReplicate ) {
			//will result in a SQL UPDATE:
			performReplication( entity, id, realOldVersion, persister, replicationMode, source );
		}
		else {
			//else do nothing (don't even reassociate object!)
			log.trace( "no need to replicate" );
		}

		//TODO: would it be better to do a refresh from db?
	}
	else {
		// no existing row - do an insert
		if ( log.isTraceEnabled() ) {
			log.trace(
					"no existing row, replicating new instance " +
							MessageHelper.infoString( persister, id, source.getFactory() )
			);
		}

		final boolean regenerate = persister.isIdentifierAssignedByInsert(); // prefer re-generation of identity!
		final EntityKey key = regenerate ?
				null : new EntityKey( id, persister, source.getEntityMode() );

		performSaveOrReplicate(
				entity,
				key,
				persister,
				regenerate,
				replicationMode,
				source,
				true
		);

	}
}
 
Example 17
Source File: DefaultReactiveFlushEntityEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
private boolean isCollectionDirtyCheckNecessary(EntityPersister persister, Status status) {
	return ( status == Status.MANAGED || status == Status.READ_ONLY ) &&
			persister.isVersioned() &&
			persister.hasCollections();
}
 
Example 18
Source File: Versioning.java    From cacheonix-core with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Inject the optimisitc locking value into the entity state snapshot.
 *
 * @param fields The state snapshot
 * @param version The optimisitc locking value
 * @param persister The entity persister
 */
public static void setVersion(Object[] fields, Object version, EntityPersister persister) {
	if ( !persister.isVersioned() ) {
		return;
	}
	fields[ persister.getVersionProperty() ] = version;
}
 
Example 19
Source File: Versioning.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Extract the optimistic locking value out of the entity state snapshot.
 *
 * @param fields The state snapshot
 * @param persister The entity persister
 * @return The extracted optimistic locking value
 */
public static Object getVersion(Object[] fields, EntityPersister persister) {
	if ( !persister.isVersioned() ) {
		return null;
	}
	return fields[ persister.getVersionProperty() ];
}
 
Example 20
Source File: Versioning.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Inject the optimistic locking value into the entity state snapshot.
 *
 * @param fields The state snapshot
 * @param version The optimistic locking value
 * @param persister The entity persister
 */
public static void setVersion(Object[] fields, Object version, EntityPersister persister) {
	if ( !persister.isVersioned() ) {
		return;
	}
	fields[ persister.getVersionProperty() ] = version;
}