1 package org.hibernate.id; 2 3 import java.io.Serializable ; 4 import java.util.Properties ; 5 6 import org.hibernate.HibernateException; 7 import org.hibernate.MappingException; 8 import org.hibernate.Session; 9 import org.hibernate.TransientObjectException; 10 import org.hibernate.dialect.Dialect; 11 import org.hibernate.engine.ForeignKeys; 12 import org.hibernate.engine.SessionImplementor; 13 import org.hibernate.type.EntityType; 14 import org.hibernate.type.Type; 15 16 26 public class ForeignGenerator implements IdentifierGenerator, Configurable { 27 28 private String propertyName; 29 private String entityName; 30 31 34 public Serializable generate(SessionImplementor sessionImplementor, Object object) 35 throws HibernateException { 36 37 Session session = (Session) sessionImplementor; 38 39 Object associatedObject = sessionImplementor.getFactory() 40 .getClassMetadata( entityName ) 41 .getPropertyValue( object, propertyName, session.getEntityMode() ); 42 43 if ( associatedObject == null ) { 44 throw new IdentifierGenerationException( 45 "attempted to assign id from null one-to-one property: " + 46 propertyName 47 ); 48 } 49 50 EntityType type = (EntityType) sessionImplementor.getFactory() 51 .getClassMetadata( entityName ) 52 .getPropertyType( propertyName ); 53 54 Serializable id; 55 try { 56 id = ForeignKeys.getEntityIdentifierIfNotUnsaved( 57 type.getAssociatedEntityName(), 58 associatedObject, 59 sessionImplementor 60 ); 61 } 62 catch (TransientObjectException toe) { 63 id = session.save(associatedObject); 64 } 65 66 if ( session.contains(object) ) { 67 return IdentifierGeneratorFactory.SHORT_CIRCUIT_INDICATOR; 69 } 71 return id; 72 } 73 74 77 public void configure(Type type, Properties params, Dialect d) 78 throws MappingException { 79 80 propertyName = params.getProperty("property"); 81 entityName = params.getProperty(ENTITY_NAME); 82 if (propertyName==null) throw new MappingException( 83 "param named \"property\" is required for foreign id generation strategy" 84 ); 85 } 86 87 } 88 | Popular Tags |