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

The following examples show how to use org.hibernate.persister.entity.EntityPersister#getPropertyTypes() . 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: ForeignKeys.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Find all non-nullable references to entities that have not yet
 * been inserted in the database, where the foreign key
 * is a reference to an unsaved transient entity. .
 *
 * @param entityName - the entity name
 * @param entity - the entity instance
 * @param values - insertable properties of the object (including backrefs),
 * possibly with substitutions
 * @param isEarlyInsert - true if the entity needs to be executed as soon as possible
 * (e.g., to generate an ID)
 * @param session - the session
 *
 * @return the transient unsaved entity dependencies that are non-nullable,
 *         or null if there are none.
 */
public static NonNullableTransientDependencies findNonNullableTransientEntities(
		String entityName,
		Object entity,
		Object[] values,
		boolean isEarlyInsert,
		SharedSessionContractImplementor session) {
	final Nullifier nullifier = new Nullifier( entity, false, isEarlyInsert, session );
	final EntityPersister persister = session.getEntityPersister( entityName, entity );
	final String[] propertyNames = persister.getPropertyNames();
	final Type[] types = persister.getPropertyTypes();
	final boolean[] nullability = persister.getPropertyNullability();
	final NonNullableTransientDependencies nonNullableTransientEntities = new NonNullableTransientDependencies();
	for ( int i = 0; i < types.length; i++ ) {
		collectNonNullableTransientEntities(
				nullifier,
				values[i],
				propertyNames[i],
				types[i],
				nullability[i],
				session,
				nonNullableTransientEntities
		);
	}
	return nonNullableTransientEntities.isEmpty() ? null : nonNullableTransientEntities;
}
 
Example 2
Source File: DefaultReactiveDeleteEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Object[] createDeletedState(EntityPersister persister, Object[] currentState, EventSource session) {
		Type[] propTypes = persister.getPropertyTypes();
		final Object[] deletedState = new Object[propTypes.length];
//      TypeFactory.deepCopy( currentState, propTypes, persister.getPropertyUpdateability(), deletedState, session );
		boolean[] copyability = new boolean[propTypes.length];
		java.util.Arrays.fill( copyability, true );
		TypeHelper.deepCopy( currentState, propTypes, copyability, deletedState, session );
		return deletedState;
	}
 
Example 3
Source File: DefaultReactiveFlushEntityEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Flushes a single entity's state to the database, by scheduling
 * an update action, if necessary
 */
public void onFlushEntity(FlushEntityEvent event) throws HibernateException {
	final Object entity = event.getEntity();
	final EntityEntry entry = event.getEntityEntry();
	final EventSource session = event.getSession();
	final EntityPersister persister = entry.getPersister();
	final Status status = entry.getStatus();
	final Type[] types = persister.getPropertyTypes();

	final boolean mightBeDirty = entry.requiresDirtyCheck( entity );

	final Object[] values = getValues( entity, entry, mightBeDirty, session );

	event.setPropertyValues( values );

	//TODO: avoid this for non-new instances where mightBeDirty==false
	boolean substitute = wrapCollections( session, persister, types, values );

	if ( isUpdateNecessary( event, mightBeDirty ) ) {
		substitute = scheduleUpdate( event ) || substitute;
	}

	if ( status != Status.DELETED ) {
		// now update the object .. has to be outside the main if block above (because of collections)
		if ( substitute ) {
			persister.setPropertyValues( entity, values );
		}

		// Search for collections by reachability, updating their role.
		// We don't want to touch collections reachable from a deleted object
		if ( persister.hasCollections() ) {
			new FlushVisitor( session, entity ).processEntityPropertyValues( values, types );
		}
	}
}
 
