Java Code Examples for org.hibernate.persister.entity.EntityPersister

The following are top voted examples for showing how to use org.hibernate.persister.entity.EntityPersister. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lams   File: AbstractSaveEventListener.java   View source code 6 votes vote down vote up
/**
 * Handles the calls needed to perform pre-save cascades for the given entity.
 *
 * @param source The session from whcih the save event originated.
 * @param persister The entity's persister instance.
 * @param entity The entity to be saved.
 * @param anything Generally cascade-specific data
 */
protected void cascadeBeforeSave(
		EventSource source,
		EntityPersister persister,
		Object entity,
		Object anything) {

	// cascade-save to many-to-one BEFORE the parent is saved
	source.getPersistenceContext().incrementCascadeLevel();
	try {
		new Cascade( getCascadeAction(), CascadePoint.BEFORE_INSERT_AFTER_DELETE, source ).cascade(
				persister,
				entity,
				anything
		);
	}
	finally {
		source.getPersistenceContext().decrementCascadeLevel();
	}
}
 
Example 2
Project: lams   File: DefaultMergeEventListener.java   View source code 6 votes vote down vote up
private boolean isVersionChanged(Object entity, EventSource source, EntityPersister persister, Object target) {
	if ( !persister.isVersioned() ) {
		return false;
	}
	// for merging of versioned entities, we consider the version having
	// been changed only when:
	// 1) the two version values are different;
	//      *AND*
	// 2) The target actually represents database state!
	//
	// This second condition is a special case which allows
	// an entity to be merged during the same transaction
	// (though during a seperate operation) in which it was
	// originally persisted/saved
	boolean changed = !persister.getVersionType().isSame(
			persister.getVersion( target ),
			persister.getVersion( entity )
	);

	// TODO : perhaps we should additionally require that the incoming entity
	// version be equivalent to the defined unsaved-value?
	return changed && existsInDatabase( target, source, persister );
}
 
Example 3
Project: lams   File: MessageHelper.java   View source code 6 votes vote down vote up
/**
 * Generate an info message string relating to a series of entities.
 *
 * @param persister The persister for the entities
 * @param ids The entity id values
 * @param factory The session factory
 * @return An info string, in the form [FooBar#<1,2,3>]
 */
public static String infoString(
		EntityPersister persister, 
		Serializable[] ids, 
		SessionFactoryImplementor factory) {
	StringBuilder s = new StringBuilder();
	s.append( '[' );
	if( persister == null ) {
		s.append( "<null EntityPersister>" );
	}
	else {
		s.append( persister.getEntityName() );
		s.append( "#<" );
		for ( int i=0; i<ids.length; i++ ) {
			s.append( persister.getIdentifierType().toLoggableString( ids[i], factory ) );
			if ( i < ids.length-1 ) {
				s.append( ", " );
			}
		}
		s.append( '>' );
	}
	s.append( ']' );

	return s.toString();

}
 
Example 4
Project: lams   File: DefaultReplicateEventListener.java   View source code 6 votes vote down vote up
private void cascadeAfterReplicate(
		Object entity,
		EntityPersister persister,
		ReplicationMode replicationMode,
		EventSource source) {
	source.getPersistenceContext().incrementCascadeLevel();
	try {
		new Cascade( CascadingActions.REPLICATE, CascadePoint.AFTER_UPDATE, source ).cascade(
				persister,
				entity,
				replicationMode
		);
	}
	finally {
		source.getPersistenceContext().decrementCascadeLevel();
	}
}
 
Example 5
Project: lams   File: StatefulPersistenceContext.java   View source code 6 votes vote down vote up
@Override
public void manageSharedNaturalIdCrossReference(
		EntityPersister persister,
		final Serializable id,
		Object[] state,
		Object[] previousState,
		CachedNaturalIdValueSource source) {
	if ( !persister.hasNaturalIdentifier() ) {
		// nothing to do
		return;
	}

	if ( !persister.hasNaturalIdCache() ) {
		// nothing to do
		return;
	}

	persister = locateProperPersister( persister );
	final Object[] naturalIdValues = extractNaturalIdValues( state, persister );
	final Object[] previousNaturalIdValues = previousState == null ? null : extractNaturalIdValues( previousState, persister );

	managedSharedCacheEntries( persister, id, naturalIdValues, previousNaturalIdValues, source );
}
 
