Java Code Examples for org.hibernate.persister.entity.EntityPersister#getEntityName()

The following examples show how to use org.hibernate.persister.entity.EntityPersister#getEntityName() . 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: DefaultReactiveFlushEntityEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * make sure user didn't mangle the id
 */
public void checkId(Object object, EntityPersister persister, Serializable id, SessionImplementor session)
		throws HibernateException {

	if (id instanceof DelayedPostInsertIdentifier) {
		// this is a situation where the entity id is assigned by a post-insert generator
		// and was saved outside the transaction forcing it to be delayed
		return;
	}

	if ( persister.canExtractIdOutOfEntity() ) {

		Serializable oid = persister.getIdentifier( object, session );
		if ( id == null ) {
			throw new AssertionFailure( "null id in " + persister.getEntityName() + " entry (don't flush the Session after an exception occurs)" );
		}
		if ( !persister.getIdentifierType().isEqual( id, oid, session.getFactory() ) ) {
			throw new HibernateException(
					"identifier of an instance of " + persister.getEntityName() + " was altered from "
							+ id + " to " + oid
			);
		}
	}

}
 
Example 2
Source File: DefaultReactiveFlushEntityEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Object[] getDatabaseSnapshot(SessionImplementor session, EntityPersister persister, Serializable id) {
	final PersistenceContext persistenceContext = session.getPersistenceContextInternal();
	if ( persister.isSelectBeforeUpdateRequired() ) {
		Object[] snapshot = persistenceContext
				.getDatabaseSnapshot( id, persister );
		if ( snapshot == null ) {
			//do we even really need this? the update will fail anyway....
			final StatisticsImplementor statistics = session.getFactory().getStatistics();
			if ( statistics.isStatisticsEnabled() ) {
				statistics
						.optimisticFailure( persister.getEntityName() );
			}
			throw new StaleObjectStateException( persister.getEntityName(), id );
		}
		return snapshot;
	}
	// TODO: optimize away this lookup for entities w/o unsaved-value="undefined"
	final EntityKey entityKey = session.generateEntityKey( id, persister );
	return persistenceContext.getCachedDatabaseSnapshot( entityKey );
}
 
Example 3
Source File: DefaultFlushEntityEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Object[] getDatabaseSnapshot(SessionImplementor session, EntityPersister persister, Serializable id) {
	if ( persister.isSelectBeforeUpdateRequired() ) {
		Object[] snapshot = session.getPersistenceContext()
				.getDatabaseSnapshot(id, persister);
		if (snapshot==null) {
			//do we even really need this? the update will fail anyway....
			if ( session.getFactory().getStatistics().isStatisticsEnabled() ) {
				session.getFactory().getStatisticsImplementor()
						.optimisticFailure( persister.getEntityName() );
			}
			throw new StaleObjectStateException( persister.getEntityName(), id );
		}
		else {
			return snapshot;
		}
	}
	else {
		//TODO: optimize away this lookup for entities w/o unsaved-value="undefined"
		EntityKey entityKey = new EntityKey( id, persister, session.getEntityMode() );
		return session.getPersistenceContext()
				.getCachedDatabaseSnapshot( entityKey ); 
	}
}
 
Example 4
Source File: DefaultSaveOrUpdateEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Determine the id to use for updating.
 *
 * @param entity The entity.
 * @param persister The entity persister
 * @param requestedId The requested identifier
 * @param entityMode The entity mode.
 *
 * @return The id.
 *
 * @throws TransientObjectException If the entity is considered transient.
 */
protected Serializable getUpdateId(
		Object entity,
		EntityPersister persister,
		Serializable requestedId,
		EntityMode entityMode) {
	// use the id assigned to the instance
	Serializable id = persister.getIdentifier( entity, entityMode );
	if ( id == null ) {
		// assume this is a newly instantiated transient object
		// which should be saved rather than updated
		throw new TransientObjectException(
				"The given object has a null identifier: " +
						persister.getEntityName()
		);
	}
	else {
		return id;
	}

}
 