Example 4
Source File: Example.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {

	EntityPersister meta = criteriaQuery.getFactory()
			.getEntityPersister( criteriaQuery.getEntityName(criteria) );
	String[] propertyNames = meta.getPropertyNames();
	Type[] propertyTypes = meta.getPropertyTypes();
	 //TODO: get all properties, not just the fetched ones!
	Object[] values = meta.getPropertyValues( entity, getEntityMode(criteria, criteriaQuery) );
	List list = new ArrayList();
	for (int i=0; i<propertyNames.length; i++) {
		Object value = values[i];
		Type type = propertyTypes[i];
		String name = propertyNames[i];

		boolean isPropertyIncluded = i!=meta.getVersionProperty() &&
			isPropertyIncluded(value, name, type);

		if (isPropertyIncluded) {
			if ( propertyTypes[i].isComponentType() ) {
				addComponentTypedValues(name, value, (AbstractComponentType) type, list, criteria, criteriaQuery);
			}
			else {
				addPropertyTypedValue(value, type, list);
			}
		}
	}
	return (TypedValue[]) list.toArray(TYPED_VALUES);
}
 
Example 5
Source File: WrapVisitor.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
void process(Object object, EntityPersister persister) throws HibernateException {
	EntityMode entityMode = getSession().getEntityMode();
	Object[] values = persister.getPropertyValues( object, entityMode );
	Type[] types = persister.getPropertyTypes();
	processEntityPropertyValues(values, types);
	if ( isSubstitutionRequired() ) {
		persister.setPropertyValues( object, values, entityMode );
	}
}
 
Example 6
Source File: Example.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
	throws HibernateException {

	StringBuffer buf = new StringBuffer().append('(');
	EntityPersister meta = criteriaQuery.getFactory().getEntityPersister( criteriaQuery.getEntityName(criteria) );
	String[] propertyNames = meta.getPropertyNames();
	Type[] propertyTypes = meta.getPropertyTypes();
	//TODO: get all properties, not just the fetched ones!
	Object[] propertyValues = meta.getPropertyValues( entity, getEntityMode(criteria, criteriaQuery) );
	for (int i=0; i<propertyNames.length; i++) {
		Object propertyValue = propertyValues[i];
		String propertyName = propertyNames[i];

		boolean isPropertyIncluded = i!=meta.getVersionProperty() &&
			isPropertyIncluded( propertyValue, propertyName, propertyTypes[i] );
		if (isPropertyIncluded) {
			if ( propertyTypes[i].isComponentType() ) {
				appendComponentCondition(
					propertyName,
					propertyValue,
					(AbstractComponentType) propertyTypes[i],
					criteria,
					criteriaQuery,
					buf
				);
			}
			else {
				appendPropertyCondition(
					propertyName,
					propertyValue,
					criteria,
					criteriaQuery,
					buf
				);
			}
		}
	}
	if ( buf.length()==1 ) buf.append("1=1"); //yuck!
	return buf.append(')').toString();
}
 
Example 7
Source File: EntityPrinter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Renders an entity to a string.
 *
 * @param entityName the entity name
 * @param entity an actual entity object, not a proxy!
 *
 * @return the entity rendered to a string
 */
public String toString(String entityName, Object entity) throws HibernateException {
	EntityPersister entityPersister = factory.getEntityPersister( entityName );

	if ( entityPersister == null || !entityPersister.isInstance( entity ) ) {
		return entity.getClass().getName();
	}

	Map<String, String> result = new HashMap<String, String>();

	if ( entityPersister.hasIdentifierProperty() ) {
		result.put(
				entityPersister.getIdentifierPropertyName(),
				entityPersister.getIdentifierType().toLoggableString(
						entityPersister.getIdentifier( entity ),
						factory
				)
		);
	}

	Type[] types = entityPersister.getPropertyTypes();
	String[] names = entityPersister.getPropertyNames();
	Object[] values = entityPersister.getPropertyValues( entity );
	for ( int i = 0; i < types.length; i++ ) {
		if ( !names[i].startsWith( "_" ) ) {
			String strValue = values[i] == LazyPropertyInitializer.UNFETCHED_PROPERTY ?
					values[i].toString() :
					types[i].toLoggableString( values[i], factory );
			result.put( names[i], strValue );
		}
	}
	return entityName + result.toString();
}
 
Example 8
Source File: DefaultFlushEntityEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Flushes a single entity's state to the database, by scheduling
 * an update action, if necessary
 */
