package org.hibernate.id;
import java.io.Serializable;
import java.util.Properties;
import org.hibernate.MappingException;
import org.hibernate.Session;
import org.hibernate.TransientObjectException;
import org.hibernate.engine.internal.ForeignKeys;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.loader.PropertyPath;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
import static org.hibernate.internal.CoreLogging.logger;
import static org.hibernate.internal.CoreLogging.messageLogger;
public class ForeignGenerator implements IdentifierGenerator, Configurable {
private static final CoreMessageLogger LOG = messageLogger( ForeignGenerator.class );
private String entityName;
private String propertyName;
public String getEntityName() {
return entityName;
}
public String getPropertyName() {
return propertyName;
}
public String getRole() {
return getEntityName() + '.' + getPropertyName();
}
@Override
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
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" );
}
}
@Override
public Serializable generate(SharedSessionContractImplementor sessionImplementor, Object object) {
final Session session = ( Session ) sessionImplementor;
final EntityPersister persister = sessionImplementor.getFactory().getMetamodel().entityPersister( entityName );
Object associatedObject = persister.getPropertyValue( object, propertyName );
if ( associatedObject == null ) {
throw new IdentifierGenerationException(
"attempted to assign id from null one-to-one property [" + getRole() + "]"
);
}
final EntityType foreignValueSourceType;
final Type propertyType = persister.getPropertyType( propertyName );
if ( propertyType.isEntityType() ) {
foreignValueSourceType = (EntityType) propertyType;
}
else {
foreignValueSourceType = (EntityType) persister.getPropertyType( PropertyPath.IDENTIFIER_MAPPER_PROPERTY + "." + propertyName );
}
Serializable id;
try {
id = ForeignKeys.getEntityIdentifierIfNotUnsaved(
foreignValueSourceType.getAssociatedEntityName(),
associatedObject,
sessionImplementor
);
}
catch (TransientObjectException toe) {
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"ForeignGenerator detected a transient entity [%s]",
foreignValueSourceType.getAssociatedEntityName()
);
}
id = session.save( foreignValueSourceType.getAssociatedEntityName(), associatedObject );
}
if ( session.contains( entityName, object ) ) {
return IdentifierGeneratorHelper.SHORT_CIRCUIT_INDICATOR;
}
return id;
}
}