Example 6
Project: lams   File: DefaultLoadEventListener.java   View source code 6 votes vote down vote up
private void loadByDerivedIdentitySimplePkValue(
		LoadEvent event,
		LoadEventListener.LoadType options,
		EntityPersister dependentPersister,
		EmbeddedComponentType dependentIdType,
		EntityPersister parentPersister) {
	final EntityKey parentEntityKey = event.getSession().generateEntityKey( event.getEntityId(), parentPersister );
	final Object parent = doLoad( event, parentPersister, parentEntityKey, options );

	final Serializable dependent = (Serializable) dependentIdType.instantiate( parent, event.getSession() );
	dependentIdType.setPropertyValues( dependent, new Object[] {parent}, dependentPersister.getEntityMode() );
	final EntityKey dependentEntityKey = event.getSession().generateEntityKey( dependent, dependentPersister );
	event.setEntityId( dependent );

	event.setResult( doLoad( event, dependentPersister, dependentEntityKey, options ) );
}
 
Example 7
Project: lams   File: StatelessSessionImpl.java   View source code 6 votes vote down vote up
@Override
public Object internalLoad(
		String entityName,
        Serializable id,
        boolean eager,
        boolean nullable) throws HibernateException {
	errorIfClosed();
	EntityPersister persister = getFactory().getEntityPersister( entityName );
	// first, try to load it from the temp PC associated to this SS
	Object loaded = temporaryPersistenceContext.getEntity( generateEntityKey( id, persister ) );
	if ( loaded != null ) {
		// we found it in the temp PC.  Should indicate we are in the midst of processing a result set
		// containing eager fetches via join fetch
		return loaded;
	}
	if ( !eager && persister.hasProxy() ) {
		// if the metadata allowed proxy creation and caller did not request forceful eager loading,
		// generate a proxy
		return persister.createProxy( id, this );
	}
	// otherwise immediately materialize it
	return get( entityName, id );
}
 
Example 8
Project: lams   File: DefaultFlushEntityEventListener.java   View source code 6 votes vote down vote up
private Object[] getValues(Object entity, EntityEntry entry, 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(), session );

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

		checkNaturalId( persister, entry, values, loadedState, session );
	}
	return values;
}
 
Example 9
Project: lams   File: AbstractExpandingFetchSource.java   View source code 6 votes vote down vote up
@Override
public BidirectionalEntityReference buildBidirectionalEntityReference(
		AssociationAttributeDefinition attributeDefinition,
		FetchStrategy fetchStrategy,
		EntityReference targetEntityReference) {
	final EntityType fetchedType = (EntityType) attributeDefinition.getType();
	final EntityPersister fetchedPersister = attributeDefinition.toEntityDefinition().getEntityPersister();

	if ( fetchedPersister == null ) {
		throw new WalkingException(
				String.format(
						"Unable to locate EntityPersister [%s] for bidirectional entity reference [%s]",
						fetchedType.getAssociatedEntityName(),
						attributeDefinition.getName()
				)
		);
	}

	final BidirectionalEntityReference bidirectionalEntityReference =
			new BidirectionalEntityReferenceImpl( this, attributeDefinition, targetEntityReference );
	addBidirectionalEntityReference( bidirectionalEntityReference );
	return bidirectionalEntityReference;
}
 
Example 10
Project: lams   File: DefaultDeleteEventListener.java   View source code 6 votes vote down vote up
/**
 * We encountered a delete request on a transient instance.
 * <p/>
 * This is a deviation from historical Hibernate (pre-3.2) behavior to
 * align with the JPA spec, which states that transient entities can be
 * passed to remove operation in which case cascades still need to be
 * performed.
 *
 * @param session The session which is the source of the event
 * @param entity The entity being delete processed
 * @param cascadeDeleteEnabled Is cascading of deletes enabled
 * @param persister The entity persister
 * @param transientEntities A cache of already visited transient entities
 * (to avoid infinite recursion).
 */
protected void deleteTransientEntity(
		EventSource session,
		Object entity,
		boolean cascadeDeleteEnabled,
		EntityPersister persister,
		Set transientEntities) {
	LOG.handlingTransientEntity();
	if ( transientEntities.contains( entity ) ) {
		LOG.trace( "Already handled transient entity; skipping" );
		return;
	}
	transientEntities.add( entity );
	cascadeBeforeDelete( session, persister, entity, null, transientEntities );
	cascadeAfterDelete( session, persister, entity, transientEntities );
}
 
