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

The following examples show how to use org.hibernate.persister.entity.EntityPersister#getIdentifierType() . 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: EntityUpdateAction.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void afterTransactionCompletion(boolean success) throws CacheException {
	EntityPersister persister = getPersister();
	if ( persister.hasCache() ) {
		
		final CacheKey ck = new CacheKey( 
				getId(), 
				persister.getIdentifierType(), 
				persister.getRootEntityName(), 
				getSession().getEntityMode(), 
				getSession().getFactory() 
			);
		
		if ( success && cacheEntry!=null /*!persister.isCacheInvalidationRequired()*/ ) {
			boolean put = persister.getCache().afterUpdate(ck, cacheEntry, nextVersion, lock );
			
			if ( put && getSession().getFactory().getStatistics().isStatisticsEnabled() ) {
				getSession().getFactory().getStatisticsImplementor()
						.secondLevelCachePut( getPersister().getCache().getRegionName() );
			}
		}
		else {
			persister.getCache().release(ck, lock );
		}
	}
	postCommitUpdate();
}
 
Example 2
Source File: EntityInsertAction.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void afterTransactionCompletion(boolean success) throws HibernateException {
	EntityPersister persister = getPersister();
	if ( success && isCachePutEnabled( persister, getSession() ) ) {
		final CacheKey ck = new CacheKey( 
				getId(), 
				persister.getIdentifierType(), 
				persister.getRootEntityName(), 
				getSession().getEntityMode(), 
				getSession().getFactory() 
			);
		boolean put = persister.getCache().afterInsert(ck, cacheEntry, version );
		
		if ( put && getSession().getFactory().getStatistics().isStatisticsEnabled() ) {
			getSession().getFactory().getStatisticsImplementor()
					.secondLevelCachePut( getPersister().getCache().getRegionName() );
		}
	}
	postCommitInsert();
}
 
Example 3
Source File: AbstractPersistentCollection.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Removes entity entries that have an equal identifier with the incoming entity instance
 *
 * @param list The list containing the entity instances
 * @param entityInstance The entity instance to match elements.
 * @param entityName The entity name
 * @param session The session
 */
public static void identityRemove(
		Collection list,
		Object entityInstance,
		String entityName,
		SharedSessionContractImplementor session) {

	if ( entityInstance != null && ForeignKeys.isNotTransient( entityName, entityInstance, null, session ) ) {
		final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName );
		final Type idType = entityPersister.getIdentifierType();

		final Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, entityInstance, session );
		final Iterator itr = list.iterator();
		while ( itr.hasNext() ) {
			final Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, itr.next(), session );
			if ( idType.isEqual( idOfCurrent, idOfOld, session.getFactory() ) ) {
				itr.remove();
				break;
			}
		}

	}
}
 