public void onFlushEntity(FlushEntityEvent event) throws HibernateException {
	final Object entity = event.getEntity();
	final EntityEntry entry = event.getEntityEntry();
	final EventSource session = event.getSession();
	final EntityPersister persister = entry.getPersister();
	final Status status = entry.getStatus();
	final EntityMode entityMode = session.getEntityMode();
	final Type[] types = persister.getPropertyTypes();

	final boolean mightBeDirty = entry.requiresDirtyCheck(entity);

	final Object[] values = getValues( entity, entry, entityMode, mightBeDirty, session );

	event.setPropertyValues(values);

	//TODO: avoid this for non-new instances where mightBeDirty==false
	boolean substitute = wrapCollections( session, persister, types, values);

	if ( isUpdateNecessary( event, mightBeDirty ) ) {
		substitute = scheduleUpdate( event ) || substitute;
	}

	if ( status != Status.DELETED ) {
		// now update the object .. has to be outside the main if block above (because of collections)
		if (substitute) persister.setPropertyValues( entity, values, entityMode );

		// Search for collections by reachability, updating their role.
		// We don't want to touch collections reachable from a deleted object
		if ( persister.hasCollections() ) {
			new FlushVisitor(session, entity).processEntityPropertyValues(values, types);
		}
	}

}
 
Example 9
Source File: WrapVisitor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
void process(Object object, EntityPersister persister) throws HibernateException {
	final Object[] values = persister.getPropertyValues( object );
	final Type[] types = persister.getPropertyTypes();
	processEntityPropertyValues( values, types );
	if ( isSubstitutionRequired() ) {
		persister.setPropertyValues( object, values );
	}
}
 
Example 10
Source File: DefaultDeleteEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Object[] createDeletedState(EntityPersister persister, Object[] currentState, EventSource session) {
		Type[] propTypes = persister.getPropertyTypes();
		final Object[] deletedState = new Object[propTypes.length];
//		TypeFactory.deepCopy( currentState, propTypes, persister.getPropertyUpdateability(), deletedState, session );
		boolean[] copyability = new boolean[propTypes.length];
		java.util.Arrays.fill( copyability, true );
		TypeHelper.deepCopy( currentState, propTypes, copyability, deletedState, session );
		return deletedState;
	}
 
Example 11
Source File: DefaultDeleteEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Object[] createDeletedState(EntityPersister persister, Object[] currentState, EventSource session) {
		Type[] propTypes = persister.getPropertyTypes();
		final Object[] deletedState = new Object[propTypes.length];
//		TypeFactory.deepCopy( currentState, propTypes, persister.getPropertyUpdateability(), deletedState, session );
		boolean[] copyability = new boolean[propTypes.length];
		java.util.Arrays.fill( copyability, true );
		TypeFactory.deepCopy( currentState, propTypes, copyability, deletedState, session );
		return deletedState;
	}
 
Example 12
Source File: DefaultFlushEntityEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Flushes a single entity's state to the database, by scheduling
 * an update action, if necessary
 */
public void onFlushEntity(FlushEntityEvent event) throws HibernateException {
	final Object entity = event.getEntity();
	final EntityEntry entry = event.getEntityEntry();
	final EventSource session = event.getSession();
	final EntityPersister persister = entry.getPersister();
	final Status status = entry.getStatus();
	final Type[] types = persister.getPropertyTypes();

	final boolean mightBeDirty = entry.requiresDirtyCheck( entity );

	final Object[] values = getValues( entity, entry, mightBeDirty, session );

	event.setPropertyValues( values );

	//TODO: avoid this for non-new instances where mightBeDirty==false
	boolean substitute = wrapCollections( session, persister, types, values );

	if ( isUpdateNecessary( event, mightBeDirty ) ) {
		substitute = scheduleUpdate( event ) || substitute;
	}

	if ( status != Status.DELETED ) {
		// now update the object .. has to be outside the main if block above (because of collections)
		if ( substitute ) {
			persister.setPropertyValues( entity, values );
		}

		// Search for collections by reachability, updating their role.
		// We don't want to touch collections reachable from a deleted object
		if ( persister.hasCollections() ) {
			new FlushVisitor( session, entity ).processEntityPropertyValues( values, types );
		}
	}

}
 