Example 11
Project: lams   File: DefaultMergeEventListener.java   View source code 6 votes vote down vote up
protected void copyValues(
		final EntityPersister persister,
		final Object entity,
		final Object target,
		final SessionImplementor source,
		final Map copyCache) {
	final Object[] copiedValues = TypeHelper.replace(
			persister.getPropertyValues( entity ),
			persister.getPropertyValues( target ),
			persister.getPropertyTypes(),
			source,
			target,
			copyCache
	);

	persister.setPropertyValues( target, copiedValues );
}
 
Example 12
Project: lams   File: FromElementFactory.java   View source code 6 votes vote down vote up
FromElement addFromElement() throws SemanticException {
	final FromClause parentFromClause = fromClause.getParentFromClause();
	if ( parentFromClause != null ) {
		// Look up class name using the first identifier in the path.
		final String pathAlias = PathHelper.getAlias( path );
		final FromElement parentFromElement = parentFromClause.getFromElement( pathAlias );
		if ( parentFromElement != null ) {
			return createFromElementInSubselect( path, pathAlias, parentFromElement, classAlias );
		}
	}

	final EntityPersister entityPersister = fromClause.getSessionFactoryHelper().requireClassPersister( path );

	final FromElement elem = createAndAddFromElement(
			path,
			classAlias,
			entityPersister,
			(EntityType) ( (Queryable) entityPersister ).getType(),
			null
	);

	// Add to the query spaces.
	fromClause.getWalker().addQuerySpaces( entityPersister.getQuerySpaces() );

	return elem;
}
 
Example 13
Project: lams   File: StatefulPersistenceContext.java   View source code 6 votes vote down vote up
@Override
public void registerInsertedKey(EntityPersister persister, Serializable id) {
	// we only are worried about registering these if the persister defines caching
	if ( persister.hasCache() ) {
		if ( insertedKeysMap == null ) {
			insertedKeysMap = new HashMap<String, List<Serializable>>();
		}
		final String rootEntityName = persister.getRootEntityName();
		List<Serializable> insertedEntityIds = insertedKeysMap.get( rootEntityName );
		if ( insertedEntityIds == null ) {
			insertedEntityIds = new ArrayList<Serializable>();
			insertedKeysMap.put( rootEntityName, insertedEntityIds );
		}
		insertedEntityIds.add( id );
	}
}
 
Example 14
Project: lams   File: NaturalIdXrefDelegate.java   View source code 6 votes vote down vote up
public CachedNaturalId(EntityPersister persister, Object[] values) {
	this.persister = persister;
	this.values = values;

	final int prime = 31;
	int hashCodeCalculation = 1;
	hashCodeCalculation = prime * hashCodeCalculation + persister.hashCode();

	final int[] naturalIdPropertyIndexes = persister.getNaturalIdentifierProperties();
	naturalIdTypes = new Type[ naturalIdPropertyIndexes.length ];
	int i = 0;
	for ( int naturalIdPropertyIndex : naturalIdPropertyIndexes ) {
		final Type type = persister.getPropertyType( persister.getPropertyNames()[ naturalIdPropertyIndex ] );
		naturalIdTypes[i] = type;
		final int elementHashCode = values[i] == null ? 0 :type.getHashCode( values[i], persister.getFactory() );
		hashCodeCalculation = prime * hashCodeCalculation + elementHashCode;
		i++;
	}

	this.hashCode = hashCodeCalculation;
}
 
Example 15
Project: lams   File: PostUpdateEvent.java   View source code 6 votes vote down vote up
public PostUpdateEvent(
		Object entity, 
		Serializable id,
		Object[] state,
		Object[] oldState,
		int[] dirtyProperties,
		EntityPersister persister,
		EventSource source
) {
	super(source);
	this.entity = entity;
	this.id = id;
	this.state = state;
	this.oldState = oldState;
	this.dirtyProperties = dirtyProperties;
	this.persister = persister;
}
 
Example 16
Project: lams   File: SessionFactoryHelper.java   View source code 6 votes vote down vote up
/**
 * Locate the persister by class or entity name.
 *
 * @param name The class or entity name
 *
 * @return The defined persister for this entity, or null if none found.
 *
 * @throws MappingException
 */
private EntityPersister findEntityPersisterByName(String name) throws MappingException {
	// First, try to get the persister using the given name directly.
	try {
		return sfi.getEntityPersister( name );
	}
	catch ( MappingException ignore ) {
		// unable to locate it using this name
	}

	// If that didn't work, try using the 'import' name.
	String importedClassName = sfi.getImportedClassName( name );
	if ( importedClassName == null ) {
		return null;
	}
	return sfi.getEntityPersister( importedClassName );
}
 
