Java Code Examples for org.hibernate.engine.SessionImplementor

The following examples show how to use org.hibernate.engine.SessionImplementor. These examples are extracted from open source projects. 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
public synchronized Serializable generate(SessionImplementor session, Object obj)
	throws HibernateException {
	if (maxLo < 1) {
		//keep the behavior consistent even for boundary usages
		int val = ( (Integer) doWorkInNewTransaction(session) ).intValue();
		if (val == 0) val = ( (Integer) doWorkInNewTransaction(session) ).intValue();
		return IdentifierGeneratorFactory.createNumber( val, returnClass );
	}
	if (lo>maxLo) {
		int hival = ( (Integer) doWorkInNewTransaction(session) ).intValue();
		lo = (hival == 0) ? 1 : 0;
		hi = hival * (maxLo+1);
		log.debug("new hi value: " + hival);
	}
	return IdentifierGeneratorFactory.createNumber( hi + lo++, returnClass );
}
 
Example 2
/**
 * Apply the {@link Type#replace} operation across a series of values.
 *
 * @param original The source of the state
 * @param target The target into which to replace the source values.
 * @param types The value types
 * @param session The orginating session
 * @param owner The entity "owning" the values
 * @param copyCache A map representing a cache of already replaced state
 * @return The replaced state
 */
public static Object[] replace(
		final Object[] original,
		final Object[] target,
		final Type[] types,
		final SessionImplementor session,
		final Object owner,
		final Map copyCache) {
	Object[] copied = new Object[original.length];
	for ( int i = 0; i < types.length; i++ ) {
		if ( original[i] == LazyPropertyInitializer.UNFETCHED_PROPERTY
			|| original[i] == BackrefPropertyAccessor.UNKNOWN ) {
			copied[i] = target[i];
		}
		else {
			copied[i] = types[i].replace( original[i], target[i], session, owner, copyCache );
		}
	}
	return copied;
}
 
Example 3
Source Project: webdsl   Source File: PersistentOwnedSet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean endRead() {
	//afterInitialize(); // Needed for DelayedOperations
	boolean result = super.endRead();
	((utils.OwnedSet)set).setDoEvents(true); // We should resume updating the inverse, because initialization is complete

	if(this.restoreFilter != null) {
		// Restore the filter that was enabled before enabling the filter hint
		SessionImplementor session = getSession();
		org.hibernate.engine.LoadQueryInfluencers lqi = session.getLoadQueryInfluencers();
		org.hibernate.impl.FilterImpl oldFilter = this.getAffectingFilter();
		if(oldFilter != null) lqi.disableFilter(oldFilter.getName());
		utils.QueryOptimization.restoreFilter(lqi, this.restoreFilter);
		this.restoreFilter = null;
	}

	return result;
}
 
Example 4
public Object replace(
		Object original, 
		Object target,
		SessionImplementor session, 
		Object owner, 
		Map copyCache)
throws HibernateException {
	if (original==null) {
		return null;
	}
	else {
		String entityName = session.bestGuessEntityName(original);
		Serializable id = ForeignKeys.getEntityIdentifierIfNotUnsaved( 
				entityName, 
				original, 
				session 
			);
		return session.internalLoad( 
				entityName, 
				id, 
				false, 
				false
			);
	}
}
 
Example 5
Source Project: webdsl   Source File: PersistentOwnedSet.java    License: Apache License 2.0 6 votes vote down vote up
protected FilterImpl getAffectingFilter(utils.AbstractOwnedSetType type) {
	SessionImplementor session = getSession();
	FilterImpl filter = null;
	LoadQueryInfluencers lqi = session.getLoadQueryInfluencers();
	if(lqi != null) {
		java.util.Map filters = lqi.getEnabledFilters();
		for(Object entry : filters.entrySet()) {
			if(!(entry instanceof java.util.Map.Entry)) continue;
			Object key = ((java.util.Map.Entry)entry).getKey();
			Object value = ((java.util.Map.Entry)entry).getValue();
			if(key != null && value != null && value instanceof org.hibernate.impl.FilterImpl && type.isAffectedBy(key.toString())) {
				if(filter == null) {
					filter = (org.hibernate.impl.FilterImpl) value;
				} else {
					throw new java.lang.UnsupportedOperationException("Filters '" + filter.getName() + "' and '" + key.toString() + "' both filter the same collection role" + (getRole() == null ? "." : " (" + getRole() + ")."));
				}
			}
		}
	}
	return filter;
}
 