Example 4
Source File: MessageHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generate an info message string relating to a particular entity.
 *
 * @param persister The persister for the entity
 * @param id The entity id value
 * @param factory The session factory - Could be null!
 * @return An info string, in the form [FooBar#1]
 */
public static String infoString(
		EntityPersister persister,
		Object id, 
		SessionFactoryImplementor factory) {
	StringBuilder s = new StringBuilder();
	s.append( '[' );
	Type idType;
	if( persister == null ) {
		s.append( "<null EntityPersister>" );
		idType = null;
	}
	else {
		s.append( persister.getEntityName() );
		idType = persister.getIdentifierType();
	}
	s.append( '#' );

	if ( id == null ) {
		s.append( "<null>" );
	}
	else {
		if ( idType == null ) {
			s.append( id );
		}
		else {
			if ( factory != null ) {
				s.append( idType.toLoggableString( id, factory ) );
			}
			else {
				s.append( "<not loggable>" );
			}
		}
	}
	s.append( ']' );

	return s.toString();

}
 
Example 5
Source File: SessionFactoryImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void evict(Class persistentClass, Serializable id) throws HibernateException {
	EntityPersister p = getEntityPersister( persistentClass.getName() );
	if ( p.hasCache() ) {
		if ( log.isDebugEnabled() ) {
			log.debug( "evicting second-level cache: " + MessageHelper.infoString(p, id, this) );
		}
		CacheKey cacheKey = new CacheKey( id, p.getIdentifierType(), p.getRootEntityName(), EntityMode.POJO, this );
		p.getCache().remove( cacheKey );
	}
}
 
Example 6
Source File: SessionFactoryImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void evictEntity(String entityName, Serializable id) throws HibernateException {
	EntityPersister p = getEntityPersister(entityName);
	if ( p.hasCache() ) {
		if ( log.isDebugEnabled() ) {
			log.debug( "evicting second-level cache: " + MessageHelper.infoString(p, id, this) );
		}
		CacheKey cacheKey = new CacheKey( id, p.getIdentifierType(), p.getRootEntityName(), EntityMode.POJO, this );
		p.getCache().remove( cacheKey );
	}
}
 
Example 7
Source File: DefaultLoadEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** 
 * If the class to be loaded has been configured with a cache, then lock
 * given id in that cache and then perform the load.
 *
 * @return The loaded entity
 * @throws HibernateException
 */
protected Object lockAndLoad(
	final LoadEvent event, 
	final EntityPersister persister,
	final EntityKey keyToLoad, 
	final LoadEventListener.LoadType options,
	final SessionImplementor source) 
throws HibernateException {
	
	CacheConcurrencyStrategy.SoftLock lock = null;
	final CacheKey ck;
	if ( persister.hasCache() ) {
		ck = new CacheKey( 
				event.getEntityId(), 
				persister.getIdentifierType(), 
				persister.getRootEntityName(), 
				source.getEntityMode(), 
				source.getFactory() 
			);
		lock = persister.getCache().lock(ck, null );
	}
	else {
		ck = null;
	}

	Object entity;
	try {
		entity = load(event, persister, keyToLoad, options);
	}
	finally {
		if ( persister.hasCache() ) {
			persister.getCache().release(ck, lock );
		}
	}

	Object proxy = event.getSession().getPersistenceContext()
			.proxyFor( persister, keyToLoad, entity );
	
	return proxy;
}
 
Example 8
Source File: EntityKey.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Construct a unique identifier for an entity class instance
 */
public EntityKey(Serializable id, EntityPersister persister, EntityMode entityMode) {
	if ( id == null ) {
		throw new AssertionFailure( "null identifier" );
	}
	this.identifier = id; 
	this.entityMode = entityMode;
	this.rootEntityName = persister.getRootEntityName();
	this.entityName = persister.getEntityName();
	this.identifierType = persister.getIdentifierType();
	this.isBatchLoadable = persister.isBatchLoadable();
	this.factory = persister.getFactory();
	hashCode = generateHashCode(); //cache the hashcode
}
 
Example 9
Source File: ReadWriteCacheConcurrencyStrategyWithLockTimeoutTest.java    From hibernate-master-class with Apache License 2.0 5 votes vote down vote up
private CacheKey cacheKey(Serializable identifier, EntityPersister p) {
    return new CacheKey(
            identifier,
            p.getIdentifierType(),
            p.getRootEntityName(),
            null,
            (SessionFactoryImplementor) getSessionFactory()
    );
}
 
Example 10
Source File: MessageHelper.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Generate an info message string relating to a particular entity.
 *
 * @param persister The persister for the entity
 * @param id The entity id value
 * @param factory The session factory
 * @return An info string, in the form [FooBar#1]
 */
public static String infoString(
		EntityPersister persister, 
		Object id, 
		SessionFactoryImplementor factory) {
	StringBuffer s = new StringBuffer();
	s.append( '[' );
	Type idType;
	if( persister == null ) {
		s.append( "<null EntityPersister>" );
		idType = null;
	}
	else {
		s.append( persister.getEntityName() );
		idType = persister.getIdentifierType();
	}
	s.append( '#' );

	if ( id == null ) {
		s.append( "<null>" );
	}
	else {
		if ( idType == null ) {
			s.append( id );
		}
		else {
			s.append( idType.toLoggableString( id, factory ) );
		}
	}
	s.append( ']' );

	return s.toString();

}
 
Example 11
Source File: AbstractReactiveSaveEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Serializable assignIdIfNecessary(Object generatedId, Object entity, String entityName, EventSource source) {
	EntityPersister persister = source.getEntityPersister(entityName, entity);
	if ( generatedId != null ) {
		if (generatedId instanceof Long) {
			Long longId = (Long) generatedId;
			Type identifierType = persister.getIdentifierType();
			if (identifierType == LongType.INSTANCE) {
				return longId;
			}
			else if (identifierType == IntegerType.INSTANCE) {
				return longId.intValue();
			}
			else {
				throw new HibernateException("cannot generate identifiers of type "
						+ identifierType.getReturnedClass().getSimpleName() + " for: " + entityName);
			}
		}
		else {
			return (Serializable) generatedId;
		}
	}
	else {
		Serializable assignedId = persister.getIdentifier( entity, source.getSession() );
		if (assignedId == null) {
			throw new IdentifierGenerationException("ids for this class must be manually assigned before calling save(): " + entityName);
		}
		return assignedId;
	}
}
 
Example 12
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 13
Source File: BatchingEntityLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public BatchingEntityLoader(EntityPersister persister, int[] batchSizes, Loader[] loaders) {
	this.batchSizes = batchSizes;
	this.loaders = loaders;
	this.persister = persister;
	idType = persister.getIdentifierType();
}
 
Example 14
Source File: DefaultLoadEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Attempts to load the entity from the second-level cache.
 *
 * @param event The load event
 * @param persister The persister for the entity being requested for load
 * @param options The load options.
 * @return The entity from the second-level cache, or null.
 * @throws HibernateException
 */
protected Object loadFromSecondLevelCache(
		final LoadEvent event,
		final EntityPersister persister,
		final LoadEventListener.LoadType options) throws HibernateException {
	
	final SessionImplementor source = event.getSession();
	
	final boolean useCache = persister.hasCache() && 
		source.getCacheMode().isGetEnabled() && 
		event.getLockMode().lessThan(LockMode.READ);
	
	if (useCache) {
		
		final SessionFactoryImplementor factory = source.getFactory();
		
		final CacheKey ck = new CacheKey( 
				event.getEntityId(), 
				persister.getIdentifierType(), 
				persister.getRootEntityName(),
				source.getEntityMode(), 
				source.getFactory()
			);
		Object ce = persister.getCache()
			.get( ck, source.getTimestamp() );
		
		if ( factory.getStatistics().isStatisticsEnabled() ) {
			if (ce==null) {
				factory.getStatisticsImplementor().secondLevelCacheMiss( 
					persister.getCache().getRegionName() 
				);
			}
			else {
				factory.getStatisticsImplementor().secondLevelCacheHit( 
					persister.getCache().getRegionName() 
				);
			}
		}

		if ( ce != null ) {

			CacheEntry entry = (CacheEntry) persister.getCacheEntryStructure()
					.destructure(ce, factory);
		
			// Entity was found in second-level cache...
			return assembleCacheEntry(
					entry,
					event.getEntityId(),
					persister,
					event
				);
		}
	}
	
	return null;
}
 
Example 15
Source File: AbstractPersistentCollection.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Given a collection of entity instances that used to
 * belong to the collection, and a collection of instances
 * that currently belong, return a collection of orphans
 */
@SuppressWarnings({"JavaDoc", "unchecked"})
protected static Collection getOrphans(
		Collection oldElements,
		Collection currentElements,
		String entityName,
		SharedSessionContractImplementor session) throws HibernateException {

	// short-circuit(s)
	if ( currentElements.size() == 0 ) {
		// no new elements, the old list contains only Orphans
		return oldElements;
	}
	if ( oldElements.size() == 0 ) {
		// no old elements, so no Orphans neither
		return oldElements;
	}

	final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName );
	final Type idType = entityPersister.getIdentifierType();
	final boolean useIdDirect = mayUseIdDirect( idType );

	// create the collection holding the Orphans
	final Collection res = new ArrayList();

	// collect EntityIdentifier(s) of the *current* elements - add them into a HashSet for fast access
	final java.util.Set currentIds = new HashSet();
	final java.util.Set currentSaving = new IdentitySet();
	for ( Object current : currentElements ) {
		if ( current != null && ForeignKeys.isNotTransient( entityName, current, null, session ) ) {
			final EntityEntry ee = session.getPersistenceContext().getEntry( current );
			if ( ee != null && ee.getStatus() == Status.SAVING ) {
				currentSaving.add( current );
			}
			else {
				final Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved(
						entityName,
						current,
						session
				);
				currentIds.add( useIdDirect ? currentId : new TypedValue( idType, currentId ) );
			}
		}
	}

	// iterate over the *old* list
	for ( Object old : oldElements ) {
		if ( !currentSaving.contains( old ) ) {
			final Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, old, session );
			if ( !currentIds.contains( useIdDirect ? oldId : new TypedValue( idType, oldId ) ) ) {
				res.add( old );
			}
		}
	}

	return res;
}
 