Example 17
Project: lams   File: AbstractPersistentCollection.java   View source code 6 votes vote down vote up
/**
 * Removes entity entries that have an equal identifier with the incoming entity instance
 *
 * @param list The list containing the entity instances
 * @param entityInstance The entity instance to match elements.
 * @param entityName The entity name
 * @param session The session
 */
public static void identityRemove(
		Collection list,
		Object entityInstance,
		String entityName,
		SessionImplementor session) {

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

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

	}
}
 
Example 18
Project: lams   File: DefaultSaveOrUpdateEventListener.java   View source code 5 votes vote down vote up
/**
 * Handles the calls needed to perform cascades as part of an update request
 * for the given entity.
 *
 * @param event The event currently being processed.
 * @param persister The defined persister for the entity being updated.
 * @param entity The entity being updated.
 */
private void cascadeOnUpdate(SaveOrUpdateEvent event, EntityPersister persister, Object entity) {
	final EventSource source = event.getSession();
	source.getPersistenceContext().incrementCascadeLevel();
	try {
		new Cascade( CascadingActions.SAVE_UPDATE, CascadePoint.AFTER_UPDATE, source ).cascade( persister, entity );
	}
	finally {
		source.getPersistenceContext().decrementCascadeLevel();
	}
}
 
Example 19
Project: lams   File: DefaultLockEventListener.java   View source code 5 votes vote down vote up
private void cascadeOnLock(LockEvent event, EntityPersister persister, Object entity) {
	EventSource source = event.getSession();
	source.getPersistenceContext().incrementCascadeLevel();
	try {
		new Cascade( CascadingActions.LOCK, CascadePoint.AFTER_LOCK, source).cascade(
				persister,
				entity,
				event.getLockOptions()
		);
	}
	finally {
		source.getPersistenceContext().decrementCascadeLevel();
	}
}
 
Example 20
Project: lams   File: MessageHelper.java   View source code 5 votes vote down vote up
/**
 * Generate an info message string relating to a particular entity.
 *
 * @param persister The persister for the entity
 * @param id The entity id value
 * @param factory The session factory - Could be null!
 * @return An info string, in the form [FooBar#1]
 */
public static String infoString(
		EntityPersister persister,
		Object id, 
		SessionFactoryImplementor factory) {
	StringBuilder s = new StringBuilder();
	s.append( '[' );
	Type idType;
	if( persister == null ) {
		s.append( "<null EntityPersister>" );
		idType = null;
	}
	else {
		s.append( persister.getEntityName() );
		idType = persister.getIdentifierType();
	}
	s.append( '#' );

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

	return s.toString();

}
 
Example 21
Project: lams   File: BatchFetchQueue.java   View source code 5 votes vote down vote up
/**
 * Get a batch of unloaded identifiers for this class, using a slightly
 * complex algorithm that tries to grab keys registered immediately after
 * the given key.
 *
 * @param persister The persister for the entities being loaded.
 * @param id The identifier of the entity currently demanding load.
 * @param batchSize The maximum number of keys to return
 * @return an array of identifiers, of length batchSize (possibly padded with nulls)
 */
public Serializable[] getEntityBatch(
		final EntityPersister persister,
		final Serializable id,
		final int batchSize,
		final EntityMode entityMode) {
	Serializable[] ids = new Serializable[batchSize];
	ids[0] = id; //first element of array is reserved for the actual instance we are loading!
	int i = 1;
	int end = -1;
	boolean checkForEnd = false;

	// TODO: this needn't exclude subclasses...

	LinkedHashSet<EntityKey> set =  batchLoadableEntityKeys.get( persister.getEntityName() );
	if ( set != null ) {
		for ( EntityKey key : set ) {
			if ( checkForEnd && i == end ) {
				//the first id found after the given id
				return ids;
			}
			if ( persister.getIdentifierType().isEqual( id, key.getIdentifier() ) ) {
				end = i;
			}
			else {
				if ( !isCached( key, persister ) ) {
					ids[i++] = key.getIdentifier();
				}
			}
			if ( i == batchSize ) {
				i = 1; // end of array, start filling again from start
				if ( end != -1 ) {
					checkForEnd = true;
				}
			}
		}
	}
	return ids; //we ran out of ids to try
}
 
