org.hibernate.engine.spi.SharedSessionContractImplementor Java Examples

The following examples show how to use org.hibernate.engine.spi.SharedSessionContractImplementor. 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: PersistentEnumUserType.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Override
public Object nullSafeGet(ResultSet rs, String[] names,
        SharedSessionContractImplementor session, Object owner)
    throws HibernateException, SQLException
{
    String name = rs.getString(names[0]);
    if (rs.wasNull()) {
        return null;
    }
    for (PersistentEnum value : returnedClass().getEnumConstants()) {
        if (name.equals(value.getId())) {
            return value;
        }
    }
    throw new IllegalStateException(
            "Unknown " + returnedClass().getSimpleName() + " value [" + name + "]");
}
 
Example #2
Source File: Dialect.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public NClob mergeNClob(NClob original, NClob target, SharedSessionContractImplementor session) {
	if ( original != target ) {
		try {
			// the NCLOB just read during the load phase of merge
			final OutputStream connectedStream = target.setAsciiStream( 1L );
			// the NCLOB from the detached state
			final InputStream detachedStream = original.getAsciiStream();
			StreamCopier.copy( detachedStream, connectedStream );
			return target;
		}
		catch (SQLException e ) {
			throw session.getFactory().getSQLExceptionHelper().convert( e, "unable to merge NCLOB data" );
		}
	}
	else {
		return NEW_LOCATOR_LOB_MERGE_STRATEGY.mergeNClob( original, target, session );
	}
}
 
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: AbstractPersistentCollection.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public final boolean setCurrentSession(SharedSessionContractImplementor session) throws HibernateException {
	if ( session == this.session ) {
		return false;
	}
	else {
		if ( this.session != null ) {
			final String msg = generateUnexpectedSessionStateMessage( session );
			if ( isConnectedToSession() ) {
				throw new HibernateException(
						"Illegal attempt to associate a collection with two open sessions. " + msg
				);
			}
			else {
				LOG.logUnexpectedSessionInCollectionNotConnected( msg );
				this.session = session;
				return true;
			}
		}
		else {
			this.session = session;
			return true;
		}
	}
}
 
Example #5
Source File: ReactiveSingleTableEntityPersister.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void update(
		Serializable id,
		Object[] fields,
		int[] dirtyFields,
		boolean hasDirtyCollection,
		Object[] oldFields,
		Object oldVersion,
		Object object,
		Object rowId,
		SharedSessionContractImplementor session) throws HibernateException {
	throw new UnsupportedOperationException( "Wrong method calls. Use the reactive equivalent." );
}
 
Example #6
Source File: DeleteExecutor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int execute(QueryParameters parameters, SharedSessionContractImplementor session) throws HibernateException {
	for (String delete : deletes) {
		doExecute( parameters, session, delete, parameterSpecifications );
	}
	
	// finally, execute the original sql statement
	return super.execute( parameters, session );
}
 
Example #7
Source File: Loader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Called by wrappers that batch initialize collections
 */
public final void loadCollectionBatch(
		final SharedSessionContractImplementor session,
		final Serializable[] ids,
		final Type type) throws HibernateException {
	if ( LOG.isDebugEnabled() ) {
		LOG.debugf(
				"Batch loading collection: %s",
				MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() )
		);
	}

	Type[] idTypes = new Type[ids.length];
	Arrays.fill( idTypes, type );
	try {
		doQueryAndInitializeNonLazyCollections(
				session,
				new QueryParameters( idTypes, ids, ids ),
				true
		);
	}
	catch (SQLException sqle) {
		throw factory.getJdbcServices().getSqlExceptionHelper().convert(
				sqle,
				"could not initialize a collection batch: " +
						MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ),
				getSQLString()
		);
	}

	LOG.debug( "Done batch load" );
}
 
Example #8
Source File: Loader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute an SQL query and attempt to instantiate instances of the class mapped by the given
 * persister from each row of the <tt>ResultSet</tt>. If an object is supplied, will attempt to
 * initialize that object. If a collection is supplied, attempt to initialize that collection.
 */
