Java Code Examples for org.hibernate.engine.SessionImplementor#getFactory()

The following examples show how to use org.hibernate.engine.SessionImplementor#getFactory() . 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: CollectionType.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Get an iterator over the element set of the collection, which may not yet be wrapped
 *
 * @param collection The collection to be iterated
 * @param session The session from which the request is originating.
 * @return The iterator.
 */
public Iterator getElementsIterator(Object collection, SessionImplementor session) {
	if ( session.getEntityMode()==EntityMode.DOM4J ) {
		final SessionFactoryImplementor factory = session.getFactory();
		final CollectionPersister persister = factory.getCollectionPersister( getRole() );
		final Type elementType = persister.getElementType();
		
		List elements = ( (Element) collection ).elements( persister.getElementNodeName() );
		ArrayList results = new ArrayList();
		for ( int i=0; i<elements.size(); i++ ) {
			Element value = (Element) elements.get(i);
			results.add( elementType.fromXMLNode( value, factory ) );
		}
		return results.iterator();
	}
	else {
		return getElementsIterator(collection);
	}
}
 
Example 2
Source File: SubqueryExpression.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {
	
	final SessionImplementor session = ( (CriteriaImpl) criteria ).getSession(); //ugly!
	final SessionFactoryImplementor factory = session.getFactory();
	
	final OuterJoinLoadable persister = (OuterJoinLoadable) factory.getEntityPersister( criteriaImpl.getEntityOrClassName() );
	CriteriaQueryTranslator innerQuery = new CriteriaQueryTranslator( 
			factory, 
			criteriaImpl, 
			criteriaImpl.getEntityOrClassName(), //implicit polymorphism not supported (would need a union) 
			criteriaQuery.generateSQLAlias(),
			criteriaQuery
		);
	
	params = innerQuery.getQueryParameters(); //TODO: bad lifecycle....
	types = innerQuery.getProjectedTypes();
	
	//String filter = persister.filterFragment( innerQuery.getRootSQLALias(), session.getEnabledFilters() );
	
	String sql = new Select( factory.getDialect() )
		.setWhereClause( innerQuery.getWhereCondition() )
		.setGroupByClause( innerQuery.getGroupBy() )
		.setSelectClause( innerQuery.getSelect() )
		.setFromClause(
				persister.fromTableFragment( innerQuery.getRootSQLALias() ) +   
				persister.fromJoinFragment( innerQuery.getRootSQLALias(), true, false )
			)
		.toStatementString();
	
	final StringBuffer buf = new StringBuffer()
		.append( toLeftSqlString(criteria, criteriaQuery) );
	if (op!=null) buf.append(' ').append(op).append(' ');
	if (quantifier!=null) buf.append(quantifier).append(' ');
	return buf.append('(').append(sql).append(')')
		.toString();
}
 
Example 3
Source File: BasicCollectionPersister.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected CollectionInitializer createSubselectInitializer(SubselectFetch subselect, SessionImplementor session) {
	return new SubselectCollectionLoader( 
			this,
			subselect.toSubselectString( getCollectionType().getLHSPropertyName() ),
			subselect.getResult(),
			subselect.getQueryParameters(),
			subselect.getNamedParameterLocMap(),
			session.getFactory(),
			session.getEnabledFilters() 
		);
}
 
Example 4
Source File: OneToManyPersister.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected CollectionInitializer createSubselectInitializer(SubselectFetch subselect, SessionImplementor session) {
	return new SubselectOneToManyLoader( 
			this,
			subselect.toSubselectString( getCollectionType().getLHSPropertyName() ),
			subselect.getResult(),
			subselect.getQueryParameters(),
			subselect.getNamedParameterLocMap(),
			session.getFactory(),
			session.getEnabledFilters() 
		);
}
 
Example 5
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 6
Source File: BulkOperationCleanupAction.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** Create an action that will evict collection and entity regions based on queryspaces (table names).
 *  TODO: cache the autodetected information and pass it in instead.
 **/