Example 22
Project: lams   File: StatelessSessionImpl.java   View source code 5 votes vote down vote up
@Override
public void delete(String entityName, Object entity) {
	errorIfClosed();
	EntityPersister persister = getEntityPersister(entityName, entity);
	Serializable id = persister.getIdentifier( entity, this );
	Object version = persister.getVersion( entity );
	persister.delete(id, version, entity, this);
}
 
Example 23
Project: lams   File: DefaultLoadEventListener.java   View source code 5 votes vote down vote up
/**
 * If there is already a corresponding proxy associated with the
 * persistence context, return it; otherwise create a proxy, associate it
 * with the persistence context, and return the just-created proxy.
 *
 * @param event The initiating load request event
 * @param persister The persister corresponding to the entity to be loaded
 * @param keyToLoad The key of the entity to be loaded
 * @param options The defined load options
 * @param persistenceContext The originating session
 *
 * @return The created/existing proxy
 */
private Object createProxyIfNecessary(
		final LoadEvent event,
		final EntityPersister persister,
		final EntityKey keyToLoad,
		final LoadEventListener.LoadType options,
		final PersistenceContext persistenceContext) {
	Object existing = persistenceContext.getEntity( keyToLoad );
	if ( existing != null ) {
		// return existing object or initialized proxy (unless deleted)
		LOG.trace( "Entity found in session cache" );
		if ( options.isCheckDeleted() ) {
			EntityEntry entry = persistenceContext.getEntry( existing );
			Status status = entry.getStatus();
			if ( status == Status.DELETED || status == Status.GONE ) {
				return null;
			}
		}
		return existing;
	}
	LOG.trace( "Creating new proxy for entity" );
	// return new uninitialized proxy
	Object proxy = persister.createProxy( event.getEntityId(), event.getSession() );
	persistenceContext.getBatchFetchQueue().addBatchLoadableEntityKey( keyToLoad );
	persistenceContext.addProxy( keyToLoad, proxy );
	return proxy;
}
 
Example 24
Project: lams   File: DefaultLockEventListener.java   View source code 5 votes vote down vote up
/**
 * Handle the given lock event.
 *
 * @param event The lock event to be handled.
 * @throws HibernateException
 */
public void onLock(LockEvent event) throws HibernateException {

	if ( event.getObject() == null ) {
		throw new NullPointerException( "attempted to lock null" );
	}

	if ( event.getLockMode() == LockMode.WRITE ) {
		throw new HibernateException( "Invalid lock mode for lock()" );
	}

	if ( event.getLockMode() == LockMode.UPGRADE_SKIPLOCKED ) {
		LOG.explicitSkipLockedLockCombo();
	}

	SessionImplementor source = event.getSession();
	
	Object entity = source.getPersistenceContext().unproxyAndReassociate( event.getObject() );
	//TODO: if object was an uninitialized proxy, this is inefficient,
	//      resulting in two SQL selects
	
	EntityEntry entry = source.getPersistenceContext().getEntry(entity);
	if (entry==null) {
		final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity );
		final Serializable id = persister.getIdentifier( entity, source );
		if ( !ForeignKeys.isNotTransient( event.getEntityName(), entity, Boolean.FALSE, source ) ) {
			throw new TransientObjectException(
					"cannot lock an unsaved transient instance: " +
					persister.getEntityName()
			);
		}

		entry = reassociate(event, entity, id, persister);
		cascadeOnLock(event, persister, entity);
	}

	upgradeLock( entity, entry, event.getLockOptions(), event.getSession() );
}
 
Example 25
Project: lams   File: DefaultPersistEventListener.java   View source code 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
protected void entityIsPersistent(PersistEvent event, Map createCache) {
	LOG.trace( "Ignoring persistent instance" );
	final EventSource source = event.getSession();

	//TODO: check that entry.getIdentifier().equals(requestedId)

	final Object entity = source.getPersistenceContext().unproxy( event.getObject() );
	final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity );

	if ( createCache.put( entity, entity ) == null ) {
		justCascade( createCache, source, entity, persister );

	}
}
 
Example 26
Project: lams   File: FromElement.java   View source code 5 votes vote down vote up
private void doInitialize(FromClause fromClause, String tableAlias, String className, String classAlias,
						  EntityPersister persister, EntityType type) {
	if ( initialized ) {
		throw new IllegalStateException( "Already initialized!!" );
	}
	this.fromClause = fromClause;
	this.tableAlias = tableAlias;
	this.className = className;
	this.classAlias = classAlias;
	this.elementType = new FromElementType( this, persister, type );
	// Register the FromElement with the FROM clause, now that we have the names and aliases.
	fromClause.registerFromElement( this );
	LOG.debugf( "%s : %s (%s) -> %s", fromClause, className, classAlias == null ? "<no alias>" : classAlias, tableAlias );
}
 