Example 6
protected Object getResultColumnOrRow(Object[] row, ResultTransformer transformer, ResultSet rs, SessionImplementor session)
throws SQLException, HibernateException {
	final Object[] result;
	final String[] aliases;
	if ( translator.hasProjection() ) {
		Type[] types = translator.getProjectedTypes();
		result = new Object[types.length];
		String[] columnAliases = translator.getProjectedColumnAliases();
		for ( int i=0; i<result.length; i++ ) {
			result[i] = types[i].nullSafeGet(rs, columnAliases[i], session, null);
		}
		aliases = translator.getProjectedAliases();
	}
	else {
		result = row;
		aliases = userAliases;
	}
	return translator.getRootCriteria().getResultTransformer()
			.transformTuple(result, aliases);
}
 
Example 7
public Object replaceElements(
	Object original,
	Object target,
	Object owner, 
	Map copyCache, 
	SessionImplementor session)
throws HibernateException {
	
	int length = Array.getLength(original);
	if ( length!=Array.getLength(target) ) {
		//note: this affects the return value!
		target=instantiateResult(original);
	}
	
	Type elemType = getElementType( session.getFactory() );
	for ( int i=0; i<length; i++ ) {
		Array.set( target, i, elemType.replace( Array.get(original, i), null, session, owner, copyCache ) );
	}
	
	return target;

}
 
Example 8
Source Project: cacheonix-core   Source File: Loader.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private void putResultInQueryCache(
		final SessionImplementor session, 
		final QueryParameters queryParameters, 
		final Type[] resultTypes,
		final QueryCache queryCache, 
		final QueryKey key, 
		final List result) {
	
	if ( session.getCacheMode().isPutEnabled() ) {
		boolean put = queryCache.put(
				key, 
				resultTypes, 
				result, 
				queryParameters.isNaturalKeyLookup(), 
				session 
		);
		if ( put && factory.getStatistics().isStatisticsEnabled() ) {
			factory.getStatisticsImplementor()
					.queryCachePut( getQueryIdentifier(), queryCache.getRegionName() );
		}
	}
}
 
Example 9
public Object replace(
		Object original, 
		Object target, 
		SessionImplementor session, 
		Object owner, 
		Map copyCache, 
		ForeignKeyDirection foreignKeyDirection) 
throws HibernateException {
	boolean include;
	if ( isAssociationType() ) {
		AssociationType atype = (AssociationType) this;
		include = atype.getForeignKeyDirection()==foreignKeyDirection;
	}
	else {
		include = ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT==foreignKeyDirection;
	}
	return include ? replace(original, target, session, owner, copyCache) : target;
}
 
Example 10
Source Project: cacheonix-core   Source File: Loader.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Called by subclasses that batch initialize collections
 */
protected final void loadCollectionSubselect(
        final SessionImplementor session,
        final Serializable[] ids,
        final Object[] parameterValues,
        final Type[] parameterTypes,
        final Map namedParameters,
        final Type type) throws HibernateException {

	Type[] idTypes = new Type[ids.length];
	Arrays.fill( idTypes, type );
	try {
		doQueryAndInitializeNonLazyCollections( session,
				new QueryParameters( parameterTypes, parameterValues, namedParameters, ids ),
				true 
			);
	}
	catch ( SQLException sqle ) {
		throw JDBCExceptionHelper.convert(
		        factory.getSQLExceptionConverter(),
		        sqle,
		        "could not load collection by subselect: " + 
		        MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ),
		        getSQLString()
			);
	}
}
 