Example 16
Source File: StatelessSessionImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void refresh(String entityName, Object entity, LockMode lockMode) {
		final EntityPersister persister = this.getEntityPersister( entityName, entity );
		final Serializable id = persister.getIdentifier( entity, getEntityMode() );
		if ( log.isTraceEnabled() ) {
			log.trace(
					"refreshing transient " +
					MessageHelper.infoString( persister, id, this.getFactory() )
			);
		}
		// TODO : can this ever happen???
//		EntityKey key = new EntityKey( id, persister, source.getEntityMode() );
//		if ( source.getPersistenceContext().getEntry( key ) != null ) {
//			throw new PersistentObjectException(
//					"attempted to refresh transient instance when persistent " +
//					"instance was already associated with the Session: " +
//					MessageHelper.infoString( persister, id, source.getFactory() )
//			);
//		}

		if ( persister.hasCache() ) {
			final CacheKey ck = new CacheKey(
					id,
			        persister.getIdentifierType(),
			        persister.getRootEntityName(),
			        this.getEntityMode(),
			        this.getFactory()
			);
			persister.getCache().remove(ck);
		}

		String previousFetchProfile = this.getFetchProfile();
		Object result = null;
		try {
			this.setFetchProfile( "refresh" );
			result = persister.load( id, entity, lockMode, this );
		}
		finally {
			this.setFetchProfile( previousFetchProfile );
		}
		UnresolvableObjectException.throwIfNull( result, id, persister.getEntityName() );
	}
 