Example 13
Source File: DefaultDeleteEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Perform the entity deletion.  Well, as with most operations, does not
 * really perform it; just schedules an action/execution with the
 * {@link org.hibernate.engine.ActionQueue} for execution during flush.
 *
 * @param session The originating session
 * @param entity The entity to delete
 * @param entityEntry The entity's entry in the {@link PersistenceContext}
 * @param isCascadeDeleteEnabled Is delete cascading enabled?
 * @param persister The entity persister.
 * @param transientEntities A cache of already deleted entities.
 */
protected final void deleteEntity(
		final EventSource session,
		final Object entity,
		final EntityEntry entityEntry,
		final boolean isCascadeDeleteEnabled,
		final EntityPersister persister,
		final Set transientEntities) {

	if ( log.isTraceEnabled() ) {
		log.trace(
				"deleting " +
						MessageHelper.infoString( persister, entityEntry.getId(), session.getFactory() )
		);
	}

	final PersistenceContext persistenceContext = session.getPersistenceContext();
	final Type[] propTypes = persister.getPropertyTypes();
	final Object version = entityEntry.getVersion();

	final Object[] currentState;
	if ( entityEntry.getLoadedState() == null ) { //ie. the entity came in from update()
		currentState = persister.getPropertyValues( entity, session.getEntityMode() );
	}
	else {
		currentState = entityEntry.getLoadedState();
	}

	final Object[] deletedState = createDeletedState( persister, currentState, session );
	entityEntry.setDeletedState( deletedState );

	session.getInterceptor().onDelete(
			entity,
			entityEntry.getId(),
			deletedState,
			persister.getPropertyNames(),
			propTypes
	);

	// before any callbacks, etc, so subdeletions see that this deletion happened first
	persistenceContext.setEntryStatus( entityEntry, Status.DELETED );
	EntityKey key = new EntityKey( entityEntry.getId(), persister, session.getEntityMode() );

	cascadeBeforeDelete( session, persister, entity, entityEntry, transientEntities );

	new ForeignKeys.Nullifier( entity, true, false, session )
			.nullifyTransientReferences( entityEntry.getDeletedState(), propTypes );
	new Nullability( session ).checkNullability( entityEntry.getDeletedState(), persister, true );
	persistenceContext.getNullifiableEntityKeys().add( key );

	// Ensures that containing deletions happen before sub-deletions
	session.getActionQueue().addAction(
			new EntityDeleteAction(
					entityEntry.getId(),
					deletedState,
					version,
					entity,
					persister,
					isCascadeDeleteEnabled,
					session
			)
	);

	cascadeAfterDelete( session, persister, entity, transientEntities );

	// the entry will be removed after the flush, and will no longer
	// override the stale snapshot
	// This is now handled by removeEntity() in EntityDeleteAction
	//persistenceContext.removeDatabaseSnapshot(key);
}
 
