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

The following examples show how to use org.hibernate.engine.spi.SharedSessionContractImplementor#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: DynamicBatchingEntityLoaderBuilder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void performOrderedBatchLoad(
		List<Serializable> idsInBatch,
		LockOptions lockOptions,
		OuterJoinLoadable persister,
		SharedSessionContractImplementor session) {
	final int batchSize =  idsInBatch.size();
	final DynamicEntityLoader batchingLoader = new DynamicEntityLoader(
			persister,
			batchSize,
			lockOptions,
			session.getFactory(),
			session.getLoadQueryInfluencers()
	);

	final Serializable[] idsInBatchArray = idsInBatch.toArray( new Serializable[ idsInBatch.size() ] );

	QueryParameters qp = buildMultiLoadQueryParameters( persister, idsInBatchArray, lockOptions );
	batchingLoader.doEntityBatchFetch( session, qp, idsInBatchArray );

	idsInBatch.clear();
}
 
Example 2
Source File: EntityInsertAction.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void doAfterTransactionCompletion(boolean success, SharedSessionContractImplementor session) throws HibernateException {
	final EntityPersister persister = getPersister();
	if ( success && isCachePutEnabled( persister, getSession() ) ) {
		final EntityDataAccess cache = persister.getCacheAccessStrategy();
		SessionFactoryImplementor factory = session.getFactory();
		final Object ck = cache.generateCacheKey( getId(), persister, factory, session.getTenantIdentifier() );
		final boolean put = cacheAfterInsert( cache, ck );

		if ( put && factory.getStatistics().isStatisticsEnabled() ) {
			factory.getStatistics().entityCachePut(
					StatsHelper.INSTANCE.getRootEntityRole( persister ),
					cache.getRegion().getName()
			);
		}
	}
	postCommitInsert( success );
}
 
Example 3
Source File: Helper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void createTempTable(
		IdTableInfoImpl idTableInfo,
		TempTableDdlTransactionHandling ddlTransactionHandling,
		SharedSessionContractImplementor session) {
	// Don't really know all the codes required to adequately decipher returned jdbc exceptions here.
	// simply allow the failure to be eaten and the subsequent insert-selects/deletes should fail
	TemporaryTableCreationWork work = new TemporaryTableCreationWork( idTableInfo, session.getFactory() );

	if ( ddlTransactionHandling == TempTableDdlTransactionHandling.NONE ) {
		final Connection connection = session.getJdbcCoordinator()
				.getLogicalConnection()
				.getPhysicalConnection();

		work.execute( connection );

		session.getJdbcCoordinator().afterStatementExecution();
	}
	else {
		session.getTransactionCoordinator()
				.createIsolationDelegate()
				.delegateWork( work, ddlTransactionHandling == TempTableDdlTransactionHandling.ISOLATE_AND_TRANSACT );
	}
}
 
Example 4
Source File: TimestampsCacheEnabledImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void preInvalidate(
		String[] spaces,
		SharedSessionContractImplementor session) {
	final SessionFactoryImplementor factory = session.getFactory();
	final RegionFactory regionFactory = factory.getCache().getRegionFactory();

	final boolean stats = factory.getStatistics().isStatisticsEnabled();

	final Long ts = regionFactory.nextTimestamp() + regionFactory.getTimeout();

	for ( Serializable space : spaces ) {
		if ( DEBUG_ENABLED ) {
			log.debugf( "Pre-invalidating space [%s], timestamp: %s", space, ts );
		}

		try {
			session.getEventListenerManager().cachePutStart();

			//put() has nowait semantics, is this really appropriate?
			//note that it needs to be async replication, never local or sync
			timestampsRegion.putIntoCache( space, ts, session );
		}
		finally {
			session.getEventListenerManager().cachePutEnd();
		}

		if ( stats ) {
			factory.getStatistics().updateTimestampsCachePut();
		}
	}
}
 