Example 5
Source File: EntityEntry.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
EntityEntry(
		final Status status,
		final Object[] loadedState,
		final Object rowId,
		final Serializable id,
		final Object version,
		final LockMode lockMode,
		final boolean existsInDatabase,
		final EntityPersister persister,
		final EntityMode entityMode,
		final boolean disableVersionIncrement,
		final boolean lazyPropertiesAreUnfetched) {
	this.status=status;
	this.loadedState=loadedState;
	this.id=id;
	this.rowId=rowId;
	this.existsInDatabase=existsInDatabase;
	this.version=version;
	this.lockMode=lockMode;
	this.isBeingReplicated=disableVersionIncrement;
	this.loadedWithLazyPropertiesUnfetched = lazyPropertiesAreUnfetched;
	this.persister=persister;
	this.entityMode = entityMode;
	this.entityName = persister == null ?
			null : persister.getEntityName();
}
 
Example 6
Source File: DefaultFlushEntityEventListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private Object[] getDatabaseSnapshot(SessionImplementor session, EntityPersister persister, Serializable id) {
	if ( persister.isSelectBeforeUpdateRequired() ) {
		Object[] snapshot = session.getPersistenceContext()
				.getDatabaseSnapshot( id, persister );
		if ( snapshot == null ) {
			//do we even really need this? the update will fail anyway....
			if ( session.getFactory().getStatistics().isStatisticsEnabled() ) {
				session.getFactory().getStatistics()
						.optimisticFailure( persister.getEntityName() );
			}
			throw new StaleObjectStateException( persister.getEntityName(), id );
		}
		return snapshot;
	}
	// TODO: optimize away this lookup for entities w/o unsaved-value="undefined"
	final EntityKey entityKey = session.generateEntityKey( id, persister );
	return session.getPersistenceContext().getCachedDatabaseSnapshot( entityKey );
}
 
Example 7
Source File: DefaultSaveOrUpdateEventListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determine the id to use for updating.
 *
 * @param entity The entity.
 * @param persister The entity persister
 * @param requestedId The requested identifier
 * @param session The session
 *
 * @return The id.
 *
 * @throws TransientObjectException If the entity is considered transient.
 */
protected Serializable getUpdateId(
		Object entity,
		EntityPersister persister,
		Serializable requestedId,
		SessionImplementor session) {
	// use the id assigned to the instance
	Serializable id = persister.getIdentifier( entity, session );
	if ( id == null ) {
		// assume this is a newly instantiated transient object
		// which should be saved rather than updated
		throw new TransientObjectException(
				"The given object has a null identifier: " +
						persister.getEntityName()
		);
	}
	else {
		return id;
	}

}
 
Example 8
Source File: FetchStrategyHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determine the fetch-style (if one) explicitly set for this association via fetch profiles.
 * <p/>
 * Note that currently fetch profiles only allow specifying join fetching, so this method currently
 * returns either (a) FetchStyle.JOIN or (b) null
 *
 * @param loadQueryInfluencers
 * @param persister
 * @param path
 * @param propertyNumber
 *
 * @return
 */
public static FetchStyle determineFetchStyleByProfile(
		LoadQueryInfluencers loadQueryInfluencers,
		EntityPersister persister,
		PropertyPath path,
		int propertyNumber) {
	if ( !loadQueryInfluencers.hasEnabledFetchProfiles() ) {
		// perf optimization
		return null;
	}

	// ugh, this stuff has to be made easier...
	final String fullPath = path.getFullPath();
	final String rootPropertyName = ( (OuterJoinLoadable) persister ).getSubclassPropertyName( propertyNumber );
	int pos = fullPath.lastIndexOf( rootPropertyName );
	final String relativePropertyPath = pos >= 0
			? fullPath.substring( pos )
			: rootPropertyName;
	final String fetchRole = persister.getEntityName() + "." + relativePropertyPath;

	for ( String profileName : loadQueryInfluencers.getEnabledFetchProfileNames() ) {
		final FetchProfile profile = loadQueryInfluencers.getSessionFactory().getFetchProfile( profileName );
		final Fetch fetch = profile.getFetchByRole( fetchRole );
		if ( fetch != null && Fetch.Style.JOIN == fetch.getStyle() ) {
			return FetchStyle.JOIN;
		}
	}
	return null;
}
 
Example 9
Source File: DefaultLockEventListener.java    From lams with GNU General Public License v2.0 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 10
Source File: EntityKey.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Construct a unique identifier for an entity class instance
 */