Example 11
public Object assemble(
	Serializable cached,
	SessionImplementor session,
	Object owner) {

	return deepCopy(cached);
}
 
Example 12
private String buildSelectVersionQuery(SessionImplementor session, String versionName, String idName, String tableName) {
	Dialect dialect = session.getFactory().getDialect();
	final String alias = "tbl";
	List<String> maxArgs = new ArrayList<>();
	maxArgs.add(StringHelper.qualify(alias, versionName));
	String maxFunction = dialect.getFunctions().get("max").render(IntegerType.INSTANCE, maxArgs, session.getFactory());
	String sql = "select " + maxFunction + " from " + tableName + ' ' + alias + " where " + StringHelper.qualify(alias, idName) + " = ?";
	return sql;
}
 
Example 13
/**
 * Hibernate 3.1 implementation of ID transferral.
 */
@Override
protected void entityIsTransient(MergeEvent event, Map copyCache) {
	super.entityIsTransient(event, copyCache);
	SessionImplementor session = event.getSession();
	EntityPersister persister = session.getEntityPersister(event.getEntityName(), event.getEntity());
	// Extract id from merged copy (which is currently registered with Session).
	Serializable id = persister.getIdentifier(event.getResult(), session.getEntityMode());
	// Set id on original object (which remains detached).
	persister.setIdentifier(event.getOriginal(), id, session.getEntityMode());
}
 
Example 14
/**
 * Determine if any of the given field values are modified, returning an array containing
 * indices of the modified fields.
 * <p/>
 * If it is determined that no fields are dirty, null is returned.
 *
 * @param properties The property definitions
 * @param currentState The current state of the entity
 * @param previousState The baseline state of the entity
 * @param includeColumns Columns to be included in the mod checking, per property
 * @param anyUninitializedProperties Does the entity currently hold any uninitialized property values?
 * @param session The session from which the dirty check request originated.
 * @return Array containing indices of the modified properties, or null if no properties considered modified.
 */
public static int[] findModified(
		final StandardProperty[] properties, 
		final Object[] currentState,
		final Object[] previousState,
		final boolean[][] includeColumns,
		final boolean anyUninitializedProperties, 
		final SessionImplementor session) {
	int[] results = null;
	int count = 0;
	int span = properties.length;

	for ( int i = 0; i < span; i++ ) {
		final boolean modified = currentState[i]!=LazyPropertyInitializer.UNFETCHED_PROPERTY
				&& properties[i].isDirtyCheckable(anyUninitializedProperties)
				&& properties[i].getType().isModified( previousState[i], currentState[i], includeColumns[i], session );

		if ( modified ) {
			if ( results == null ) {
				results = new int[span];
			}
			results[count++] = i;
		}
	}

	if ( count == 0 ) {
		return null;
	}
	else {
		int[] trimmed = new int[count];
		System.arraycopy( results, 0, trimmed, 0, count );
		return trimmed;
	}
}
 
Example 15
/**
 * Write the identifier to a JDBC <tt>PreparedStatement</tt>
 */
public int writeIdentifier(PreparedStatement st, Object id, int i, SessionImplementor session)
		throws HibernateException, SQLException {
	
	getIdentifierType().nullSafeSet( st, id, i, session );
	return i + 1;
}
 
Example 16
public QueryImpl(
		String queryString,
        FlushMode flushMode,
        SessionImplementor session,
        ParameterMetadata parameterMetadata) {
	super( queryString, flushMode, session, parameterMetadata );
}
 