Example 5
Source File: EntityType.java    From lams with GNU General Public License v2.0 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,
		SharedSessionContractImplementor session) throws HibernateException {
	final SessionFactoryImplementor factory = session.getFactory();
	UniqueKeyLoadable persister = (UniqueKeyLoadable) factory.getMetamodel().entityPersister( entityName );

	//TODO: implement 2nd level caching?! natural id caching ?! proxies?!

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

	final PersistenceContext persistenceContext = session.getPersistenceContext();
	Object result = persistenceContext.getEntity( euk );
	if ( result == null ) {
		result = persister.loadByUniqueKey( uniqueKeyPropertyName, key, session );
		
		// If the entity was not in the Persistence Context, but was found now,
		// add it to the Persistence Context
		if (result != null) {
			persistenceContext.addEntity(euk, result);
		}
	}

	return result == null ? null : persistenceContext.proxyFor( result );
}
 
Example 6
Source File: BulkOperationCleanupAction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs an action to cleanup "affected cache regions" based on a
 * set of affected table spaces.  This differs from {@link #BulkOperationCleanupAction(SharedSessionContractImplementor, Queryable[])}
 * in that here we have the affected <strong>table names</strong>.  From those
 * we deduce the entity persisters which are affected based on the defined
 * {@link EntityPersister#getQuerySpaces() table spaces}; and from there, we
 * determine the affected collection regions based on any collections
 * in which those entity persisters participate as elements/keys/etc.
 *
 * @param session The session to which this request is tied.
 * @param tableSpaces The table spaces.
 */
@SuppressWarnings({ "unchecked" })
public BulkOperationCleanupAction(SharedSessionContractImplementor session, Set tableSpaces) {
	final LinkedHashSet<String> spacesList = new LinkedHashSet<>();
	spacesList.addAll( tableSpaces );

	final SessionFactoryImplementor factory = session.getFactory();
	for ( EntityPersister persister : factory.getMetamodel().entityPersisters().values() ) {
		final String[] entitySpaces = (String[]) persister.getQuerySpaces();
		if ( affectedEntity( tableSpaces, entitySpaces ) ) {
			spacesList.addAll( Arrays.asList( entitySpaces ) );

			if ( persister.canWriteToCache() ) {
				entityCleanups.add( new EntityCleanup( persister.getCacheAccessStrategy(), session ) );
			}
			if ( persister.hasNaturalIdentifier() && persister.hasNaturalIdCache() ) {
				naturalIdCleanups.add( new NaturalIdCleanup( persister.getNaturalIdCacheAccessStrategy(), session ) );
			}

			final Set<String> roles = session.getFactory().getMetamodel().getCollectionRolesByEntityParticipant( persister.getEntityName() );
			if ( roles != null ) {
				for ( String role : roles ) {
					final CollectionPersister collectionPersister = factory.getMetamodel().collectionPersister( role );
					if ( collectionPersister.hasCache() ) {
						collectionCleanups.add(
								new CollectionCleanup( collectionPersister.getCacheAccessStrategy(), session )
						);
					}
				}
			}
		}
	}

	this.affectedTableSpaces = spacesList.toArray( new String[ spacesList.size() ] );
}
 
Example 7
Source File: BulkOperationCleanupAction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs an action to cleanup "affected cache regions" based on the
 * affected entity persisters.  The affected regions are defined as the
 * region (if any) of the entity persisters themselves, plus the
 * collection regions for any collection in which those entity
 * persisters participate as elements/keys/etc.
 *
 * @param session The session to which this request is tied.
 * @param affectedQueryables The affected entity persisters.
 */
public BulkOperationCleanupAction(SharedSessionContractImplementor session, Queryable... affectedQueryables) {
	final SessionFactoryImplementor factory = session.getFactory();
	final LinkedHashSet<String> spacesList = new LinkedHashSet<>();
	for ( Queryable persister : affectedQueryables ) {
		spacesList.addAll( Arrays.asList( (String[]) persister.getQuerySpaces() ) );

		if ( persister.canWriteToCache() ) {
			final EntityDataAccess entityDataAccess = persister.getCacheAccessStrategy();
			if ( entityDataAccess != null ) {
				entityCleanups.add( new EntityCleanup( entityDataAccess, session ) );
			}
		}

		if ( persister.hasNaturalIdentifier() && persister.hasNaturalIdCache() ) {
			naturalIdCleanups.add(
					new NaturalIdCleanup( persister.getNaturalIdCacheAccessStrategy(), session )
			);
		}

		final Set<String> roles = factory.getMetamodel().getCollectionRolesByEntityParticipant( persister.getEntityName() );
		if ( roles != null ) {
			for ( String role : roles ) {
				final CollectionPersister collectionPersister = factory.getMetamodel().collectionPersister( role );
				if ( collectionPersister.hasCache() ) {
					collectionCleanups.add(
							new CollectionCleanup(
									collectionPersister.getCacheAccessStrategy(),
									session
							)
					);
				}
			}
		}
	}

	this.affectedTableSpaces = spacesList.toArray( new String[ spacesList.size() ] );
}
 
Example 8
Source File: OutputsImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public CustomLoaderExtension(
		CustomQuery customQuery,
		QueryParameters queryParameters,
		SharedSessionContractImplementor session) {
	super( customQuery, session.getFactory() );
	this.queryParameters = queryParameters;
	this.session = session;

	entityAliases = interpretEntityAliases( customQuery.getCustomQueryReturns() );
}
 
Example 9
Source File: NaturalIdCacheKey.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a new key for a caching natural identifier resolutions into the second level cache.
 * @param naturalIdValues The naturalIdValues associated with the cached data
 * @param propertyTypes
 * @param naturalIdPropertyIndexes
 * @param session The originating session
 */
public NaturalIdCacheKey(
		final Object[] naturalIdValues,
		Type[] propertyTypes, int[] naturalIdPropertyIndexes, final String entityName,
		final SharedSessionContractImplementor session) {

	this.entityName = entityName;
	this.tenantId = session.getTenantIdentifier();

	this.naturalIdValues = new Serializable[naturalIdValues.length];

	final SessionFactoryImplementor factory = session.getFactory();

	final int prime = 31;
	int result = 1;
	result = prime * result + ( ( this.entityName == null ) ? 0 : this.entityName.hashCode() );
	result = prime * result + ( ( this.tenantId == null ) ? 0 : this.tenantId.hashCode() );
	for ( int i = 0; i < naturalIdValues.length; i++ ) {
		final int naturalIdPropertyIndex = naturalIdPropertyIndexes[i];
		final Type type = propertyTypes[naturalIdPropertyIndex];
		final Object value = naturalIdValues[i];

		result = prime * result + (value != null ? type.getHashCode( value, factory ) : 0);

		// The natural id may not be fully resolved in some situations.  See HHH-7513 for one of them
		// (re-attaching a mutable natural id uses a database snapshot and hydration does not resolve associations).
		// TODO: The snapshot should probably be revisited at some point.  Consider semi-resolving, hydrating, etc.
		if (type instanceof EntityType && type.getSemiResolvedType( factory ).getReturnedClass().isInstance( value )) {
			this.naturalIdValues[i] = (Serializable) value;
		}
		else {
			this.naturalIdValues[i] = type.disassemble( value, session, null );
		}
	}

	this.hashCode = result;
	initTransients();
}
 
Example 10
Source File: JdbcSessionContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public JdbcSessionContextImpl(SharedSessionContractImplementor session, StatementInspector statementInspector) {
	this.sessionFactory = session.getFactory();
	this.statementInspector = statementInspector;
	this.connectionHandlingMode = settings().getPhysicalConnectionHandlingMode();
	this.serviceRegistry = sessionFactory.getServiceRegistry();
	this.jdbcObserver = new JdbcObserverImpl( session );

	if ( this.statementInspector == null ) {
		throw new IllegalArgumentException( "StatementInspector cannot be null" );
	}
}
 
Example 11
Source File: OneToManyPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected CollectionInitializer createSubselectInitializer(SubselectFetch subselect, SharedSessionContractImplementor session) {
	return new SubselectOneToManyLoader(
			this,
			subselect.toSubselectString( getCollectionType().getLHSPropertyName() ),
			subselect.getResult(),
			subselect.getQueryParameters(),
			subselect.getNamedParameterLocMap(),
			session.getFactory(),
			session.getLoadQueryInfluencers()
	);
}
 
Example 12
Source File: BasicCollectionPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected CollectionInitializer createSubselectInitializer(SubselectFetch subselect, SharedSessionContractImplementor session) {
	return new SubselectCollectionLoader(
			this,
			subselect.toSubselectString( getCollectionType().getLHSPropertyName() ),
			subselect.getResult(),
			subselect.getQueryParameters(),
			subselect.getNamedParameterLocMap(),
			session.getFactory(),
			session.getLoadQueryInfluencers()
	);
}
 
Example 13
Source File: ReactiveOneToManyPersister.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected ReactiveCollectionInitializer createSubselectInitializer(SubselectFetch subselect, SharedSessionContractImplementor session) {
	return new ReactiveSubselectOneToManyLoader(
			this,
			subselect.toSubselectString( getCollectionType().getLHSPropertyName() ),
			subselect.getResult(),
			subselect.getQueryParameters(),
			subselect.getNamedParameterLocMap(),
			session.getFactory(),
			session.getLoadQueryInfluencers()
	);
}
 
Example 14
Source File: SelectLockingStrategy.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void lock(
		Serializable id,
		Object version,
		Object object,
		int timeout,
		SharedSessionContractImplementor session) throws StaleObjectStateException, JDBCException {
	final String sql = determineSql( timeout );
	final SessionFactoryImplementor factory = session.getFactory();
	try {
		final PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( sql );
		try {
			getLockable().getIdentifierType().nullSafeSet( st, id, 1, session );
			if ( getLockable().isVersioned() ) {
				getLockable().getVersionType().nullSafeSet(
						st,
						version,
						getLockable().getIdentifierType().getColumnSpan( factory ) + 1,
						session
				);
			}

			final ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract( st );
			try {
				if ( !rs.next() ) {
					if ( factory.getStatistics().isStatisticsEnabled() ) {
						factory.getStatistics().optimisticFailure( getLockable().getEntityName() );
					}
					throw new StaleObjectStateException( getLockable().getEntityName(), id );
				}
			}
			finally {
				session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( rs, st );
			}
		}
		finally {
			session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st );
			session.getJdbcCoordinator().afterStatementExecution();
		}

	}
	catch ( SQLException sqle ) {
		throw session.getJdbcServices().getSqlExceptionHelper().convert(
				sqle,
				"could not lock: " + MessageHelper.infoString( getLockable(), id, session.getFactory() ),
				sql
			);
	}
}
 
Example 15
Source File: ReactiveAbstractEntityPersister.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Perform an SQL INSERT, and then retrieve a generated identifier.
 * <p>
 * This form is used for PostInsertIdentifierGenerator-style ids (IDENTITY,
 * select, etc).
 */
default CompletionStage<Serializable> insertReactive(
		Object[] fields,
		boolean[] notNull,
		String sql,
		Object object,
		SharedSessionContractImplementor session) throws HibernateException {

	if ( log.isTraceEnabled() ) {
		log.tracev( "Inserting entity: {0}", infoString(delegate()) );
		if ( delegate().isVersioned() ) {
			log.tracev( "Version: {0}", Versioning.getVersion( fields, delegate()) );
		}
	}

	Object[] params = PreparedStatementAdaptor.bind( insert -> {
		boolean[][] insertable = delegate().getPropertyColumnInsertable();
		delegate().dehydrate( null, fields, notNull, insertable, 0, insert, session, false );
	} );

	SessionFactoryImplementor factory = session.getFactory();
	Dialect dialect = factory.getJdbcServices().getDialect();
	String identifierColumnName = delegate().getIdentifierColumnNames()[0];
	ReactiveConnection connection = getReactiveConnection(session);
	if ( factory.getSessionFactoryOptions().isGetGeneratedKeysEnabled() ) {
		//TODO: wooooo this is awful ... I believe the problem is fixed in Hibernate 6
		if ( dialect instanceof PostgreSQL81Dialect) {
			sql = sql + " returning " + identifierColumnName;
		}
		return connection.updateReturning( sql, params ).thenApply( id -> id );
	}
	else {
		//use an extra round trip to fetch the id
		String selectIdSql = dialect.getIdentityColumnSupport()
				.getIdentitySelectString(
						delegate().getTableName(),
						identifierColumnName,
						Types.INTEGER
				);
		return connection.update( sql, params )
				.thenCompose( v -> connection.selectLong( selectIdSql, new Object[0] ) )
				.thenApply( id -> id );
	}

}
 
Example 16
Source File: UpdateLockingStrategy.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void lock(
		Serializable id,
		Object version,
		Object object,
		int timeout,
		SharedSessionContractImplementor 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?
	final SessionFactoryImplementor factory = session.getFactory();
	try {
		final PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( 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 );
			}

			final int affected = session.getJdbcCoordinator().getResultSetReturn().executeUpdate( st );
			if ( affected < 0 ) {
				if (factory.getStatistics().isStatisticsEnabled()) {
					factory.getStatistics().optimisticFailure( lockable.getEntityName() );
				}
				throw new StaleObjectStateException( lockable.getEntityName(), id );
			}

		}
		finally {
			session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st );
			session.getJdbcCoordinator().afterStatementExecution();
		}

	}
	catch ( SQLException sqle ) {
		throw session.getJdbcServices().getSqlExceptionHelper().convert(
				sqle,
				"could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ),
				sql
		);
	}
}
 