public BulkOperationCleanupAction(SessionImplementor session, Set querySpaces) {
	this.session = session;

	Set tmpSpaces = new HashSet(querySpaces);
	SessionFactoryImplementor factory = session.getFactory();
	Iterator iterator = factory.getAllClassMetadata().entrySet().iterator();
	while ( iterator.hasNext() ) {
		Map.Entry entry = (Map.Entry) iterator.next();
		String entityName = (String) entry.getKey();
		EntityPersister persister = factory.getEntityPersister( entityName );
		Serializable[] entitySpaces = persister.getQuerySpaces();

		if (affectedEntity( querySpaces, entitySpaces )) {
			if ( persister.hasCache() ) {
				affectedEntityNames.add( persister.getEntityName() );
			}
			Set roles = session.getFactory().getCollectionRolesByEntityParticipant( persister.getEntityName() );
			if ( roles != null ) {
				affectedCollectionRoles.addAll( roles );
			}
			for ( int y = 0; y < entitySpaces.length; y++ ) {
				tmpSpaces.add( entitySpaces[y] );
			}
		}

	}
	this.spaces = (Serializable[]) tmpSpaces.toArray( new Serializable[tmpSpaces.size()] );		
}
 
Example 7
Source File: EntityType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Load an instance by a unique key that is not the primary key.
 *
 * @param entityName The name of the entity to load
 * @param uniqueKeyPropertyName The name of the property defining the uniqie key.
 * @param key The unique key property value.
 * @param session The originating session.
 * @return The loaded entity
 * @throws HibernateException generally indicates problems performing the load.
 */
public Object loadByUniqueKey(
		String entityName, 
		String uniqueKeyPropertyName, 
		Object key, 
		SessionImplementor session) throws HibernateException {
	final SessionFactoryImplementor factory = session.getFactory();
	UniqueKeyLoadable persister = ( UniqueKeyLoadable ) factory.getEntityPersister( entityName );

	//TODO: implement caching?! proxies?!

	EntityUniqueKey euk = new EntityUniqueKey(
			entityName, 
			uniqueKeyPropertyName, 
			key, 
			getIdentifierOrUniqueKeyType( factory ),
			session.getEntityMode(), 
			session.getFactory()
	);

	final PersistenceContext persistenceContext = session.getPersistenceContext();
	Object result = persistenceContext.getEntity( euk );
	if ( result == null ) {
		result = persister.loadByUniqueKey( uniqueKeyPropertyName, key, session );
	}
	return result == null ? null : persistenceContext.proxyFor( result );
}
 
Example 8
Source File: Loader.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Hydrate the state an object from the SQL <tt>ResultSet</tt>, into
 * an array or "hydrated" values (do not resolve associations yet),
 * and pass the hydrates state to the session.
 */
private void loadFromResultSet(
        final ResultSet rs,
        final int i,
        final Object object,
        final String instanceEntityName,
        final EntityKey key,
        final String rowIdAlias,
        final LockMode lockMode,
        final Loadable rootPersister,
        final SessionImplementor session) 