Example 17
private Object[] getValues(
		Object entity,
		EntityEntry entry,
		EntityMode entityMode,
		boolean mightBeDirty,
        SessionImplementor session
) {
	final Object[] loadedState = entry.getLoadedState();
	final Status status = entry.getStatus();
	final EntityPersister persister = entry.getPersister();

	final Object[] values;
	if ( status == Status.DELETED ) {
		//grab its state saved at deletion
		values = entry.getDeletedState();
	}
	else if ( !mightBeDirty && loadedState!=null ) {
		values = loadedState;
	}
	else {
		checkId( entity, persister, entry.getId(), entityMode );

		// grab its current state
		values = persister.getPropertyValues( entity, entityMode );

		checkNaturalId( persister, entry.getId(), values, loadedState, entityMode, session );
	}
	return values;
}
 
Example 18
public Object assemble(Serializable oid, SessionImplementor session, Object owner)
throws HibernateException {
	//TODO: currently broken for unique-key references (does not detect
	//      change to unique key property of the associated object)
	Serializable id = (Serializable) getIdentifierType(session).assemble(oid, session, null); //the owner of the association is not the owner of the id

	if ( isNotEmbedded(session) ) return id;
	
	if (id==null) {
		return null;
	}
	else {
		return resolveIdentifier(id, session);
	}
}
 
Example 19
public synchronized Serializable generate(SessionImplementor session, Object object) 
throws HibernateException {

	if (sql!=null) {
		getNext( session );
	}
	return IdentifierGeneratorFactory.createNumber(next++, returnClass);
}
 
Example 20
public Serializable disassemble(Object value, SessionImplementor session)
throws HibernateException {
	if (value==null) return null;
	Multiplicity m = (Multiplicity) value;
	return new Serializable[] { 
			new Integer(m.count), 
			ForeignKeys.getEntityIdentifierIfNotUnsaved( Glarch.class.getName(), m.glarch, session ) 
	};
}
 
Example 21
public Object getForInsert(Object target, Map mergeMap, SessionImplementor session) throws HibernateException {
	if (session==null) {
		return BackrefPropertyAccessor.UNKNOWN;
	}
	else {
		return session.getPersistenceContext()
				.getIndexInOwner(entityName, propertyName, target, mergeMap);
	}
}
 
Example 22
/**
 * {@inheritDoc}
 */
public Object replace(
		Object original,
		Object target,
		SessionImplementor session,
		Object owner,
		Map copyCache) throws HibernateException {
	if ( original == null ) {
		return null;
	}
	Object cached = copyCache.get(original);
	if ( cached != null ) {
		return cached;
	}
	else {
		if ( original == target ) {
			return target;
		}
		Object id = getIdentifier( original, session );
		if ( id == null ) {
			throw new AssertionFailure("cannot copy a reference to an object with a null id");
		}
		id = getIdentifierOrUniqueKeyType( session.getFactory() )
				.replace(id, null, session, owner, copyCache);
		return resolve( id, session, owner );
	}
}
 
Example 23
private void getNext( SessionImplementor session ) {

		log.debug("fetching initial value: " + sql);
		
		try {
			PreparedStatement st = session.getBatcher().prepareSelectStatement(sql);
			try {
				ResultSet rs = st.executeQuery();
				try {
					if ( rs.next() ) {
						next = rs.getLong(1) + 1;
						if ( rs.wasNull() ) next = 1;
					}
					else {
						next = 1;
					}
					sql=null;
					log.debug("first free id: " + next);
				}
				finally {
					rs.close();
				}
			}
			finally {
				session.getBatcher().closeStatement(st);
			}
			
		}
		catch (SQLException sqle) {
			throw JDBCExceptionHelper.convert(
					session.getFactory().getSQLExceptionConverter(),
					sqle,
					"could not fetch initial value for increment generator",
					sql
				);
		}
	}
 
Example 24
public final Object nullSafeGet(
		ResultSet rs,
		String[] names,
		SessionImplementor session,
		Object owner) throws HibernateException, SQLException {
	return nullSafeGet(rs, names[0]);
}
 