Example 17
Source File: CollectionLoadContext.java    From lams with GNU General Public License v2.0 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 SharedSessionContractImplementor session = getLoadContext().getPersistenceContext().getSession();
	final SessionFactoryImplementor factory = session.getFactory();

	final boolean debugEnabled = LOG.isDebugEnabled();
	if ( debugEnabled ) {
		LOG.debugf( "Caching collection: %s", MessageHelper.collectionInfoString( persister, lce.getCollection(), lce.getKey(), session ) );
	}

	if ( !session.getLoadQueryInfluencers().getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters( session ) ) {
		// some filters affecting the collection are enabled on the session, so do not do the put into the cache.
		if ( debugEnabled ) {
			LOG.debug( "Refusing to add to cache due to enabled filters" );
		}
		// todo : add the notion of enabled filters to the cache key to differentiate filtered collections from non-filtered;
		//      DefaultInitializeCollectionEventHandler.initializeCollectionFromCache() (which makes sure to not read from
		//      cache with enabled filters).
		// EARLY EXIT!!!!!
		return;
	}

	final Object version;
	if ( persister.isVersioned() ) {
		Object collectionOwner = getLoadContext().getPersistenceContext().getCollectionOwner( lce.getKey(), persister );
		if ( collectionOwner == null ) {
			// generally speaking this would be caused by the collection key being defined by a property-ref, thus
			// the collection key and the owner key would not match up.  In this case, try to use the key of the
			// owner instance associated with the collection itself, if one.  If the collection does already know
			// about its owner, that owner should be the same instance as associated with the PC, but we do the
			// resolution against the PC anyway just to be safe since the lookup should not be costly.
			if ( lce.getCollection() != null ) {
				final Object linkedOwner = lce.getCollection().getOwner();
				if ( linkedOwner != null ) {
					final Serializable ownerKey = persister.getOwnerEntityPersister().getIdentifier( linkedOwner, session );
					collectionOwner = getLoadContext().getPersistenceContext().getCollectionOwner( ownerKey, persister );
				}
			}
			if ( collectionOwner == null ) {
				throw new HibernateException(
						"Unable to resolve owner of loading collection [" +
								MessageHelper.collectionInfoString( persister, lce.getCollection(), lce.getKey(), session ) +
								"] for second level caching"
				);
			}
		}
		version = getLoadContext().getPersistenceContext().getEntry( collectionOwner ).getVersion();
	}
	else {
		version = null;
	}

	final CollectionCacheEntry entry = new CollectionCacheEntry( lce.getCollection(), persister );
	final CollectionDataAccess cacheAccess = persister.getCacheAccessStrategy();
	final Object cacheKey = cacheAccess.generateCacheKey(
			lce.getKey(),
			persister,
			session.getFactory(),
			session.getTenantIdentifier()
	);

	boolean isPutFromLoad = true;
	if ( persister.getElementType().isAssociationType() ) {
		for ( Serializable id : entry.getState() ) {
			EntityPersister entityPersister = ( (QueryableCollection) persister ).getElementPersister();
			if ( session.getPersistenceContext().wasInsertedDuringTransaction( entityPersister, id ) ) {
				isPutFromLoad = false;
				break;
			}
		}
	}

	// CollectionRegionAccessStrategy has no update, so avoid putting uncommitted data via putFromLoad
	if (isPutFromLoad) {
		try {
			session.getEventListenerManager().cachePutStart();
			final boolean put = cacheAccess.putFromLoad(
					session,
					cacheKey,
					persister.getCacheEntryStructure().structure( entry ),
					version,
					factory.getSessionFactoryOptions().isMinimalPutsEnabled() && session.getCacheMode()!= CacheMode.REFRESH
			);

			if ( put && factory.getStatistics().isStatisticsEnabled() ) {
				factory.getStatistics().collectionCachePut(
						persister.getNavigableRole(),
						persister.getCacheAccessStrategy().getRegion().getName()
				);
			}
		}
		finally {
			session.getEventListenerManager().cachePutEnd();
		}
	}
}
 
