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

The following examples show how to use org.hibernate.persister.entity.EntityPersister#getNaturalIdentifierProperties() . 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: NaturalIdXrefDelegate.java    From lams with GNU General Public License v2.0 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 2
Source File: StatefulPersistenceContext.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object[] extractNaturalIdValues(Object entity, EntityPersister persister) {
	if ( entity == null ) {
		throw new AssertionFailure( "Entity from which to extract natural id value(s) cannot be null" );
	}
	if ( persister == null ) {
		throw new AssertionFailure( "Persister to use in extracting natural id value(s) cannot be null" );
	}

	final int[] naturalIdentifierProperties = persister.getNaturalIdentifierProperties();
	final Object[] naturalIdValues = new Object[naturalIdentifierProperties.length];

	for ( int i = 0; i < naturalIdentifierProperties.length; i++ ) {
		naturalIdValues[i] = persister.getPropertyValue( entity, naturalIdentifierProperties[i] );
	}

	return naturalIdValues;
}
 
Example 3
Source File: NaturalIdXrefDelegate.java    From lams with GNU General Public License v2.0 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 4
Source File: StatefulPersistenceContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object[] extractNaturalIdValues(Object[] state, EntityPersister persister) {
	final int[] naturalIdPropertyIndexes = persister.getNaturalIdentifierProperties();
	if ( state.length == naturalIdPropertyIndexes.length ) {
		return state;
	}

	final Object[] naturalIdValues = new Object[naturalIdPropertyIndexes.length];
	for ( int i = 0; i < naturalIdPropertyIndexes.length; i++ ) {
		naturalIdValues[i] = state[naturalIdPropertyIndexes[i]];
	}
	return naturalIdValues;
}
 
Example 5
Source File: StatefulPersistenceContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Object[] getNaturalIdValues(Object[] state, EntityPersister persister) {
	final int[] naturalIdPropertyIndexes = persister.getNaturalIdentifierProperties();
	final Object[] naturalIdValues = new Object[naturalIdPropertyIndexes.length];

	for ( int i = 0; i < naturalIdPropertyIndexes.length; i++ ) {
		naturalIdValues[i] = state[naturalIdPropertyIndexes[i]];
	}

	return naturalIdValues;
}
 
Example 6
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 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 7
Source File: StatefulPersistenceContext.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Object[] getNaturalIdSnapshot(Serializable id, EntityPersister persister)
throws HibernateException {
	if ( !persister.hasNaturalIdentifier() ) {
		return null;
	}

	// if the natural-id is marked as non-mutable, it is not retrieved during a
	// normal database-snapshot operation...
	int[] props = persister.getNaturalIdentifierProperties();
	boolean[] updateable = persister.getPropertyUpdateability();
	boolean allNatualIdPropsAreUpdateable = true;
	for ( int i = 0; i < props.length; i++ ) {
		if ( !updateable[ props[i] ] ) {
			allNatualIdPropsAreUpdateable = false;
			break;
		}
	}

	if ( allNatualIdPropsAreUpdateable ) {
		// do this when all the properties are updateable since there is
		// a certain likelihood that the information will already be
		// snapshot-cached.
		Object[] entitySnapshot = getDatabaseSnapshot( id, persister );
		if ( entitySnapshot == NO_ROW ) {
			return null;
		}
		Object[] naturalIdSnapshot = new Object[ props.length ];
		for ( int i = 0; i < props.length; i++ ) {
			naturalIdSnapshot[i] = entitySnapshot[ props[i] ];
		}
		return naturalIdSnapshot;
	}
	else {
		return persister.getNaturalIdentifierSnapshot( id, session );
	}
}
 
Example 8
Source File: DefaultFlushEntityEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void checkNaturalId(
		EntityPersister persister,
        Serializable identifier,
        Object[] current,
        Object[] loaded,
        EntityMode entityMode,
        SessionImplementor session) {
	if ( persister.hasNaturalIdentifier() ) {
			Object[] snapshot = null;			
		Type[] types = persister.getPropertyTypes();
		int[] props = persister.getNaturalIdentifierProperties();
		boolean[] updateable = persister.getPropertyUpdateability();
		for ( int i=0; i<props.length; i++ ) {
			int prop = props[i];
			if ( !updateable[prop] ) {
					Object loadedVal;
					if ( loaded == null ) {
						if ( snapshot == null) {
							snapshot = session.getPersistenceContext().getNaturalIdSnapshot( identifier, persister );
						}
						loadedVal = snapshot[i];
					} else {
						loadedVal = loaded[prop];
					}
					if ( !types[prop].isEqual( current[prop], loadedVal, entityMode ) ) {						
					throw new HibernateException(
							"immutable natural identifier of an instance of " +
							persister.getEntityName() +
							" was altered"
						);
				}
			}
		}
	}
}
 