Example 14
Source File: AbstractSaveEventListener.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Performs all the actual work needed to save an entity (well to get the save moved to
 * the execution queue).
 *
 * @param entity The entity to be saved
 * @param key The id to be used for saving the entity (or null, in the case of identity columns)
 * @param persister The entity's persister instance.
 * @param useIdentityColumn Should an identity column be used for id generation?
 * @param anything Generally cascade-specific information.
 * @param source The session which is the source of the current event.
 * @param requiresImmediateIdAccess Is access to the identifier required immediately
 * after the completion of the save?  persist(), for example, does not require this...
 *
 * @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 performSaveOrReplicate(
		Object entity,
		EntityKey key,
		EntityPersister persister,
		boolean useIdentityColumn,
		Object anything,
		EventSource source,
		boolean requiresImmediateIdAccess) {

	Serializable id = key == null ? null : key.getIdentifier();

	boolean shouldDelayIdentityInserts = shouldDelayIdentityInserts( requiresImmediateIdAccess, source );

	// Put a placeholder in entries, so we don't recurse back and try to save() the
	// same object again. QUESTION: should this be done before onSave() is called?
	// likewise, should it be done before onUpdate()?
	EntityEntry original = source.getPersistenceContext().addEntry(
			entity,
			Status.SAVING,
			null,
			null,
			id,
			null,
			LockMode.WRITE,
			useIdentityColumn,
			persister,
			false
	);

	cascadeBeforeSave( source, persister, entity, anything );

	Object[] values = persister.getPropertyValuesToInsert( entity, getMergeMap( anything ), source );
	Type[] types = persister.getPropertyTypes();

	boolean substitute = substituteValuesIfNecessary( entity, id, values, persister, source );

	if ( persister.hasCollections() ) {
		substitute = substitute || visitCollectionsBeforeSave( entity, id, values, types, source );
	}

	if ( substitute ) {
		persister.setPropertyValues( entity, values );
	}

	TypeHelper.deepCopy(
			values,
			types,
			persister.getPropertyUpdateability(),
			values,
			source
	);

	AbstractEntityInsertAction insert = addInsertAction(
			values, id, entity, persister, useIdentityColumn, source, shouldDelayIdentityInserts
	);

	// postpone initializing id in case the insert has non-nullable transient dependencies
	// that are not resolved until cascadeAfterSave() is executed
	cascadeAfterSave( source, persister, entity, anything );
	if ( useIdentityColumn && insert.isEarlyInsert() ) {
		if ( !EntityIdentityInsertAction.class.isInstance( insert ) ) {
			throw new IllegalStateException(
					"Insert should be using an identity column, but action is of unexpected type: " +
							insert.getClass().getName()
			);
		}
		id = ((EntityIdentityInsertAction) insert).getGeneratedId();

		insert.handleNaturalIdPostSaveNotifications( id );
	}

	EntityEntry newEntry = source.getPersistenceContext().getEntry( entity );

	if ( newEntry != original ) {
		EntityEntryExtraState extraState = newEntry.getExtraState( EntityEntryExtraState.class );
		if ( extraState == null ) {
			newEntry.addExtraState( original.getExtraState( EntityEntryExtraState.class ) );
		}
	}

	return id;
}
 
Example 15
Source File: DefaultLoadEventListener.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private Object convertCacheEntryToEntity(
		CacheEntry entry,
		Serializable entityId,
		EntityPersister persister,
		LoadEvent event,
		EntityKey entityKey) {

	final EventSource session = event.getSession();
	final SessionFactoryImplementor factory = session.getFactory();
	final EntityPersister subclassPersister;

	if ( traceEnabled ) {
		LOG.tracef(
				"Converting second-level cache entry [%s] into entity : %s",
				entry,
				MessageHelper.infoString( persister, entityId, factory )
		);
	}

	final Object entity;

	subclassPersister = factory.getEntityPersister( entry.getSubclass() );
	final Object optionalObject = event.getInstanceToLoad();
	entity = optionalObject == null
			? session.instantiate( subclassPersister, entityId )
			: optionalObject;

	// make it circular-reference safe
	TwoPhaseLoad.addUninitializedCachedEntity(
			entityKey,
			entity,
			subclassPersister,
			LockMode.NONE,
			entry.getVersion(),
			session
	);

	final PersistenceContext persistenceContext = session.getPersistenceContext();
	final Object[] values;
	final Object version;
	final boolean isReadOnly;

	final Type[] types = subclassPersister.getPropertyTypes();
	// initializes the entity by (desired) side-effect
	values = ( (StandardCacheEntryImpl) entry ).assemble(
			entity, entityId, subclassPersister, session.getInterceptor(), session
	);
	if ( ( (StandardCacheEntryImpl) entry ).isDeepCopyNeeded() ) {
		TypeHelper.deepCopy(
				values,
				types,
				subclassPersister.getPropertyUpdateability(),
				values,
				session
		);
	}
	version = Versioning.getVersion( values, subclassPersister );
	LOG.tracef( "Cached Version : %s", version );

	final Object proxy = persistenceContext.getProxy( entityKey );
	if ( proxy != null ) {
		// there is already a proxy for this impl
		// only set the status to read-only if the proxy is read-only
		isReadOnly = ( (HibernateProxy) proxy ).getHibernateLazyInitializer().isReadOnly();
	}
	else {
		isReadOnly = session.isDefaultReadOnly();
	}

	persistenceContext.addEntry(
			entity,
			( isReadOnly ? Status.READ_ONLY : Status.MANAGED ),
			values,
			null,
			entityId,
			version,
			LockMode.NONE,
			true,
			subclassPersister,
			false
	);
	subclassPersister.afterInitialize( entity, session );
	persistenceContext.initializeNonLazyCollections();

	//PostLoad is needed for EJB3
	PostLoadEvent postLoadEvent = event.getPostLoadEvent()
			.setEntity( entity )
			.setId( entityId )
			.setPersister( persister );

	for ( PostLoadEventListener listener : postLoadEventListeners( session ) ) {
		listener.onPostLoad( postLoadEvent );
	}

	return entity;
}
 