Example 18
Source File: Helper.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected void releaseTempTable(
		IdTableInfoImpl idTableInfo,
		AfterUseAction afterUseAction,
		TempTableDdlTransactionHandling ddlTransactionHandling,
		SharedSessionContractImplementor session) {
	if ( afterUseAction == AfterUseAction.NONE ) {
		return;
	}

	if ( afterUseAction == AfterUseAction.DROP ) {
		TemporaryTableDropWork work = new TemporaryTableDropWork( idTableInfo, session.getFactory() );
		if ( ddlTransactionHandling == TempTableDdlTransactionHandling.NONE ) {
			final Connection connection = session.getJdbcCoordinator()
					.getLogicalConnection()
					.getPhysicalConnection();

			work.execute( connection );

			session.getJdbcCoordinator().afterStatementExecution();
		}
		else {
			session.getTransactionCoordinator()
					.createIsolationDelegate()
					.delegateWork( work, ddlTransactionHandling == TempTableDdlTransactionHandling.ISOLATE_AND_TRANSACT );
		}
	}

	if ( afterUseAction == AfterUseAction.CLEAN ) {
		PreparedStatement ps = null;
		try {
			final String sql = "delete from " + idTableInfo.getQualifiedIdTableName();
			ps = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( sql, false );
			session.getJdbcCoordinator().getResultSetReturn().executeUpdate( ps );
		}
		catch( Throwable t ) {
			log.unableToCleanupTemporaryIdTable(t);
		}
		finally {
			if ( ps != null ) {
				try {
					session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( ps );
				}
				catch( Throwable ignore ) {
					// ignore
				}
			}
		}
	}
}
 