Example 9
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()
								)
						)
				);
			}
		}
	}
}
 
Example 10
Source File: StatefulPersistenceContext.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Object[] getNaturalIdSnapshot(Serializable id, EntityPersister persister) throws HibernateException {
	if ( !persister.hasNaturalIdentifier() ) {
		return null;
	}

	persister = locateProperPersister( persister );

	// let's first see if it is part of the natural id cache...
	final Object[] cachedValue = naturalIdHelper.findCachedNaturalId( persister, id );
	if ( cachedValue != null ) {
		return cachedValue;
	}

	// check to see if the natural id is mutable/immutable
	if ( persister.getEntityMetamodel().hasImmutableNaturalId() ) {
		// an immutable natural-id is not retrieved during a normal database-snapshot operation...
		final Object[] dbValue = persister.getNaturalIdentifierSnapshot( id, session );
		naturalIdHelper.cacheNaturalIdCrossReferenceFromLoad(
				persister,
				id,
				dbValue
		);
		return dbValue;
	}
	else {
		// for a mutable natural there is a likelihood that the the information will already be
		// snapshot-cached.
		final int[] props = persister.getNaturalIdentifierProperties();
		final Object[] entitySnapshot = getDatabaseSnapshot( id, persister );
		if ( entitySnapshot == NO_ROW || entitySnapshot == null ) {
			return null;
		}

		final Object[] naturalIdSnapshotSubSet = new Object[ props.length ];
		for ( int i = 0; i < props.length; i++ ) {
			naturalIdSnapshotSubSet[i] = entitySnapshot[ props[i] ];
		}
		naturalIdHelper.cacheNaturalIdCrossReferenceFromLoad(
				persister,
				id,
				naturalIdSnapshotSubSet
		);
		return naturalIdSnapshotSubSet;
	}
}
 
Example 11
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Checks to see if the CriteriaImpl is a naturalId lookup that can be done via
 * NaturalIdLoadAccess
 *
 * @param criteria The criteria to check as a complete natural identifier lookup.
 *
 * @return A fully configured NaturalIdLoadAccess or null, if null is returned the standard CriteriaImpl execution
 * should be performed
 */
private NaturalIdLoadAccess tryNaturalIdLoadAccess(CriteriaImpl criteria) {
	// See if the criteria lookup is by naturalId
	if ( !criteria.isLookupByNaturalKey() ) {
		return null;
	}

	final String entityName = criteria.getEntityOrClassName();
	final EntityPersister entityPersister = getFactory().getMetamodel().entityPersister( entityName );

	// Verify the entity actually has a natural id, needed for legacy support as NaturalIdentifier criteria
	// queries did no natural id validation
	if ( !entityPersister.hasNaturalIdentifier() ) {
		return null;
	}

	// Since isLookupByNaturalKey is true there can be only one CriterionEntry and getCriterion() will
	// return an instanceof NaturalIdentifier
	final CriterionEntry criterionEntry = criteria.iterateExpressionEntries().next();
	final NaturalIdentifier naturalIdentifier = (NaturalIdentifier) criterionEntry.getCriterion();

	final Map<String, Object> naturalIdValues = naturalIdentifier.getNaturalIdValues();
	final int[] naturalIdentifierProperties = entityPersister.getNaturalIdentifierProperties();

	// Verify the NaturalIdentifier criterion includes all naturalId properties, first check that the property counts match
	if ( naturalIdentifierProperties.length != naturalIdValues.size() ) {
		return null;
	}

	final String[] propertyNames = entityPersister.getPropertyNames();
	final NaturalIdLoadAccess naturalIdLoader = this.byNaturalId( entityName );

	// Build NaturalIdLoadAccess and in the process verify all naturalId properties were specified
	for ( int naturalIdentifierProperty : naturalIdentifierProperties ) {
		final String naturalIdProperty = propertyNames[naturalIdentifierProperty];
		final Object naturalIdValue = naturalIdValues.get( naturalIdProperty );

		if ( naturalIdValue == null ) {
			// A NaturalId property is missing from the critera query, can't use NaturalIdLoadAccess
			return null;
		}

		naturalIdLoader.using( naturalIdProperty, naturalIdValue );
	}

	// Criteria query contains a valid naturalId, use the new API
	log.warn(
			"Session.byNaturalId(" + entityName
					+ ") should be used for naturalId queries instead of Restrictions.naturalId() from a Criteria"
	);

	return naturalIdLoader;
}
 