public List doQueryAndInitializeNonLazyCollections(
		final SharedSessionContractImplementor session,
		final QueryParameters queryParameters,
		final boolean returnProxies) throws HibernateException, SQLException {
	return doQueryAndInitializeNonLazyCollections(
			session,
			queryParameters,
			returnProxies,
			null
	);
}
 
Example #9
Source File: AbstractCollectionPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object readIndex(ResultSet rs, String[] aliases, SharedSessionContractImplementor session)
		throws HibernateException, SQLException {
	Object index = getIndexType().nullSafeGet( rs, aliases, session, null );
	if ( index == null ) {
		throw new HibernateException( "null index column for collection: " + navigableRole.getFullPath() );
	}
	index = decrementIndexByBase( index );
	return index;
}
 
Example #10
Source File: DynamicFilterParameterSpecification.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int bind(
		PreparedStatement statement,
		QueryParameters qp,
		SharedSessionContractImplementor session,
		int start) throws SQLException {
	final int columnSpan = definedParameterType.getColumnSpan( session.getFactory() );
	final String fullParamName = filterName + '.' + parameterName;
	final Object value = session.getLoadQueryInfluencers().getFilterParameterValue(fullParamName);
	final Type type = session.getLoadQueryInfluencers().getFilterParameterType(fullParamName);
	if ( Collection.class.isInstance( value ) ) {
		int positions = 0;
		Iterator itr = ( ( Collection ) value ).iterator();
		while ( itr.hasNext() ) {
			Object next = itr.next();
			qp.bindDynamicParameter( type, next );
			definedParameterType.nullSafeSet( statement, next, start + positions, session );
			positions += columnSpan;
		}
		return positions;
	}
	else {
		qp.bindDynamicParameter(type, value);
		definedParameterType.nullSafeSet( statement, value, start, session );
		return columnSpan;
	}
}
 
Example #11
Source File: JsonBinaryPlainStringType.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Object nullSafeGet( ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner ) throws HibernateException, SQLException
{
    final Object result = rs.getObject( names[0] );

    if ( !rs.wasNull() )
    {
        String content = null;

        if ( result instanceof String )
        {
            content = (String) result;
        }
        else if ( result instanceof PGobject )
        {
            content = ((PGobject) result).getValue();
        }

        // Other types currently ignored

        if ( content != null )
        {
            return content.toString();
        }
    }

    return null;
}
 
Example #12
Source File: QueryParametersAdaptor.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Object[] toParameterArray(
		QueryParameters queryParameters,
		List<ParameterSpecification> parameterSpecifications,
		SharedSessionContractImplementor session) {
	return PreparedStatementAdaptor.bind( adaptor -> {
		int pos = 1;
		for (ParameterSpecification parameterSpecification: parameterSpecifications) {
			pos += parameterSpecification.bind(adaptor, queryParameters, session, pos);
		}
	} );
}
 
Example #13
Source File: AbstractCollectionPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private CollectionInitializer getSubselectInitializer(Serializable key, SharedSessionContractImplementor session) {

		if ( !isSubselectLoadable() ) {
			return null;
		}

		final PersistenceContext persistenceContext = session.getPersistenceContext();

		SubselectFetch subselect = persistenceContext.getBatchFetchQueue()
				.getSubselect( session.generateEntityKey( key, getOwnerEntityPersister() ) );

		if ( subselect == null ) {
			return null;
		}
		else {

			// Take care of any entities that might have
			// been evicted!
			Iterator iter = subselect.getResult().iterator();
			while ( iter.hasNext() ) {
				if ( !persistenceContext.containsEntity( (EntityKey) iter.next() ) ) {
					iter.remove();
				}
			}

			// Run a subquery loader
			return createSubselectInitializer( subselect, session );
		}
	}
 