Example 27
Project: lams   File: StatefulPersistenceContext.java   View source code 5 votes vote down vote up
@Override
public void handleSynchronization(EntityPersister persister, Serializable pk, Object entity) {
	if ( !persister.hasNaturalIdentifier() ) {
		// nothing to do
		return;
	}

	persister = locateProperPersister( persister );

	final Object[] naturalIdValuesFromCurrentObjectState = extractNaturalIdValues( entity, persister );
	final boolean changed = ! naturalIdXrefDelegate.sameAsCached(
			persister,
			pk,
			naturalIdValuesFromCurrentObjectState
	);

	if ( changed ) {
		final Object[] cachedNaturalIdValues = naturalIdXrefDelegate.findCachedNaturalId( persister, pk );
		naturalIdXrefDelegate.cacheNaturalIdCrossReference( persister, pk, naturalIdValuesFromCurrentObjectState );
		naturalIdXrefDelegate.stashInvalidNaturalIdReference( persister, cachedNaturalIdValues );

		removeSharedNaturalIdCrossReference(
				persister,
				pk,
				cachedNaturalIdValues
		);
	}
}
 
Example 28
Project: lams   File: SessionImpl.java   View source code 5 votes vote down vote up
/**	
 * Load the data for the object with the specified id into a newly created object.
 * This is only called when lazily initializing a proxy.
 * Do NOT return a proxy.
 */
@Override
public Object immediateLoad(String entityName, Serializable id) throws HibernateException {
	if ( LOG.isDebugEnabled() ) {
		EntityPersister persister = getFactory().getEntityPersister(entityName);
		LOG.debugf( "Initializing proxy: %s", MessageHelper.infoString( persister, id, getFactory() ) );
	}

	LoadEvent event = new LoadEvent(id, entityName, true, this);
	fireLoad(event, LoadEventListener.IMMEDIATE_LOAD);
	return event.getResult();
}
 
Example 29
Project: lams   File: StatefulPersistenceContext.java   View source code 5 votes vote down vote up
private Object getIndexInParent(
		String property,
		Object childEntity,
		EntityPersister persister,
		CollectionPersister collectionPersister,
		Object potentialParent){
	final Object collection = persister.getPropertyValue( potentialParent, property );
	if ( collection != null && Hibernate.isInitialized( collection ) ) {
		return collectionPersister.getCollectionType().indexOf( collection, childEntity );
	}
	else {
		return null;
	}
}
 
Example 30
Project: lams   File: FromElement.java   View source code 5 votes vote down vote up
public void initializeEntity(
        FromClause fromClause,
        String className,
        EntityPersister persister,
        EntityType type,
        String classAlias,
        String tableAlias) {
	doInitialize( fromClause, tableAlias, className, classAlias, persister, type );
	this.sequence = fromClause.nextFromElementCounter();
	initialized = true;
}
 
Example 31
Project: lams   File: DefaultEvictEventListener.java   View source code 5 votes vote down vote up
protected void doEvict(
		final Object object,
		final EntityKey key,
		final EntityPersister persister,
		final EventSource session)
		throws HibernateException {

	if ( LOG.isTraceEnabled() ) {
		LOG.tracev( "Evicting {0}", MessageHelper.infoString( persister ) );
	}

	if ( persister.hasNaturalIdentifier() ) {
		session.getPersistenceContext().getNaturalIdHelper().handleEviction(
				object,
				persister,
				key.getIdentifier()
		);
	}

	// remove all collections for the entity from the session-level cache
	if ( persister.hasCollections() ) {
		new EvictVisitor( session ).process( object, persister );
	}

	// remove any snapshot, not really for memory management purposes, but
	// rather because it might now be stale, and there is no longer any
	// EntityEntry to take precedence
	// This is now handled by removeEntity()
	//session.getPersistenceContext().removeDatabaseSnapshot(key);

	new Cascade( CascadingActions.EVICT, CascadePoint.AFTER_EVICT, session ).cascade( persister, object );
}
 