throws SQLException, HibernateException {

	final Serializable id = key.getIdentifier();

	// Get the persister for the _subclass_
	final Loadable persister = (Loadable) getFactory().getEntityPersister( instanceEntityName );

	if ( log.isTraceEnabled() ) {
		log.trace( 
				"Initializing object from ResultSet: " + 
				MessageHelper.infoString( persister, id, getFactory() ) 
			);
	}
	
	boolean eagerPropertyFetch = isEagerPropertyFetchEnabled(i);

	// add temp entry so that the next step is circular-reference
	// safe - only needed because some types don't take proper
	// advantage of two-phase-load (esp. components)
	TwoPhaseLoad.addUninitializedEntity( 
			key, 
			object, 
			persister, 
			lockMode, 
			!eagerPropertyFetch, 
			session 
		);

	//This is not very nice (and quite slow):
	final String[][] cols = persister == rootPersister ?
			getEntityAliases()[i].getSuffixedPropertyAliases() :
			getEntityAliases()[i].getSuffixedPropertyAliases(persister);

	final Object[] values = persister.hydrate( 
			rs, 
			id, 
			object, 
			rootPersister, 
			cols, 
			eagerPropertyFetch, 
			session 
		);

	final Object rowId = persister.hasRowId() ? rs.getObject(rowIdAlias) : null;

	final AssociationType[] ownerAssociationTypes = getOwnerAssociationTypes();
	if ( ownerAssociationTypes != null && ownerAssociationTypes[i] != null ) {
		String ukName = ownerAssociationTypes[i].getRHSUniqueKeyPropertyName();
		if (ukName!=null) {
			final int index = ( (UniqueKeyLoadable) persister ).getPropertyIndex(ukName);
			final Type type = persister.getPropertyTypes()[index];

			// polymorphism not really handled completely correctly,
			// perhaps...well, actually its ok, assuming that the
			// entity name used in the lookup is the same as the
			// the one used here, which it will be

			EntityUniqueKey euk = new EntityUniqueKey( 
					rootPersister.getEntityName(), //polymorphism comment above
					ukName,
					type.semiResolve( values[index], session, object ),
					type,
					session.getEntityMode(), session.getFactory()
				);
			session.getPersistenceContext().addEntity( euk, object );
		}
	}

	TwoPhaseLoad.postHydrate( 
			persister, 
			id, 
			values, 
			rowId, 
			object, 
			lockMode, 
			!eagerPropertyFetch, 
			session 
		);

}
 
Example 9
Source File: CollectionLoadContext.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Add the collection to the second-level cache
 *
 * @param lce The entry representing the collection to add
 * @param persister The persister
 */
private void addCollectionToCache(LoadingCollectionEntry lce, CollectionPersister persister) {
	final SessionImplementor session = getLoadContext().getPersistenceContext().getSession();
	final SessionFactoryImplementor factory = session.getFactory();

	if ( log.isDebugEnabled() ) {
		log.debug( "Caching collection: " + MessageHelper.collectionInfoString( persister, lce.getKey(), factory ) );
	}

	if ( !session.getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters( session ) ) {
		// some filters affecting the collection are enabled on the session, so do not do the put into the cache.
		log.debug( "Refusing to add to cache due to enabled filters" );
		// todo : add the notion of enabled filters to the CacheKey to differentiate filtered collections from non-filtered;
		//      but CacheKey is currently used for both collections and entities; would ideally need to define two seperate ones;
		//      currently this works in conjuction with the check on
		//      DefaultInitializeCollectionEventHandler.initializeCollectionFromCache() (which makes sure to not read from
		//      cache with enabled filters).
		return; // EARLY EXIT!!!!!
	}

	final Comparator versionComparator;
	final Object version;
	if ( persister.isVersioned() ) {
		versionComparator = persister.getOwnerEntityPersister().getVersionType().getComparator();
		final Object collectionOwner = getLoadContext().getPersistenceContext().getCollectionOwner( lce.getKey(), persister );
		version = getLoadContext().getPersistenceContext().getEntry( collectionOwner ).getVersion();
	}
	else {
		version = null;
		versionComparator = null;
	}

	CollectionCacheEntry entry = new CollectionCacheEntry( lce.getCollection(), persister );
	CacheKey cacheKey = new CacheKey(
			lce.getKey(),
			persister.getKeyType(),
			persister.getRole(),
			session.getEntityMode(),
			session.getFactory()
	);
	boolean put = persister.getCache().put(
			cacheKey,
			persister.getCacheEntryStructure().structure(entry),
			session.getTimestamp(),
			version,
			versionComparator,
			factory.getSettings().isMinimalPutsEnabled() && session.getCacheMode()!= CacheMode.REFRESH
	);

	if ( put && factory.getStatistics().isStatisticsEnabled() ) {
		factory.getStatisticsImplementor().secondLevelCachePut( persister.getCache().getRegionName() );
	}
}
 
Example 10
Source File: UpdateLockingStrategy.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * @see LockingStrategy#lock
 */