public EntityKey(Serializable id, EntityPersister persister, EntityMode entityMode) {
	if ( id == null ) {
		throw new AssertionFailure( "null identifier" );
	}
	this.identifier = id; 
	this.entityMode = entityMode;
	this.rootEntityName = persister.getRootEntityName();
	this.entityName = persister.getEntityName();
	this.identifierType = persister.getIdentifierType();
	this.isBatchLoadable = persister.isBatchLoadable();
	this.factory = persister.getFactory();
	hashCode = generateHashCode(); //cache the hashcode
}
 
Example 11
Source File: DefaultLoadEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Object processCachedEntry(
		final LoadEvent event,
		final EntityPersister persister,
		final Object ce,
		final SessionImplementor source,
		final EntityKey entityKey) {

	CacheEntry entry = (CacheEntry) persister.getCacheEntryStructure().destructure( ce, source.getFactory() );
	if(entry.isReferenceEntry()) {
		if( event.getInstanceToLoad() != null ) {
			throw new HibernateException(
					"Attempt to load entity [%s] from cache using provided object instance, but cache " +
							"is storing references: "+ event.getEntityId());
		}
		else {
			return convertCacheReferenceEntryToEntity( (ReferenceCacheEntryImpl) entry,
					event.getSession(), entityKey);
		}
	}
	else {
		Object entity = convertCacheEntryToEntity( entry, event.getEntityId(), persister, event, entityKey );

		if ( !persister.isInstance( entity ) ) {
			throw new WrongClassException(
					"loaded object was of wrong class " + entity.getClass(),
					event.getEntityId(),
					persister.getEntityName()
			);
		}

		return entity;
	}
}
 
Example 12
Source File: DefaultLoadEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void checkIdClass(
		final EntityPersister persister,
		final LoadEvent event,
		final LoadEventListener.LoadType loadType,
		final Class idClass) {
			// we may have the kooky jpa requirement of allowing find-by-id where
		// "id" is the "simple pk value" of a dependent objects parent.  This
		// is part of its generally goofy "derived identity" "feature"
		if ( persister.getEntityMetamodel().getIdentifierProperty().isEmbedded() ) {
			final EmbeddedComponentType dependentIdType =
					(EmbeddedComponentType) persister.getEntityMetamodel().getIdentifierProperty().getType();
			if ( dependentIdType.getSubtypes().length == 1 ) {
				final Type singleSubType = dependentIdType.getSubtypes()[0];
				if ( singleSubType.isEntityType() ) {
					final EntityType dependentParentType = (EntityType) singleSubType;
					final Type dependentParentIdType = dependentParentType.getIdentifierOrUniqueKeyType( event.getSession().getFactory() );
					if ( dependentParentIdType.getReturnedClass().isInstance( event.getEntityId() ) ) {
						// yep that's what we have...
						loadByDerivedIdentitySimplePkValue(
								event,
								loadType,
								persister,
								dependentIdType,
								event.getSession().getFactory().getEntityPersister( dependentParentType.getAssociatedEntityName() )
						);
						return;
					}
				}
			}
		}
		throw new TypeMismatchException(
				"Provided id of the wrong type for class " + persister.getEntityName() + ". Expected: " + idClass
						+ ", got " + event.getEntityId().getClass()
		);
}
 
Example 13
Source File: FromElementFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
FromElement createElementJoin(QueryableCollection queryableCollection) throws SemanticException {
		FromElement elem;

		implied = true; //TODO: always true for now, but not if we later decide to support elements() in the from clause
		inElementsFunction = true;
		Type elementType = queryableCollection.getElementType();
		if ( !elementType.isEntityType() ) {
			throw new IllegalArgumentException( "Cannot create element join for a collection of non-entities!" );
		}
		this.queryableCollection = queryableCollection;
		SessionFactoryHelper sfh = fromClause.getSessionFactoryHelper();
		FromElement destination = null;
		String tableAlias = null;
		EntityPersister entityPersister = queryableCollection.getElementPersister();
		tableAlias = fromClause.getAliasGenerator().createName( entityPersister.getEntityName() );
		String associatedEntityName = entityPersister.getEntityName();
		EntityPersister targetEntityPersister = sfh.requireClassPersister( associatedEntityName );
		// Create the FROM element for the target (the elements of the collection).
		destination = createAndAddFromElement(
				associatedEntityName,
				classAlias,
				targetEntityPersister,
				(EntityType) queryableCollection.getElementType(),
				tableAlias
		);
		// If the join is implied, then don't include sub-classes on the element.
		if ( implied ) {
			destination.setIncludeSubclasses( false );
		}
		fromClause.addCollectionJoinFromElementByPath( path, destination );
//		origin.addDestination(destination);
		// Add the query spaces.
		fromClause.getWalker().addQuerySpaces( entityPersister.getQuerySpaces() );

		CollectionType type = queryableCollection.getCollectionType();
		String role = type.getRole();
		String roleAlias = origin.getTableAlias();

		String[] targetColumns = sfh.getCollectionElementColumns( role, roleAlias );
		AssociationType elementAssociationType = sfh.getElementAssociationType( type );

		// Create the join element under the from element.
		JoinType joinType = JoinType.INNER_JOIN;
		JoinSequence joinSequence = sfh.createJoinSequence(
				implied,
				elementAssociationType,
				tableAlias,
				joinType,
				targetColumns
		);
		elem = initializeJoin( path, destination, joinSequence, targetColumns, origin, false );
		elem.setUseFromFragment( true );    // The associated entity is implied, but it must be included in the FROM.
		elem.setCollectionTableAlias( roleAlias );    // The collection alias is the role.
		return elem;
	}
 