Example 32
Project: lams   File: AbstractSaveEventListener.java   View source code 5 votes vote down vote up
/**
 * Prepares the save call using a newly generated id.
 *
 * @param entity The entity to be saved
 * @param entityName The entity-name for the entity to be saved
 * @param anything Generally cascade-specific information.
 * @param source The session which is the source of this save event.
 * @param requiresImmediateIdAccess does the event context require
 * access to the identifier immediately after execution of this method (if
 * not, post-insert style id generators may be postponed if we are outside
 * a transaction).
 *
 * @return The id used to save the entity; may be null depending on the
 *         type of id generator used and the requiresImmediateIdAccess value
 */
protected Serializable saveWithGeneratedId(
		Object entity,
		String entityName,
		Object anything,
		EventSource source,
		boolean requiresImmediateIdAccess) {
	EntityPersister persister = source.getEntityPersister( entityName, entity );
	Serializable generatedId = persister.getIdentifierGenerator().generate( source, entity );
	if ( generatedId == null ) {
		throw new IdentifierGenerationException( "null id generated for:" + entity.getClass() );
	}
	else if ( generatedId == IdentifierGeneratorHelper.SHORT_CIRCUIT_INDICATOR ) {
		return source.getIdentifier( entity );
	}
	else if ( generatedId == IdentifierGeneratorHelper.POST_INSERT_INDICATOR ) {
		return performSave( entity, null, persister, true, anything, source, requiresImmediateIdAccess );
	}
	else {
		// TODO: define toString()s for generators
		if ( LOG.isDebugEnabled() ) {
			LOG.debugf(
					"Generated identifier: %s, using strategy: %s",
					persister.getIdentifierType().toLoggableString( generatedId, source.getFactory() ),
					persister.getIdentifierGenerator().getClass().getName()
			);
		}

		return performSave( entity, generatedId, persister, false, anything, source, true );
	}
}
 
Example 33
Project: lams   File: SessionImpl.java   View source code 5 votes vote down vote up
private SimpleNaturalIdLoadAccessImpl(EntityPersister entityPersister) {
	super(entityPersister);

	if ( entityPersister.getNaturalIdentifierProperties().length != 1 ) {
		throw new HibernateException(
				String.format( "Entity [%s] did not define a simple natural id", entityPersister.getEntityName() )
		);
	}

	final int naturalIdAttributePosition = entityPersister.getNaturalIdentifierProperties()[0];
	this.naturalIdAttributeName = entityPersister.getPropertyNames()[ naturalIdAttributePosition ];
}
 
Example 34
Project: lams   File: AbstractEntityReference.java   View source code 5 votes vote down vote up
private EncapsulatedEntityIdentifierDescription buildEncapsulatedCompositeIdentifierDescription(
		ExpandingCompositeQuerySpace compositeQuerySpace) {
	return new EncapsulatedEntityIdentifierDescription(
			this,
			compositeQuerySpace,
			(CompositeType) getEntityPersister().getIdentifierType(),
			getPropertyPath().append( EntityPersister.ENTITY_ID )
	);
}
 
Example 35
Project: lams   File: StandardCacheEntryImpl.java   View source code 5 votes vote down vote up
/**
 * Assemble the previously disassembled state represented by this entry into the given entity instance.
 *
 * Additionally manages the PreLoadEvent callbacks.
 *
 * @param instance The entity instance
 * @param id The entity identifier
 * @param persister The entity persister
 * @param interceptor (currently unused)
 * @param session The session
 *
 * @return The assembled state
 *
 * @throws HibernateException Indicates a problem performing assembly or calling the PreLoadEventListeners.
 *
 * @see org.hibernate.type.Type#assemble
 * @see org.hibernate.type.Type#disassemble
 */
public Object[] assemble(
		final Object instance,
		final Serializable id,
		final EntityPersister persister,
		final Interceptor interceptor,
		final EventSource session) throws HibernateException {
	if ( !persister.getEntityName().equals( subclass ) ) {
		throw new AssertionFailure( "Tried to assemble a different subclass instance" );
	}

	//assembled state gets put in a new array (we read from cache by value!)
	final Object[] assembledProps = TypeHelper.assemble(
			disassembledState,
			persister.getPropertyTypes(),
			session, instance
	);

	//persister.setIdentifier(instance, id); //before calling interceptor, for consistency with normal load

	//TODO: reuse the PreLoadEvent
	final PreLoadEvent preLoadEvent = new PreLoadEvent( session )
			.setEntity( instance )
			.setState( assembledProps )
			.setId( id )
			.setPersister( persister );

	final EventListenerGroup<PreLoadEventListener> listenerGroup = session
			.getFactory()
			.getServiceRegistry()
			.getService( EventListenerRegistry.class )
			.getEventListenerGroup( EventType.PRE_LOAD );
	for ( PreLoadEventListener listener : listenerGroup.listeners() ) {
		listener.onPreLoad( preLoadEvent );
	}

	persister.setPropertyValues( instance, assembledProps );

	return assembledProps;
}
 