Example 25
private Object initializeLazyPropertiesFromCache(
		final String fieldName,
		final Object entity,
		final SessionImplementor session,
		final EntityEntry entry,
		final CacheEntry cacheEntry
) {

	log.trace("initializing lazy properties from second-level cache");

	Object result = null;
	Serializable[] disassembledValues = cacheEntry.getDisassembledState();
	final Object[] snapshot = entry.getLoadedState();
	for ( int j = 0; j < lazyPropertyNames.length; j++ ) {
		final Object propValue = lazyPropertyTypes[j].assemble(
				disassembledValues[ lazyPropertyNumbers[j] ],
				session,
				entity
			);
		if ( initializeLazyProperty( fieldName, entity, session, snapshot, j, propValue ) ) {
			result = propValue;
		}
	}

	log.trace( "done initializing lazy properties" );

	return result;
}
 
Example 26
public ScrollableResultsImpl(
        ResultSet rs,
        PreparedStatement ps,
        SessionImplementor sess,
        Loader loader,
        QueryParameters queryParameters,
        Type[] types, HolderInstantiator holderInstantiator) throws MappingException {
	super( rs, ps, sess, loader, queryParameters, types, holderInstantiator );
}
 
Example 27
/**
 * Retrieve property values from one row of a result set
 */
public Object[] hydrate(
		ResultSet rs,
		Serializable id,
		Object object,
		Loadable rootLoadable,
		String[][] suffixedPropertyColumns,
		boolean allProperties, 
		SessionImplementor session)
throws SQLException, HibernateException;
 
Example 28
public void nullSafeSet(
	PreparedStatement st,
	Object value,
	int index,
	boolean[] settable, 
	SessionImplementor session)
	throws HibernateException, SQLException {

	userType.nullSafeSet(st, value, index, session);

}
 
Example 29
Source Project: webdsl   Source File: AbstractOwnedListType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object replaceElements(Object original, Object target,
		CollectionPersister persister, Object owner, Map copyCache,
		SessionImplementor session) throws HibernateException {
	java.util.List result = (java.util.List) target;
	result.clear();
	result.addAll((java.util.List) original);
	return result;
}
 
Example 30
/**
 * Attempts to locate the entity in the session-level cache.
 * <p/>
 * If allowed to return nulls, then if the entity happens to be found in
 * the session cache, we check the entity type for proper handling
 * of entity hierarchies.
 * <p/>
 * If checkDeleted was set to true, then if the entity is found in the
 * session-level cache, it's current status within the session cache
 * is checked to see if it has previously been scheduled for deletion.
 *
 * @param event The load event
 * @param keyToLoad The EntityKey representing the entity to be loaded.
 * @param options The load options.
 * @return The entity from the session-level cache, or null.
 * @throws HibernateException Generally indicates problems applying a lock-mode.
 */
protected Object loadFromSessionCache(
		final LoadEvent event,
		final EntityKey keyToLoad,
		final LoadEventListener.LoadType options) throws HibernateException {
	
	SessionImplementor session = event.getSession();
	Object old = session.getEntityUsingInterceptor( keyToLoad );

	if ( old != null ) {
		// this object was already loaded
		EntityEntry oldEntry = session.getPersistenceContext().getEntry( old );
		if ( options.isCheckDeleted() ) {
			Status status = oldEntry.getStatus();
			if ( status == Status.DELETED || status == Status.GONE ) {
				return REMOVED_ENTITY_MARKER;
			}
		}
		if ( options.isAllowNulls() ) {
			EntityPersister persister = event.getSession().getFactory().getEntityPersister( event.getEntityClassName() );
			if ( ! persister.isInstance( old, event.getSession().getEntityMode() ) ) {
				return INCONSISTENT_RTN_CLASS_MARKER;
			}
		}
		upgradeLock( old, oldEntry, event.getLockMode(), session );
	}

	return old;
}