Example 14
Source File: EntityCrudEventListener.java    From mojito with Apache License 2.0 4 votes vote down vote up
@Override
public boolean requiresPostCommitHanding(EntityPersister ep) {
    String entityName = ep.getEntityName();
    return ENTITY_NAMES.contains(entityName);
}
 
Example 15
Source File: Nullability.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Check nullability of the class persister properties
 *
 * @param values entity properties
 * @param persister class persister
 * @param isUpdate wether it is intended to be updated or saved
 * @throws org.hibernate.PropertyValueException Break the nullability of one property
 * @throws HibernateException error while getting Component values
 */
public void checkNullability(
		final Object[] values,
		final EntityPersister persister,
		final boolean isUpdate) 
throws PropertyValueException, HibernateException {

	/*
	  * Algorithm
	  * Check for any level one nullability breaks
	  * Look at non null components to
	  *   recursively check next level of nullability breaks
	  * Look at Collections contraining component to
	  *   recursively check next level of nullability breaks
	  *
	  *
	  * In the previous implementation, not-null stuffs where checked
	  * filtering by level one only updateable
	  * or insertable columns. So setting a sub component as update="false"
	  * has no effect on not-null check if the main component had good checkeability
	  * In this implementation, we keep this feature.
	  * However, I never see any documentation mentioning that, but it's for
	  * sure a limitation.
	  */

	final boolean[] nullability = persister.getPropertyNullability();
	final boolean[] checkability = isUpdate ?
		persister.getPropertyUpdateability() :
		persister.getPropertyInsertability();
	final Type[] propertyTypes = persister.getPropertyTypes();

	for ( int i = 0; i < values.length; i++ ) {
		
		if ( checkability[i] && values[i]!=LazyPropertyInitializer.UNFETCHED_PROPERTY ) {
			final Object value = values[i];
			if ( !nullability[i] && value == null ) {
				
				//check basic level one nullablilty
				throw new PropertyValueException(
						"not-null property references a null or transient value",
						persister.getEntityName(),
						persister.getPropertyNames()[i]
					);
				
			}
			else if ( value != null ) {
				
				//values is not null and is checkable, we'll look deeper
				String breakProperties = checkSubElementsNullability( propertyTypes[i], value );
				if ( breakProperties != null ) {
					throw new PropertyValueException(
						"not-null property references a null or transient value",
						persister.getEntityName(),
						buildPropertyPath( persister.getPropertyNames()[i], breakProperties )
					);
				}
				
			}
		}
		
	}
}
 