public void lock(
		Serializable id,
        Object version,
        Object object,
        SessionImplementor session) throws StaleObjectStateException, JDBCException {
	if ( !lockable.isVersioned() ) {
		throw new HibernateException( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" );
	}
	// todo : should we additionally check the current isolation mode explicitly?
	SessionFactoryImplementor factory = session.getFactory();
	try {
		PreparedStatement st = session.getBatcher().prepareSelectStatement( sql );
		try {
			lockable.getVersionType().nullSafeSet( st, version, 1, session );
			int offset = 2;

			lockable.getIdentifierType().nullSafeSet( st, id, offset, session );
			offset += lockable.getIdentifierType().getColumnSpan( factory );

			if ( lockable.isVersioned() ) {
				lockable.getVersionType().nullSafeSet( st, version, offset, session );
			}

			int affected = st.executeUpdate();
			if ( affected < 0 ) {
				factory.getStatisticsImplementor().optimisticFailure( lockable.getEntityName() );
				throw new StaleObjectStateException( lockable.getEntityName(), id );
			}

		}
		finally {
			session.getBatcher().closeStatement( st );
		}

	}
	catch ( SQLException sqle ) {
		throw JDBCExceptionHelper.convert(
				session.getFactory().getSQLExceptionConverter(),
		        sqle,
		        "could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ),
		        sql
		);
	}
}
 
Example 11
Source File: SelectLockingStrategy.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * @see LockingStrategy#lock
 */
public void lock(
        Serializable id,
        Object version,
        Object object,
        SessionImplementor session) throws StaleObjectStateException, JDBCException {

	SessionFactoryImplementor factory = session.getFactory();
	try {
		PreparedStatement st = session.getBatcher().prepareSelectStatement( sql );
		try {
			lockable.getIdentifierType().nullSafeSet( st, id, 1, session );
			if ( lockable.isVersioned() ) {
				lockable.getVersionType().nullSafeSet(
						st,
						version,
						lockable.getIdentifierType().getColumnSpan( factory ) + 1,
						session
				);
			}

			ResultSet rs = st.executeQuery();
			try {
				if ( !rs.next() ) {
					if ( factory.getStatistics().isStatisticsEnabled() ) {
						factory.getStatisticsImplementor()
								.optimisticFailure( lockable.getEntityName() );
					}
					throw new StaleObjectStateException( lockable.getEntityName(), id );
				}
			}
			finally {
				rs.close();
			}
		}
		finally {
			session.getBatcher().closeStatement( st );
		}

	}
	catch ( SQLException sqle ) {
		throw JDBCExceptionHelper.convert(
				session.getFactory().getSQLExceptionConverter(),
				sqle,
				"could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ),
				sql
			);
	}
}
 
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: DefaultInitializeCollectionEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Try to initialize a collection from the cache
 */
private boolean initializeCollectionFromCache(
		Serializable id,
		CollectionPersister persister,
		PersistentCollection collection,
		SessionImplementor source)
throws HibernateException {

	if ( !source.getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters( source ) ) {
		log.trace( "disregarding cached version (if any) of collection due to enabled filters ");
		return false;
	}

	final boolean useCache = persister.hasCache() && 
			source.getCacheMode().isGetEnabled();

	if ( !useCache ) {
		return false;
	}
	else {
		
		final SessionFactoryImplementor factory = source.getFactory();

		final CacheKey ck = new CacheKey( 
				id, 
				persister.getKeyType(), 
				persister.getRole(), 
				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) {
			return false;
		}
		else {

			CollectionCacheEntry cacheEntry = (CollectionCacheEntry) persister.getCacheEntryStructure()
					.destructure(ce, factory);
		
			final PersistenceContext persistenceContext = source.getPersistenceContext();
			cacheEntry.assemble(
					collection, 
					persister,  
					persistenceContext.getCollectionOwner(id, persister)
				);
			persistenceContext.getCollectionEntry(collection).postInitialize(collection);
			//addInitializedCollection(collection, persister, id);
			return true;
		}
		
	}
}
 
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: 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 16
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() );
		}

	}