Example #14
Source File: MonetaryAmountUserType.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void nullSafeSet(
		PreparedStatement st, Object value, int index,
		SharedSessionContractImplementor session
) throws HibernateException, SQLException {
	MonetaryAmount ma = (MonetaryAmount) value;
	BigDecimal amt = ma == null ? null : ma.getAmount();
	Currency cur = ma == null ? null : ma.getCurrency();
	StandardBasicTypes.BIG_DECIMAL.nullSafeSet( st, amt, index, session );
	StandardBasicTypes.CURRENCY.nullSafeSet( st, cur, index + 1, session );
}
 
Example #15
Source File: EntityUpdateAction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void doAfterTransactionCompletion(boolean success, SharedSessionContractImplementor session) throws CacheException {
	final EntityPersister persister = getPersister();
	if ( persister.canWriteToCache() ) {
		final EntityDataAccess cache = persister.getCacheAccessStrategy();
		final Object ck = cache.generateCacheKey(
				getId(),
				persister,
				session.getFactory(),
				session.getTenantIdentifier()
				
		);

		if ( success &&
				cacheEntry != null &&
				!persister.isCacheInvalidationRequired() &&
				session.getCacheMode().isPutEnabled() ) {
			final boolean put = cacheAfterUpdate( cache, ck );

			if ( put && getSession().getFactory().getStatistics().isStatisticsEnabled() ) {
				session.getFactory().getStatistics().entityCachePut(
						StatsHelper.INSTANCE.getRootEntityRole( persister ),
						getPersister().getCacheAccessStrategy().getRegion().getName()
				);
			}
		}
		else {
			cache.unlockItem(session, ck, lock );
		}
	}
	postCommitUpdate( success );
}
 
Example #16
Source File: LineSegmentType.java    From hibernate-postgresql with Apache License 2.0 5 votes vote down vote up
@Override
   public void nullSafeSet(PreparedStatement preparedStatement, Object value, int i, SharedSessionContractImplementor sessionImplementor) throws HibernateException, SQLException {
	LineSegment line = (LineSegment) value;

	if (value == null) {
		preparedStatement.setNull(i, java.sql.Types.OTHER);
	} else {
		preparedStatement.setObject(i, new PGlseg(line.getP1().getX(), line.getP1().getY(),
				line.getP2().getX(), line.getP2().getY()));
	}
}
 
Example #17
Source File: EntityPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Update a persistent instance
 */
void update(
		Serializable id,
		Object[] fields,
		int[] dirtyFields,
		boolean hasDirtyCollection,
		Object[] oldFields,
		Object oldVersion,
		Object object,
		Object rowId,
		SharedSessionContractImplementor session
) throws HibernateException;
 
Example #18
Source File: AbstractEntityTuplizer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setIdentifier(Object entity, Serializable id, EntityMode entityMode, SharedSessionContractImplementor session) {
	final Object[] extractedValues = mappedIdentifierType.getPropertyValues( id, entityMode );
	final Object[] injectionValues = new Object[extractedValues.length];
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	for ( int i = 0; i < virtualIdComponent.getSubtypes().length; i++ ) {
		final Type virtualPropertyType = virtualIdComponent.getSubtypes()[i];
		final Type idClassPropertyType = mappedIdentifierType.getSubtypes()[i];
		if ( virtualPropertyType.isEntityType() && !idClassPropertyType.isEntityType() ) {
			if ( session == null ) {
				throw new AssertionError(
						"Deprecated version of getIdentifier (no session) was used but session was required"
				);
			}
			final String associatedEntityName = ( (EntityType) virtualPropertyType ).getAssociatedEntityName();
			final EntityKey entityKey = session.generateEntityKey(
					(Serializable) extractedValues[i],
					sessionFactory.getMetamodel().entityPersister( associatedEntityName )
			);
			// it is conceivable there is a proxy, so check that first
			Object association = persistenceContext.getProxy( entityKey );
			if ( association == null ) {
				// otherwise look for an initialized version
				association = persistenceContext.getEntity( entityKey );
				if ( association == null ) {
					// get the association out of the entity itself
					association = sessionFactory.getMetamodel().entityPersister( entityName ).getPropertyValue(
							entity,
							virtualIdComponent.getPropertyNames()[i]
					);
				}
			}
			injectionValues[i] = association;
		}
		else {
			injectionValues[i] = extractedValues[i];
		}
	}
	virtualIdComponent.setPropertyValues( entity, injectionValues, entityMode );
}
 