Example 36
Project: lams   File: DefaultFlushEntityEventListener.java   View source code 5 votes vote down vote up
/**
 * Convience method to retreive an entities next version value
 */
private Object getNextVersion(FlushEntityEvent event) throws HibernateException {

	EntityEntry entry = event.getEntityEntry();
	EntityPersister persister = entry.getPersister();
	if ( persister.isVersioned() ) {

		Object[] values = event.getPropertyValues();

		if ( entry.isBeingReplicated() ) {
			return Versioning.getVersion( values, persister );
		}
		else {
			int[] dirtyProperties = event.getDirtyProperties();

			final boolean isVersionIncrementRequired = isVersionIncrementRequired(
					event,
					entry,
					persister,
					dirtyProperties
			);

			final Object nextVersion = isVersionIncrementRequired ?
					Versioning.increment( entry.getVersion(), persister.getVersionType(), event.getSession() ) :
					entry.getVersion(); //use the current version

			Versioning.setVersion( values, nextVersion, persister );

			return nextVersion;
		}
	}
	else {
		return null;
	}

}
 
Example 37
Project: lams   File: NaturalIdXrefDelegate.java   View source code 5 votes vote down vote up
private NaturalIdResolutionCache(EntityPersister persister) {
	this.persister = persister;

	final int[] naturalIdPropertyIndexes = persister.getNaturalIdentifierProperties();
	naturalIdTypes = new Type[ naturalIdPropertyIndexes.length ];
	int i = 0;
	for ( int naturalIdPropertyIndex : naturalIdPropertyIndexes ) {
		naturalIdTypes[i++] = persister.getPropertyType( persister.getPropertyNames()[ naturalIdPropertyIndex ] );
	}
}
 
Example 38
Project: lams   File: StandardPersisterClassResolver.java   View source code 5 votes vote down vote up
public Class<? extends EntityPersister> getEntityPersisterClass(EntityBinding metadata) {
	if ( metadata.isRoot() ) {
           Iterator<EntityBinding> subEntityBindingIterator = metadata.getDirectSubEntityBindings().iterator();
           if ( subEntityBindingIterator.hasNext() ) {
               //If the class has children, we need to find of which kind
               metadata = subEntityBindingIterator.next();
           }
           else {
		    return singleTableEntityPersister();
           }
	}
	switch ( metadata.getHierarchyDetails().getInheritanceType() ) {
		case JOINED: {
			return joinedSubclassEntityPersister();
		}
		case SINGLE_TABLE: {
			return singleTableEntityPersister();
		}
		case TABLE_PER_CLASS: {
			return unionSubclassEntityPersister();
		}
		default: {
			throw new UnknownPersisterException(
					"Could not determine persister implementation for entity [" + metadata.getEntity().getName() + "]"
			);
		}

	}
}
 
Example 39
Project: lams   File: CacheImpl.java   View source code 5 votes vote down vote up
@Override
public void evictNaturalIdRegion(String entityName) {
	EntityPersister p = sessionFactory.getEntityPersister( entityName );
	if ( p.hasNaturalIdCache() ) {
		if ( LOG.isDebugEnabled() ) {
			LOG.debugf( "Evicting natural-id cache: %s", p.getEntityName() );
		}
		p.getNaturalIdCacheAccessStrategy().evictAll();
	}
}
 
Example 40
Project: lams   File: PersisterFactoryImpl.java   View source code 5 votes vote down vote up
@Override
@SuppressWarnings( {"unchecked"})
public EntityPersister createEntityPersister(
		PersistentClass metadata,
		EntityRegionAccessStrategy cacheAccessStrategy,
		NaturalIdRegionAccessStrategy naturalIdRegionAccessStrategy,
		SessionFactoryImplementor factory,
		Mapping cfg) {
	Class<? extends EntityPersister> persisterClass = metadata.getEntityPersisterClass();
	if ( persisterClass == null ) {
		persisterClass = serviceRegistry.getService( PersisterClassResolver.class ).getEntityPersisterClass( metadata );
	}
	return create( persisterClass, ENTITY_PERSISTER_CONSTRUCTOR_ARGS, metadata, cacheAccessStrategy, naturalIdRegionAccessStrategy, factory, cfg );
}