Example 16
Source File: DefaultDeleteEventListener.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Perform the entity deletion.  Well, as with most operations, does not
 * really perform it; just schedules an action/execution with the
 * {@link org.hibernate.engine.spi.ActionQueue} for execution during flush.
 *
 * @param session The originating session
 * @param entity The entity to delete
 * @param entityEntry The entity's entry in the {@link PersistenceContext}
 * @param isCascadeDeleteEnabled Is delete cascading enabled?
 * @param persister The entity persister.
 * @param transientEntities A cache of already deleted entities.
 */
protected final void deleteEntity(
		final EventSource session,
		final Object entity,
		final EntityEntry entityEntry,
		final boolean isCascadeDeleteEnabled,
		final boolean isOrphanRemovalBeforeUpdates,
		final EntityPersister persister,
		final Set transientEntities) {

	if ( LOG.isTraceEnabled() ) {
		LOG.tracev(
				"Deleting {0}",
				MessageHelper.infoString( persister, entityEntry.getId(), session.getFactory() )
		);
	}

	final PersistenceContext persistenceContext = session.getPersistenceContext();
	final Type[] propTypes = persister.getPropertyTypes();
	final Object version = entityEntry.getVersion();

	final Object[] currentState;
	if ( entityEntry.getLoadedState() == null ) {
		//ie. the entity came in from update()
		currentState = persister.getPropertyValues( entity );
	}
	else {
		currentState = entityEntry.getLoadedState();
	}

	final Object[] deletedState = createDeletedState( persister, currentState, session );
	entityEntry.setDeletedState( deletedState );

	session.getInterceptor().onDelete(
			entity,
			entityEntry.getId(),
			deletedState,
			persister.getPropertyNames(),
			propTypes
	);

	// before any callbacks, etc, so subdeletions see that this deletion happened first
	persistenceContext.setEntryStatus( entityEntry, Status.DELETED );
	final EntityKey key = session.generateEntityKey( entityEntry.getId(), persister );

	cascadeBeforeDelete( session, persister, entity, entityEntry, transientEntities );

	new ForeignKeys.Nullifier( entity, true, false, session )
			.nullifyTransientReferences( entityEntry.getDeletedState(), propTypes );
	new Nullability( session ).checkNullability( entityEntry.getDeletedState(), persister, Nullability.NullabilityCheckType.DELETE );
	persistenceContext.getNullifiableEntityKeys().add( key );

	if ( isOrphanRemovalBeforeUpdates ) {
		// TODO: The removeOrphan concept is a temporary "hack" for HHH-6484.  This should be removed once action/task
		// ordering is improved.
		session.getActionQueue().addAction(
				new OrphanRemovalAction(
						entityEntry.getId(),
						deletedState,
						version,
						entity,
						persister,
						isCascadeDeleteEnabled,
						session
				)
		);
	}
	else {
		// Ensures that containing deletions happen before sub-deletions
		session.getActionQueue().addAction(
				new EntityDeleteAction(
						entityEntry.getId(),
						deletedState,
						version,
						entity,
						persister,
						isCascadeDeleteEnabled,
						session
				)
		);
	}

	cascadeAfterDelete( session, persister, entity, transientEntities );

	// the entry will be removed after the flush, and will no longer
	// override the stale snapshot
	// This is now handled by removeEntity() in EntityDeleteAction
	//persistenceContext.removeDatabaseSnapshot(key);
}
 