Example #19
Source File: AbstractType.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner)
throws HibernateException {
	if ( cached==null ) {
		return null;
	}
	else {
		return deepCopy( cached, session.getFactory() );
	}
}
 
Example #20
Source File: ForeignKeys.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Is this instance persistent or detached?
 * <p/>
 * If <tt>assumed</tt> is non-null, don't hit the database to make the determination, instead assume that
 * value; the client code must be prepared to "recover" in the case that this assumed result is incorrect.
 *
 * @param entityName The name of the entity
 * @param entity The entity instance
 * @param assumed The assumed return value, if avoiding database hit is desired
 * @param session The session
 *
 * @return {@code true} if the given entity is not transient (meaning it is either detached/persistent)
 */
@SuppressWarnings("SimplifiableIfStatement")
public static boolean isNotTransient(String entityName, Object entity, Boolean assumed, SharedSessionContractImplementor session) {
	if ( entity instanceof HibernateProxy ) {
		return true;
	}

	if ( session.getPersistenceContext().isEntryFor( entity ) ) {
		return true;
	}

	// todo : shouldnt assumed be revered here?

	return !isTransient( entityName, entity, assumed, session );
}
 
Example #21
Source File: ComponentType.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public Object instantiate(Object parent, SharedSessionContractImplementor session)
		throws HibernateException {

	Object result = instantiate( entityMode );

	if ( componentTuplizer.hasParentProperty() && parent != null ) {
		componentTuplizer.setParent(
				result,
				session.getPersistenceContext().proxyFor( parent ),
				session.getFactory()
		);
	}

	return result;
}
 
Example #22
Source File: CustomType.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void nullSafeSet(
		CallableStatement statement, Object value, String name, SharedSessionContractImplementor session) throws SQLException {
	if ( canDoSetting() ) {
		((ProcedureParameterNamedBinder) getUserType() ).nullSafeSet( statement, value, name, session );
	}
	else {
		throw new UnsupportedOperationException(
				"Type [" + getUserType() + "] does support parameter binding by name"
		);
	}
}
 
Example #23
Source File: Oracle12cGetGeneratedKeysDelegate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected PreparedStatement prepare(String insertSQL, SharedSessionContractImplementor session) throws SQLException {
	return session
			.getJdbcCoordinator()
			.getStatementPreparer()
			.prepareStatement( insertSQL, keyColumns );
}
 
Example #24
Source File: ResultSetProcessorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void handlePotentiallyEmptyCollectionRootReturns(
		LoadPlan loadPlan,
		Serializable[] collectionKeys,
		ResultSet resultSet,
		SharedSessionContractImplementor session) {
	if ( collectionKeys == null ) {
		// this is not a collection initializer (and empty collections will be detected by looking for
		// the owner's identifier in the result set)
		return;
	}

	// this is a collection initializer, so we must create a collection
	// for each of the passed-in keys, to account for the possibility
	// that the collection is empty and has no rows in the result set
	//
	// todo : move this inside CollectionReturn ?
	CollectionPersister persister = ( (CollectionReturn) loadPlan.getReturns().get( 0 ) ).getCollectionPersister();
	for ( Serializable key : collectionKeys ) {
		if ( LOG.isDebugEnabled() ) {
			LOG.debugf(
					"Preparing collection intializer : %s",
						MessageHelper.collectionInfoString( persister, key, session.getFactory() )
			);
		}
		session.getPersistenceContext()
				.getLoadContexts()
				.getCollectionLoadContext( resultSet )
				.getLoadingCollection( persister, key );
	}
}
 