Example 17
Source File: EntityDeleteAction.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void execute() throws HibernateException {
	Serializable id = getId();
	EntityPersister persister = getPersister();
	SessionImplementor session = getSession();
	Object instance = getInstance();

	boolean veto = preDelete();

	Object version = this.version;
	if ( persister.isVersionPropertyGenerated() ) {
		// we need to grab the version value from the entity, otherwise
		// we have issues with generated-version entities that may have
		// multiple actions queued during the same flush
		version = persister.getVersion( instance, session.getEntityMode() );
	}

	final CacheKey ck;
	if ( persister.hasCache() ) {
		ck = new CacheKey( 
				id, 
				persister.getIdentifierType(), 
				persister.getRootEntityName(), 
				session.getEntityMode(), 
				session.getFactory() 
			);
		lock = persister.getCache().lock(ck, version);
	}
	else {
		ck = null;
	}

	if ( !isCascadeDeleteEnabled && !veto ) {
		persister.delete( id, version, instance, session );
	}
	
	//postDelete:
	// After actually deleting a row, record the fact that the instance no longer 
	// exists on the database (needed for identity-column key generation), and
	// remove it from the session cache
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	EntityEntry entry = persistenceContext.removeEntry( instance );
	if ( entry == null ) {
		throw new AssertionFailure( "possible nonthreadsafe access to session" );
	}
	entry.postDelete();

	EntityKey key = new EntityKey( entry.getId(), entry.getPersister(), session.getEntityMode() );
	persistenceContext.removeEntity(key);
	persistenceContext.removeProxy(key);
	
	if ( persister.hasCache() ) persister.getCache().evict(ck);

	postDelete();

	if ( getSession().getFactory().getStatistics().isStatisticsEnabled() && !veto ) {
		getSession().getFactory().getStatisticsImplementor()
				.deleteEntity( getPersister().getEntityName() );
	}
}
 
Example 18
Source File: EntityInsertAction.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void execute() throws HibernateException {
		EntityPersister persister = getPersister();
		SessionImplementor session = getSession();
		Object instance = getInstance();
		Serializable id = getId();

		boolean veto = preInsert();

		// Don't need to lock the cache here, since if someone
		// else inserted the same pk first, the insert would fail

		if ( !veto ) {
			
			persister.insert( id, state, instance, session );
		
			EntityEntry entry = session.getPersistenceContext().getEntry( instance );
			if ( entry == null ) {
				throw new AssertionFailure( "possible nonthreadsafe access to session" );
			}
			
			entry.postInsert();
	
			if ( persister.hasInsertGeneratedProperties() ) {
				persister.processInsertGeneratedProperties( id, instance, state, session );
				if ( persister.isVersionPropertyGenerated() ) {
					version = Versioning.getVersion(state, persister);
				}
				entry.postUpdate(instance, state, version);
			}
			
		}

		final SessionFactoryImplementor factory = getSession().getFactory();

		if ( isCachePutEnabled( persister, session ) ) {
			
			CacheEntry ce = new CacheEntry(
					state,
					persister, 
					persister.hasUninitializedLazyProperties( instance, session.getEntityMode() ),
					version,
					session,
					instance
				);
			
			cacheEntry = persister.getCacheEntryStructure().structure(ce);
			final CacheKey ck = new CacheKey( 
					id, 
					persister.getIdentifierType(), 
					persister.getRootEntityName(), 
					session.getEntityMode(), 
					session.getFactory() 
				);
//			boolean put = persister.getCache().insert(ck, cacheEntry);
			boolean put = persister.getCache().insert( ck, cacheEntry, version );
			
			if ( put && factory.getStatistics().isStatisticsEnabled() ) {
				factory.getStatisticsImplementor()
						.secondLevelCachePut( getPersister().getCache().getRegionName() );
			}
			
		}

		postInsert();

		if ( factory.getStatistics().isStatisticsEnabled() && !veto ) {
			factory.getStatisticsImplementor()
					.insertEntity( getPersister().getEntityName() );
		}

	}
 
Example 19
Source File: DefaultCacheKeysFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public static Object staticCreateEntityKey(Object id, EntityPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) {
	return new CacheKeyImplementation( id, persister.getIdentifierType(), persister.getRootEntityName(), tenantIdentifier, factory );
}
 
Example 20
Source File: BatchingEntityLoader.java    From webdsl with Apache License 2.0 4 votes vote down vote up
public BatchingEntityLoader(EntityPersister persister, int[] batchSizes, Loader[] loaders) {
	this.batchSizes = batchSizes;
	this.loaders = loaders;
	this.persister = persister;
	idType = persister.getIdentifierType();
}