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

The following examples show how to use org.hibernate.persister.entity.EntityPersister#getPropertyNames() . 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: StructuredCacheEntry.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Object destructure(Object structured, SessionFactoryImplementor factory) {
	final Map map = (Map) structured;
	final String subclass = (String) map.get( SUBCLASS_KEY );
	final Object version = map.get( VERSION_KEY );
	final EntityPersister subclassPersister = factory.getEntityPersister( subclass );
	final String[] names = subclassPersister.getPropertyNames();
	final Serializable[] disassembledState = new Serializable[names.length];
	for ( int i = 0; i < names.length; i++ ) {
		disassembledState[i] = (Serializable) map.get( names[i] );
	}
	return new StandardCacheEntryImpl(
		disassembledState,
		subclass,
		version
	);
}
 
Example 3
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 4
Source File: StructuredCacheEntry.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Object destructure(Object item, SessionFactoryImplementor factory) {
	Map map = (Map) item;
	boolean lazyPropertiesUnfetched = ( (Boolean) map.get("_lazyPropertiesUnfetched") ).booleanValue();
	String subclass = (String) map.get("_subclass");
	Object version = map.get("_version");
	EntityPersister subclassPersister = factory.getEntityPersister(subclass);
	String[] names = subclassPersister.getPropertyNames();
	Serializable[] state = new Serializable[names.length];
	for ( int i=0; i<names.length; i++ ) {
		state[i] = (Serializable) map.get( names[i] );
	}
	return new CacheEntry(state, subclass, lazyPropertiesUnfetched, version);
}
 
Example 5
Source File: CascadingAction.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void noCascade(
		EventSource session,
		Object child,
		Object parent,
		EntityPersister persister,
		int propertyIndex) {
	if ( child == null ) {
		return;
	}
	Type type = persister.getPropertyTypes()[propertyIndex];
	if ( type.isEntityType() ) {
		String childEntityName = ( ( EntityType ) type ).getAssociatedEntityName( session.getFactory() );

		if ( ! isInManagedState( child, session )
				&& ! ( child instanceof HibernateProxy ) //a proxy cannot be transient and it breaks ForeignKeys.isTransient
				&& ForeignKeys.isTransient( childEntityName, child, null, session ) ) {
			String parentEntiytName = persister.getEntityName();
			String propertyName = persister.getPropertyNames()[propertyIndex];
			throw new TransientObjectException(
					"object references an unsaved transient instance - " +
					"save the transient instance before flushing: " +
					parentEntiytName + "." + propertyName + " -> " + childEntityName
			);

		}
	}
}
 
Example 6
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 7
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 8
Source File: DefaultFlushEntityEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void logDirtyProperties(Serializable id, int[] dirtyProperties, EntityPersister persister) {
	if ( dirtyProperties != null && dirtyProperties.length > 0 && LOG.isTraceEnabled() ) {
		final String[] allPropertyNames = persister.getPropertyNames();
		final String[] dirtyPropertyNames = new String[dirtyProperties.length];
		for ( int i = 0; i < dirtyProperties.length; i++ ) {
			dirtyPropertyNames[i] = allPropertyNames[dirtyProperties[i]];
		}
		LOG.tracev(
				"Found dirty properties [{0}] : {1}",
				MessageHelper.infoString( persister.getEntityName(), id ),
				Arrays.toString( dirtyPropertyNames )
		);
	}
}
 
Example 9
Source File: DefaultReactiveFlushEntityEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void logDirtyProperties(Serializable id, int[] dirtyProperties, EntityPersister persister) {
	if ( dirtyProperties != null && dirtyProperties.length > 0 && LOG.isTraceEnabled() ) {
		final String[] allPropertyNames = persister.getPropertyNames();
		final String[] dirtyPropertyNames = new String[dirtyProperties.length];
		for ( int i = 0; i < dirtyProperties.length; i++ ) {
			dirtyPropertyNames[i] = allPropertyNames[dirtyProperties[i]];
		}
		LOG.tracev(
				"Found dirty properties [{0}] : {1}",
				MessageHelper.infoString( persister.getEntityName(), id ),
				Arrays.toString( dirtyPropertyNames )
		);
	}
}
 
Example 10
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 11
Source File: CascadingActions.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void noCascade(
		EventSource session,
		Object parent,
		EntityPersister persister,
		Type propertyType,
		int propertyIndex) {
	if ( propertyType.isEntityType() ) {
		Object child = persister.getPropertyValue( parent, propertyIndex );
		String childEntityName = ((EntityType) propertyType).getAssociatedEntityName( session.getFactory() );

		if ( child != null
				&& !isInManagedState( child, session )
				&& !(child instanceof HibernateProxy) //a proxy cannot be transient and it breaks ForeignKeys.isTransient
				&& ForeignKeys.isTransient( childEntityName, child, null, session ) ) {
			String parentEntityName = persister.getEntityName();
			String propertyName = persister.getPropertyNames()[propertyIndex];
			throw new TransientPropertyValueException(
					"object references an unsaved transient instance - save the transient instance before flushing",
					childEntityName,
					parentEntityName,
					propertyName
			);

		}
	}
}
 
Example 12
Source File: Example.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) {
	final EntityPersister meta = criteriaQuery.getFactory().getEntityPersister(
			criteriaQuery.getEntityName( criteria )
	);
	final String[] propertyNames = meta.getPropertyNames();
	final Type[] propertyTypes = meta.getPropertyTypes();

	final Object[] values = meta.getPropertyValues( exampleEntity );
	final List<TypedValue> list = new ArrayList<TypedValue>();
	for ( int i=0; i<propertyNames.length; i++ ) {
		final Object value = values[i];
		final Type type = propertyTypes[i];
		final String name = propertyNames[i];

		final boolean isVersionProperty = i == meta.getVersionProperty();

		if ( ! isVersionProperty && isPropertyIncluded( value, name, type ) ) {
			if ( propertyTypes[i].isComponentType() ) {
				addComponentTypedValues( name, value, (CompositeType) type, list, criteria, criteriaQuery );
			}
			else {
				addPropertyTypedValue( value, type, list );
			}
		}
	}

	return list.toArray( new TypedValue[ list.size() ] );
}
 
Example 13
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 14
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 15
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 16
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 17
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();
}