Example #25
Source File: MonetaryAmountUserType.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
		throws HibernateException, SQLException {
	BigDecimal amt = StandardBasicTypes.BIG_DECIMAL.nullSafeGet( rs, names[0], session);
	Currency cur = StandardBasicTypes.CURRENCY.nullSafeGet( rs, names[1], session );
	if ( amt == null ) return null;
	return new MonetaryAmount( amt, cur );
}
 
Example #26
Source File: AbstractLoadPlanBasedLoader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected SqlStatementWrapper executeQueryStatement(
		String sqlStatement,
		QueryParameters queryParameters,
		boolean scroll,
		List<AfterLoadAction> afterLoadActions,
		SharedSessionContractImplementor session) throws SQLException {

	// Processing query filters.
	queryParameters.processFilters( sqlStatement, session );

	// Applying LIMIT clause.
	final LimitHandler limitHandler = getLimitHandler(
			queryParameters.getRowSelection()
	);
	String sql = limitHandler.processSql( queryParameters.getFilteredSQL(), queryParameters.getRowSelection() );

	// Adding locks and comments.
	sql = session.getJdbcServices().getJdbcEnvironment().getDialect()
			.addSqlHintOrComment(
				sql,
				queryParameters,
				session.getFactory().getSessionFactoryOptions().isCommentsEnabled()
			);

	final PreparedStatement st = prepareQueryStatement( sql, queryParameters, limitHandler, scroll, session );
	return new SqlStatementWrapper( st, getResultSet( st, queryParameters.getRowSelection(), limitHandler, queryParameters.hasAutoDiscoverScalarTypes(), session ) );
}
 
Example #27
Source File: EntityInsertAction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean cacheAfterInsert(EntityDataAccess cache, Object ck) {
	SharedSessionContractImplementor session = getSession();
	final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
	try {
		eventListenerManager.cachePutStart();
		return cache.afterInsert( session, ck, cacheEntry, version );
	}
	finally {
		eventListenerManager.cachePutEnd();
	}
}
 
Example #28
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 #29
Source File: DynamicBatchingEntityLoaderBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object load(
		Serializable id,
		Object optionalObject,
		SharedSessionContractImplementor session,
		LockOptions lockOptions) {
	final Serializable[] batch = session.getPersistenceContext()
			.getBatchFetchQueue()
			.getEntityBatch( persister(), id, maxBatchSize, persister().getEntityMode() );

	final int numberOfIds = ArrayHelper.countNonNull( batch );
	if ( numberOfIds <= 1 ) {
		final Object result =  singleKeyLoader.load( id, optionalObject, session );
		if ( result == null ) {
			// There was no entity with the specified ID. Make sure the EntityKey does not remain
			// in the batch to avoid including it in future batches that get executed.
			BatchFetchQueueHelper.removeBatchLoadableEntityKey( id, persister(), session );
		}
		return result;
	}

	final Serializable[] idsToLoad = new Serializable[numberOfIds];
	System.arraycopy( batch, 0, idsToLoad, 0, numberOfIds );

	if ( log.isDebugEnabled() ) {
		log.debugf( "Batch loading entity: %s", MessageHelper.infoString( persister(), idsToLoad, session.getFactory() ) );
	}

	QueryParameters qp = buildQueryParameters( id, idsToLoad, optionalObject, lockOptions );
	List results = dynamicLoader.doEntityBatchFetch( session, qp, idsToLoad );

	// The EntityKey for any entity that is not found will remain in the batch.
	// Explicitly remove the EntityKeys for entities that were not found to
	// avoid including them in future batches that get executed.
	BatchFetchQueueHelper.removeNotFoundBatchLoadableEntityKeys( idsToLoad, results, persister(), session );

	return getObjectFromList( results, id, session );
}
 
Example #30
Source File: ColumnMapperSingleColumnTypeAdapter.java    From jadira with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index,
		SharedSessionContractImplementor session) throws HibernateException, SQLException {
	
	final Object param = value == null ? null : columnMapper.toNonNullValue((T) value);		
	columnMapper.getHibernateType().nullSafeSet(st, param, index, session);
}