Example 17
Source File: SimpleCacheKeysFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Object createNaturalIdKey(Object[] naturalIdValues, EntityPersister persister, SharedSessionContractImplementor session) {
	// natural ids always need to be wrapped
	return new NaturalIdCacheKey(naturalIdValues, persister.getPropertyTypes(), persister.getNaturalIdentifierProperties(), null, session);
}
 
Example 18
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 19
Source File: Example.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) {
	final StringBuilder buf = new StringBuilder().append( '(' );
	final EntityPersister meta = criteriaQuery.getFactory().getEntityPersister(
			criteriaQuery.getEntityName( criteria )
	);
	final String[] propertyNames = meta.getPropertyNames();
	final Type[] propertyTypes = meta.getPropertyTypes();

	final Object[] propertyValues = meta.getPropertyValues( exampleEntity );
	for ( int i=0; i<propertyNames.length; i++ ) {
		final Object propertyValue = propertyValues[i];
		final String propertyName = propertyNames[i];

		final boolean isVersionProperty = i == meta.getVersionProperty();
		if ( ! isVersionProperty && isPropertyIncluded( propertyValue, propertyName, propertyTypes[i] ) ) {
			if ( propertyTypes[i].isComponentType() ) {
				appendComponentCondition(
					propertyName,
					propertyValue,
					(CompositeType) propertyTypes[i],
					criteria,
					criteriaQuery,
					buf
				);
			}
			else {
				appendPropertyCondition(
					propertyName,
					propertyValue,
					criteria,
					criteriaQuery,
					buf
				);
			}
		}
	}

	if ( buf.length()==1 ) {
		buf.append( "1=1" );
	}

	return buf.append( ')' ).toString();
}
 
Example 20
Source File: DefaultReactiveFlushEntityEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void checkNaturalId(
		EntityPersister persister,
		EntityEntry entry,
		Object[] current,
		Object[] loaded,
		SessionImplementor session) {
	if ( persister.hasNaturalIdentifier() && entry.getStatus() != Status.READ_ONLY ) {
		if ( !persister.getEntityMetamodel().hasImmutableNaturalId() ) {
			// SHORT-CUT: if the natural id is mutable (!immutable), no need to do the below checks
			// EARLY EXIT!!!
			return;
		}

		final int[] naturalIdentifierPropertiesIndexes = persister.getNaturalIdentifierProperties();
		final Type[] propertyTypes = persister.getPropertyTypes();
		final boolean[] propertyUpdateability = persister.getPropertyUpdateability();

		final PersistenceContext persistenceContext = session.getPersistenceContextInternal();
		final Object[] snapshot = loaded == null
				? persistenceContext.getNaturalIdSnapshot( entry.getId(), persister )
				: persistenceContext.getNaturalIdHelper().extractNaturalIdValues( loaded, persister );

		for ( int i = 0; i < naturalIdentifierPropertiesIndexes.length; i++ ) {
			final int naturalIdentifierPropertyIndex = naturalIdentifierPropertiesIndexes[i];
			if ( propertyUpdateability[naturalIdentifierPropertyIndex] ) {
				// if the given natural id property is updatable (mutable), there is nothing to check
				continue;
			}

			final Type propertyType = propertyTypes[naturalIdentifierPropertyIndex];
			if ( !propertyType.isEqual( current[naturalIdentifierPropertyIndex], snapshot[i] ) ) {
				throw new HibernateException(
						String.format(
								"An immutable natural identifier of entity %s was altered from %s to %s",
								persister.getEntityName(),
								propertyTypes[naturalIdentifierPropertyIndex].toLoggableString(
										snapshot[i],
										session.getFactory()
								),
								propertyTypes[naturalIdentifierPropertyIndex].toLoggableString(
										current[naturalIdentifierPropertyIndex],
										session.getFactory()
								)
						)
				);
			}
		}
	}
}