FileDocCategorySizeDatePackage
ForeignGenerator.javaAPI DocHibernate 3.2.52684Tue Jan 10 11:54:36 GMT 2006org.hibernate.id

ForeignGenerator

public class ForeignGenerator extends Object implements Configurable, IdentifierGenerator
foreign

An Identifier generator that uses the value of the id property of an associated object

One mapping parameter is required: property.
author
Gavin King

Fields Summary
private String
propertyName
private String
entityName
Constructors Summary
Methods Summary
public voidconfigure(org.hibernate.type.Type type, java.util.Properties params, org.hibernate.dialect.Dialect d)

see
org.hibernate.id.Configurable#configure(org.hibernate.type.Type, java.util.Properties, org.hibernate.dialect.Dialect)


		propertyName = params.getProperty("property");
		entityName = params.getProperty(ENTITY_NAME);
		if (propertyName==null) throw new MappingException(
			"param named \"property\" is required for foreign id generation strategy"
		);
	
public java.io.Serializablegenerate(org.hibernate.engine.SessionImplementor sessionImplementor, java.lang.Object object)

see
org.hibernate.id.IdentifierGenerator#generate(org.hibernate.engine.SessionImplementor, java.lang.Object)

		
		Session session = (Session) sessionImplementor;

		Object associatedObject = sessionImplementor.getFactory()
		        .getClassMetadata( entityName )
		        .getPropertyValue( object, propertyName, session.getEntityMode() );
		
		if ( associatedObject == null ) {
			throw new IdentifierGenerationException(
					"attempted to assign id from null one-to-one property: " + 
					propertyName
				);
		}
		
		EntityType type = (EntityType) sessionImplementor.getFactory()
        	.getClassMetadata( entityName )
        	.getPropertyType( propertyName );

		Serializable id;
		try {
			id = ForeignKeys.getEntityIdentifierIfNotUnsaved(
					type.getAssociatedEntityName(), 
					associatedObject, 
					sessionImplementor
				); 
		}
		catch (TransientObjectException toe) {
			id = session.save( type.getAssociatedEntityName(), associatedObject );
		}

		if ( session.contains(object) ) {
			//abort the save (the object is already saved by a circular cascade)
			return IdentifierGeneratorFactory.SHORT_CIRCUIT_INDICATOR;
			//throw new IdentifierGenerationException("save associated object first, or disable cascade for inverse association");
		}
		return id;