Example 16
Source File: Nullability.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void checkNullability(
		final Object[] values,
		final EntityPersister persister,
		final NullabilityCheckType checkType) {

	/*
	 * Typically when Bean Validation is on, we don't want to validate null values
	 * at the Hibernate Core level. Hence the checkNullability setting.
	 */
	if ( checkNullability ) {
		/*
		  * Algorithm
		  * Check for any level one nullability breaks
		  * Look at non null components to
		  *   recursively check next level of nullability breaks
		  * Look at Collections containing components to
		  *   recursively check next level of nullability breaks
		  *
		  *
		  * In the previous implementation, not-null stuffs where checked
		  * filtering by level one only updateable
		  * or insertable columns. So setting a sub component as update="false"
		  * has no effect on not-null check if the main component had good checkeability
		  * In this implementation, we keep this feature.
		  * However, I never see any documentation mentioning that, but it's for
		  * sure a limitation.
		  */

		final boolean[] nullability = persister.getPropertyNullability();
		final boolean[] checkability = checkType == NullabilityCheckType.CREATE
				? persister.getPropertyInsertability()
				: persister.getPropertyUpdateability();
		final Type[] propertyTypes = persister.getPropertyTypes();

		for ( int i = 0; i < values.length; i++ ) {

			if ( checkability[i] && values[i]!= LazyPropertyInitializer.UNFETCHED_PROPERTY ) {
				final Object value = values[i];
				if ( !nullability[i] && value == null ) {
					//check basic level one nullablilty
					throw new PropertyValueException(
							"not-null property references a null or transient value",
							persister.getEntityName(),
							persister.getPropertyNames()[i]
						);

				}
				else if ( value != null ) {
					//values is not null and is checkable, we'll look deeper
					final String breakProperties = checkSubElementsNullability( propertyTypes[i], value );
					if ( breakProperties != null ) {
						throw new PropertyValueException(
							"not-null property references a null or transient value",
							persister.getEntityName(),
							buildPropertyPath( persister.getPropertyNames()[i], breakProperties )
						);
					}

				}
			}

		}
	}
}
 
Example 17
Source File: DefaultMergeEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected void entityIsTransient(MergeEvent event, Map copyCache) {
	
	log.trace("merging transient instance");
	
	final Object entity = event.getEntity();
	final EventSource source = event.getSession();

	final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity );
	final String entityName = persister.getEntityName();
	
	final Serializable id = persister.hasIdentifierProperty() ?
			persister.getIdentifier( entity, source.getEntityMode() ) :
	        null;
	
	final Object copy = persister.instantiate( id, source.getEntityMode() );  //TODO: should this be Session.instantiate(Persister, ...)?
	copyCache.put(entity, copy); //before cascade!
	
	// cascade first, so that all unsaved objects get their
	// copy created before we actually copy
	//cascadeOnMerge(event, persister, entity, copyCache, Cascades.CASCADE_BEFORE_MERGE);
	super.cascadeBeforeSave(source, persister, entity, copyCache);
	copyValues(persister, entity, copy, source, copyCache, ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT);
	
	//this bit is only *really* absolutely necessary for handling 
	//requestedId, but is also good if we merge multiple object 
	//graphs, since it helps ensure uniqueness
	final Serializable requestedId = event.getRequestedId();
	if (requestedId==null) {
		saveWithGeneratedId( copy, entityName, copyCache, source, false );
	}
	else {
		saveWithRequestedId( copy, requestedId, entityName, copyCache, source );
	}
	
	// cascade first, so that all unsaved objects get their 
	// copy created before we actually copy
	super.cascadeAfterSave(source, persister, entity, copyCache);
	copyValues(persister, entity, copy, source, copyCache, ForeignKeyDirection.FOREIGN_KEY_TO_PARENT);
	
	event.setResult(copy);

}
 
Example 18
Source File: EntityAction.java    From cacheonix-core with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Instantiate an action.
 *
 * @param session The session from which this action is coming.
 * @param id The id of the entity
 * @param instance The entiyt instance
 * @param persister The entity persister
 */
protected EntityAction(SessionImplementor session, Serializable id, Object instance, EntityPersister persister) {
	this.entityName = persister.getEntityName();
	this.id = id;
	this.instance = instance;
	this.session = session;
	this.persister = persister;
}
 
Example 19
Source File: EntityAction.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Instantiate an action.
 *
 * @param session The session from which this action is coming.
 * @param id The id of the entity
 * @param instance The entity instance
 * @param persister The entity persister
 */
protected EntityAction(SharedSessionContractImplementor session, Serializable id, Object instance, EntityPersister persister) {
	this.entityName = persister.getEntityName();
	this.id = id;
	this.instance = instance;
	this.session = session;
	this.persister = persister;
}
 
Example 20
Source File: Association.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Constructs a association defining what is to be fetched.
 *
 * @param owner The entity owning the association
 * @param associationPath The path of the association, from the entity
 */
public Association(EntityPersister owner, String associationPath) {
	this.owner = owner;
	this.associationPath = associationPath;
	this.role = owner.getEntityName() + '.' + associationPath;
}