Example 12
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 13
Source File: DefaultCacheKeysFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public static Object staticCreateNaturalIdKey(Object[] naturalIdValues, EntityPersister persister, SharedSessionContractImplementor session) {
	return new NaturalIdCacheKey( naturalIdValues,  persister.getPropertyTypes(), persister.getNaturalIdentifierProperties(), persister.getRootEntityName(), session );
}
 
Example 14
Source File: ResolveNaturalIdEvent.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public ResolveNaturalIdEvent(
		Map<String, Object> naturalIdValues,
		EntityPersister entityPersister,
		LockOptions lockOptions,
		EventSource source) {
	super( source );

	if ( entityPersister == null ) {
		throw new IllegalArgumentException( "EntityPersister is required for loading" );
	}

	if ( ! entityPersister.hasNaturalIdentifier() ) {
		throw new HibernateException( "Entity did not define a natural-id" );
	}

	if ( naturalIdValues == null || naturalIdValues.isEmpty() ) {
		throw new IllegalArgumentException( "natural-id to load is required" );
	}

	if ( entityPersister.getNaturalIdentifierProperties().length != naturalIdValues.size() ) {
		throw new HibernateException(
				String.format(
					"Entity [%s] defines its natural-id with %d properties but only %d were specified",
					entityPersister.getEntityName(),
					entityPersister.getNaturalIdentifierProperties().length,
					naturalIdValues.size()
				)
		);
	}

	if ( lockOptions.getLockMode() == LockMode.WRITE ) {
		throw new IllegalArgumentException( "Invalid lock mode for loading" );
	}
	else if ( lockOptions.getLockMode() == null ) {
		lockOptions.setLockMode( DEFAULT_LOCK_MODE );
	}

	this.entityPersister = entityPersister;
	this.naturalIdValues = naturalIdValues;
	this.lockOptions = lockOptions;

	int[] naturalIdPropertyPositions = entityPersister.getNaturalIdentifierProperties();
	orderedNaturalIdValues = new Object[naturalIdPropertyPositions.length];
	int i = 0;
	for ( int position : naturalIdPropertyPositions ) {
		final String propertyName = entityPersister.getPropertyNames()[position];
		if ( ! naturalIdValues.containsKey( propertyName ) ) {
			throw new HibernateException(
					String.format( "No value specified for natural-id property %s#%s", getEntityName(), propertyName )
			);
		}
		orderedNaturalIdValues[i++] = naturalIdValues.get( entityPersister.getPropertyNames()[position] );
	}
}
 
Example 15
Source File: DefaultFlushEntityEventListener.java    From lams with GNU General Public License v2.0 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 Object[] snapshot = loaded == null
				? session.getPersistenceContext().getNaturalIdSnapshot( entry.getId(), persister )
				: session.getPersistenceContext().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()
								)
						)
				);
			}
		}
	}
}
 
Example 16
Source File: NaturalIdXrefDelegate.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Invariant validate of the natural id.  Checks include<ul>
 *     <li>that the entity defines a natural id</li>
 *     <li>the number of natural id values matches the expected number</li>
 * </ul>
 *
 * @param persister The persister representing the entity type.
 * @param naturalIdValues The natural id values
 */
protected void validateNaturalId(EntityPersister persister, Object[] naturalIdValues) {
	if ( !persister.hasNaturalIdentifier() ) {
		throw new IllegalArgumentException( "Entity did not define a natrual-id" );
	}
	if ( persister.getNaturalIdentifierProperties().length != naturalIdValues.length ) {
		throw new IllegalArgumentException( "Mismatch between expected number of natural-id values and found." );
	}
}