Example 19
Source File: EntityInsertAction.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void execute() throws HibernateException {
	nullifyTransientReferencesIfNotAlready();

	final EntityPersister persister = getPersister();
	final SharedSessionContractImplementor session = getSession();
	final Object instance = getInstance();
	final Serializable id = getId();

	final 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, getState(), instance, session );
		PersistenceContext persistenceContext = session.getPersistenceContext();
		final EntityEntry entry = persistenceContext.getEntry( instance );
		if ( entry == null ) {
			throw new AssertionFailure( "possible non-threadsafe access to session" );
		}
		
		entry.postInsert( getState() );

		if ( persister.hasInsertGeneratedProperties() ) {
			persister.processInsertGeneratedProperties( id, instance, getState(), session );
			if ( persister.isVersionPropertyGenerated() ) {
				version = Versioning.getVersion( getState(), persister );
			}
			entry.postUpdate( instance, getState(), version );
		}

		persistenceContext.registerInsertedKey( persister, getId() );
	}

	final SessionFactoryImplementor factory = session.getFactory();

	if ( isCachePutEnabled( persister, session ) ) {
		final CacheEntry ce = persister.buildCacheEntry(
				instance,
				getState(),
				version,
				session
		);
		cacheEntry = persister.getCacheEntryStructure().structure( ce );
		final EntityDataAccess cache = persister.getCacheAccessStrategy();
		final Object ck = cache.generateCacheKey( id, persister, factory, session.getTenantIdentifier() );

		final boolean put = cacheInsert( persister, ck );

		if ( put && factory.getStatistics().isStatisticsEnabled() ) {
			factory.getStatistics().entityCachePut(
					StatsHelper.INSTANCE.getRootEntityRole( persister ),
					cache.getRegion().getName()
			);
		}
	}

	handleNaturalIdPostSaveNotifications( id );

	postInsert();

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

	markExecuted();
}
 
Example 20
Source File: Loader.java    From lams with GNU General Public License v2.0 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 SharedSessionContractImplementor 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.tracef(
				"Initializing object from ResultSet: %s",
				MessageHelper.infoString(
						persister,
						id,
						getFactory()
				)
		);
	}

	boolean fetchAllPropertiesRequested = 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,
			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,
			fetchAllPropertiesRequested,
			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,
					persister.getEntityMode(),
					session.getFactory()
			);
			session.getPersistenceContext().addEntity( euk, object );
		}
	}

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

}