public SecondPass getSecondPass( final Ejb3JoinColumn[] fkJoinColumns, final Ejb3JoinColumn[] keyColumns, final Ejb3JoinColumn[] inverseColumns, final Ejb3Column[] elementColumns, final Ejb3Column[] mapKeyColumns, final Ejb3JoinColumn[] mapKeyManyToManyColumns, final boolean isEmbedded, final XProperty property, final XClass collType, final boolean ignoreNotFound, final boolean unique, final TableBinder assocTableBinder, final Mappings mappings) { return new CollectionSecondPass( mappings, collection ) { @Override public void secondPass(java.util.Map persistentClasses, java.util.Map inheritedMetas) throws MappingException { bindStarToManySecondPass( persistentClasses, collType, fkJoinColumns, keyColumns, inverseColumns, elementColumns, isEmbedded, property, unique, assocTableBinder, ignoreNotFound, mappings ); } }; }
private static void bindCollectionSecondPass( Collection collValue, PersistentClass collectionEntity, Ejb3JoinColumn[] joinColumns, boolean cascadeDeleteEnabled, XProperty property, Mappings mappings) { try { BinderHelper.createSyntheticPropertyReference( joinColumns, collValue.getOwner(), collectionEntity, collValue, false, mappings ); } catch (AnnotationException ex) { throw new AnnotationException( "Unable to map collection " + collectionEntity.getClassName() + "." + property.getName(), ex ); } SimpleValue key = buildCollectionKey( collValue, joinColumns, cascadeDeleteEnabled, property, mappings ); if ( property.isAnnotationPresent( ElementCollection.class ) && joinColumns.length > 0 ) { joinColumns[0].setJPA2ElementCollection( true ); } TableBinder.bindFk( collValue.getOwner(), collectionEntity, joinColumns, key, false, mappings ); }
public static void bindNamedStoredProcedureQuery(NamedStoredProcedureQuery annotation, Mappings mappings, boolean isDefault) { if ( annotation == null ) { return; } if ( BinderHelper.isEmptyAnnotationValue( annotation.name() ) ) { throw new AnnotationException( "A named query must have a name when used in class or package level" ); } final NamedProcedureCallDefinition def = new NamedProcedureCallDefinition( annotation ); if(isDefault){ mappings.addDefaultNamedProcedureCallDefinition( def ); } else{ mappings.addNamedProcedureCallDefinition( def ); } LOG.debugf( "Bound named stored procedure query : %s => %s", def.getRegisteredName(), def.getProcedureName() ); }
public void afterConfigurationBuilt(Mappings mappings, Dialect dialect) { super.afterConfigurationBuilt( mappings, dialect ); // Oracle and Postgres do not have year() functions, so we need to // redefine the 'User.person.yob' formula // // consider temporary until we add the capability to define // mapping foprmulas which can use dialect-registered functions... PersistentClass user = mappings.getClass( User.class.getName() ); org.hibernate.mapping.Property personProperty = user.getProperty( "person" ); Component component = ( Component ) personProperty.getValue(); Formula f = ( Formula ) component.getProperty( "yob" ).getValue().getColumnIterator().next(); SQLFunction yearFunction = ( SQLFunction ) dialect.getFunctions().get( "year" ); if ( yearFunction == null ) { // the dialect not know to support a year() function, so rely on the // ANSI SQL extract function f.setFormula( "extract( year from dob )"); } else { List args = new ArrayList(); args.add( "dob" ); f.setFormula( yearFunction.render( args, null ) ); } }
public Configuration buildSessionFactory(Database database) { try { Configuration configuration = new Configuration(); setupConnection(configuration); setupConfigurationProperties(configuration); Mappings mappings = configuration.createMappings(); //Class Mapping classMapping(database, mappings); //One2Many Mapping o2mMapping(database, configuration, mappings); //TODO //mappings.addSecondPass(new ToOneFkSecondPass(?)); return configuration; } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } }
protected void setPKColumnGenerator(Mappings mappings, RootClass clazz, Table tab, com.manydesigns.portofino.model.database.Column column, SimpleValue id, Generator generator) { if (column.isAutoincrement()) { manageIdentityGenerator(mappings, tab, id); } else if (generator != null) { if (generator instanceof SequenceGenerator) { manageSequenceGenerator(mappings, tab, id, (SequenceGenerator) generator); } else if (generator instanceof com.manydesigns.portofino.model.database.TableGenerator) { manageTableGenerator(mappings, tab, id, (com.manydesigns.portofino.model.database.TableGenerator) generator); } else if (generator instanceof com.manydesigns.portofino.model.database.IncrementGenerator){ manageIncrementGenerator(mappings, tab, id, clazz.getEntityName()); } } }
private void manageIdentityGenerator(Mappings mappings, Table tab, SimpleValue id) { id.setIdentifierGeneratorStrategy(PortofinoIdentityGenerator.class.getName()); //"identity"); Properties params = new Properties(); params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, mappings.getObjectNameNormalizer()); if (mappings.getSchemaName() != null) { params.setProperty( PersistentIdentifierGenerator.SCHEMA, mappings.getObjectNameNormalizer().normalizeIdentifierQuoting(mappings.getSchemaName())); } if (mappings.getCatalogName() != null) { params.setProperty( PersistentIdentifierGenerator.CATALOG, mappings.getObjectNameNormalizer().normalizeIdentifierQuoting(mappings.getCatalogName())); } id.setIdentifierGeneratorProperties(params); id.setNullValue(null); }
private void manageTableGenerator(Mappings mappings, Table tab, SimpleValue id, com.manydesigns.portofino.model.database.TableGenerator generator) { id.setIdentifierGeneratorStrategy("enhanced-table"); Properties params = new Properties(); params.put(TableGenerator.TABLE, tab); params.put(TableGenerator.TABLE_PARAM, quoteIdentifier(generator.getTable())); params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, mappings.getObjectNameNormalizer()); params.put(TableGenerator.SEGMENT_COLUMN_PARAM, quoteIdentifier(generator.getKeyColumn())); params.put(TableGenerator.SEGMENT_VALUE_PARAM, generator.getKeyValue()); params.put(TableGenerator.VALUE_COLUMN_PARAM, quoteIdentifier(generator.getValueColumn())); params.setProperty( TableGenerator.SCHEMA, quoteIdentifier(tab.getSchema())); id.setIdentifierGeneratorProperties(params); id.setNullValue(null); }
public Configuration buildSessionFactory(Database database) { try { Configuration configuration = new Configuration(); setupConnection(configuration); setupConfigurationProperties(configuration); Mappings mappings = configuration.createMappings(); //Class Mapping classMapping(database, mappings); //One2Many Mapping o2mMapping(database, configuration, mappings); //Many2One Mapping m2oMapping(database, configuration, mappings); return configuration; } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } }
private void manageTableGenerator(Mappings mappings, Table tab, SimpleValue id, com.manydesigns.portofino.model.database.TableGenerator generator) { id.setIdentifierGeneratorStrategy("enhanced-table"); Properties params = new Properties(); params.put(TableGenerator.TABLE, tab); params.put(TableGenerator.TABLE_PARAM, escapeName(generator.getTable())); params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, mappings.getObjectNameNormalizer()); params.put(TableGenerator.SEGMENT_COLUMN_PARAM, escapeName(generator.getKeyColumn())); params.put(TableGenerator.SEGMENT_VALUE_PARAM, generator.getKeyValue()); params.put(TableGenerator.VALUE_COLUMN_PARAM,escapeName(generator.getValueColumn())); params.setProperty( TableGenerator.SCHEMA,escapeName(tab.getSchema())); id.setIdentifierGeneratorProperties(params); id.setNullValue(null); }
@Override public SecondPass getSecondPass( final Ejb3JoinColumn[] fkJoinColumns, final Ejb3JoinColumn[] keyColumns, final Ejb3JoinColumn[] inverseColumns, final Ejb3Column[] elementColumns, Ejb3Column[] mapKeyColumns, final Ejb3JoinColumn[] mapKeyManyToManyColumns, final boolean isEmbedded, final XProperty property, final XClass collType, final boolean ignoreNotFound, final boolean unique, final TableBinder assocTableBinder, final Mappings mappings) { return new CollectionSecondPass( mappings, ListBinder.this.collection ) { @Override public void secondPass(Map persistentClasses, Map inheritedMetas) throws MappingException { bindStarToManySecondPass( persistentClasses, collType, fkJoinColumns, keyColumns, inverseColumns, elementColumns, isEmbedded, property, unique, assocTableBinder, ignoreNotFound, mappings ); bindIndex( mappings ); } }; }
private void bindIndex(final Mappings mappings) { if ( !indexColumn.isImplicit() ) { PropertyHolder valueHolder = PropertyHolderBuilder.buildPropertyHolder( this.collection, StringHelper.qualify( this.collection.getRole(), "key" ), null, null, propertyHolder, mappings ); List list = (List) this.collection; if ( !list.isOneToMany() ) indexColumn.forceNotNull(); indexColumn.setPropertyHolder( valueHolder ); SimpleValueBinder value = new SimpleValueBinder(); value.setColumns( new Ejb3Column[] { indexColumn } ); value.setExplicitType( "integer" ); value.setMappings( mappings ); SimpleValue indexValue = value.make(); indexColumn.linkWithValue( indexValue ); list.setIndex( indexValue ); list.setBaseIndex( indexColumn.getBase() ); if ( list.isOneToMany() && !list.getKey().isNullable() && !list.isInverse() ) { String entityName = ( (OneToMany) list.getElement() ).getReferencedEntityName(); PersistentClass referenced = mappings.getClass( entityName ); IndexBackref ib = new IndexBackref(); ib.setName( '_' + propertyName + "IndexBackref" ); ib.setUpdateable( false ); ib.setSelectable( false ); ib.setCollectionRole( list.getRole() ); ib.setEntityName( list.getOwner().getEntityName() ); ib.setValue( list.getIndex() ); referenced.addProperty( ib ); } } else { Collection coll = this.collection; throw new AnnotationException( "List/array has to be annotated with an @OrderColumn (or @IndexColumn): " + coll.getRole() ); } }
public static Table buildAndFillTable( String schema, String catalog, ObjectNameSource nameSource, ObjectNameNormalizer.NamingStrategyHelper namingStrategyHelper, boolean isAbstract, List<UniqueConstraintHolder> uniqueConstraints, String constraints, Table denormalizedSuperTable, Mappings mappings, String subselect) { return buildAndFillTable( schema, catalog, nameSource, namingStrategyHelper, isAbstract, uniqueConstraints, null, constraints , denormalizedSuperTable, mappings, subselect); }
public static void addIndexes(Table hibTable, Index[] indexes, Mappings mappings) { for (Index index : indexes) { //no need to handle inSecondPass here since it is only called from EntityBinder mappings.addSecondPass( new IndexOrUniqueKeySecondPass( hibTable, index.name(), index.columnNames(), mappings ) ); } }
public EntityBinder( Entity ejb3Ann, org.hibernate.annotations.Entity hibAnn, XClass annotatedClass, PersistentClass persistentClass, Mappings mappings) { this.mappings = mappings; this.persistentClass = persistentClass; this.annotatedClass = annotatedClass; bindEjb3Annotation( ejb3Ann ); bindHibernateAnnotation( hibAnn ); }
private void bindJoinToPersistentClass(Join join, Ejb3JoinColumn[] ejb3JoinColumns, Mappings mappings) { SimpleValue key = new DependantValue( mappings, join.getTable(), persistentClass.getIdentifier() ); join.setKey( key ); setFKNameIfDefined( join ); key.setCascadeDeleteEnabled( false ); TableBinder.bindFk( persistentClass, null, ejb3JoinColumns, key, false, mappings ); join.createPrimaryKey(); join.createForeignKey(); persistentClass.addJoin( join ); }
@Override public SecondPass getSecondPass( final Ejb3JoinColumn[] fkJoinColumns, final Ejb3JoinColumn[] keyColumns, final Ejb3JoinColumn[] inverseColumns, final Ejb3Column[] elementColumns, final Ejb3Column[] mapKeyColumns, final Ejb3JoinColumn[] mapKeyManyToManyColumns, final boolean isEmbedded, final XProperty property, final XClass collType, final boolean ignoreNotFound, final boolean unique, final TableBinder assocTableBinder, final Mappings mappings) { return new CollectionSecondPass( mappings, MapBinder.this.collection ) { public void secondPass(Map persistentClasses, Map inheritedMetas) throws MappingException { bindStarToManySecondPass( persistentClasses, collType, fkJoinColumns, keyColumns, inverseColumns, elementColumns, isEmbedded, property, unique, assocTableBinder, ignoreNotFound, mappings ); bindKeyFromAssociationTable( collType, persistentClasses, mapKeyPropertyName, property, isEmbedded, mappings, mapKeyColumns, mapKeyManyToManyColumns, inverseColumns != null ? inverseColumns[0].getPropertyName() : null ); } }; }
public static void bindQuery(NamedQuery queryAnn, Mappings mappings, boolean isDefault) { if ( queryAnn == null ) return; if ( BinderHelper.isEmptyAnnotationValue( queryAnn.name() ) ) { throw new AnnotationException( "A named query must have a name when used in class or package level" ); } //EJBQL Query QueryHintDefinition hints = new QueryHintDefinition( queryAnn.hints() ); String queryName = queryAnn.query(); NamedQueryDefinition queryDefinition = new NamedQueryDefinitionBuilder( queryAnn.name() ) .setLockOptions( hints.determineLockOptions( queryAnn ) ) .setQuery( queryName ) .setCacheable( hints.getBoolean( queryName, QueryHints.CACHEABLE ) ) .setCacheRegion( hints.getString( queryName, QueryHints.CACHE_REGION ) ) .setTimeout( hints.getTimeout( queryName ) ) .setFetchSize( hints.getInteger( queryName, QueryHints.FETCH_SIZE ) ) .setFlushMode( hints.getFlushMode( queryName ) ) .setCacheMode( hints.getCacheMode( queryName ) ) .setReadOnly( hints.getBoolean( queryName, QueryHints.READ_ONLY ) ) .setComment( hints.getString( queryName, QueryHints.COMMENT ) ) .setParameterTypes( null ) .createNamedQueryDefinition(); if ( isDefault ) { mappings.addDefaultQuery( queryDefinition.getName(), queryDefinition ); } else { mappings.addQuery( queryDefinition.getName(), queryDefinition ); } if ( LOG.isDebugEnabled() ) { LOG.debugf( "Binding named query: %s => %s", queryDefinition.getName(), queryDefinition.getQueryString() ); } }
public static void bindNativeQueries( org.hibernate.annotations.NamedNativeQueries queriesAnn, Mappings mappings ) { if ( queriesAnn == null ) return; for (org.hibernate.annotations.NamedNativeQuery q : queriesAnn.value()) { bindNativeQuery( q, mappings ); } }
public static void bindQuery(org.hibernate.annotations.NamedQuery queryAnn, Mappings mappings) { if ( queryAnn == null ) return; if ( BinderHelper.isEmptyAnnotationValue( queryAnn.name() ) ) { throw new AnnotationException( "A named query must have a name when used in class or package level" ); } FlushMode flushMode; flushMode = getFlushMode( queryAnn.flushMode() ); NamedQueryDefinition query = new NamedQueryDefinitionBuilder().setName( queryAnn.name() ) .setQuery( queryAnn.query() ) .setCacheable( queryAnn.cacheable() ) .setCacheRegion( BinderHelper.isEmptyAnnotationValue( queryAnn.cacheRegion() ) ? null : queryAnn.cacheRegion() ) .setTimeout( queryAnn.timeout() < 0 ? null : queryAnn.timeout() ) .setFetchSize( queryAnn.fetchSize() < 0 ? null : queryAnn.fetchSize() ) .setFlushMode( flushMode ) .setCacheMode( getCacheMode( queryAnn.cacheMode() ) ) .setReadOnly( queryAnn.readOnly() ) .setComment( BinderHelper.isEmptyAnnotationValue( queryAnn.comment() ) ? null : queryAnn.comment() ) .setParameterTypes( null ) .createNamedQueryDefinition(); mappings.addQuery( query.getName(), query ); if ( LOG.isDebugEnabled() ) { LOG.debugf( "Binding named query: %s => %s", query.getName(), query.getQueryString() ); } }
public static void bindSqlResultsetMappings(SqlResultSetMappings ann, Mappings mappings, boolean isDefault) { if ( ann == null ) return; for (SqlResultSetMapping rs : ann.value()) { //no need to handle inSecondPass mappings.addSecondPass( new ResultsetMappingSecondPass( rs, mappings, true ) ); } }
@Override public void prepare( JdbcServices jdbcServices, JdbcConnectionAccess connectionAccess, Mappings mappings, Mapping mapping, Map settings) { this.catalog = ConfigurationHelper.getString( CATALOG, settings, ConfigurationHelper.getString( AvailableSettings.DEFAULT_CATALOG, settings ) ); this.schema = ConfigurationHelper.getString( SCHEMA, settings, ConfigurationHelper.getString( AvailableSettings.DEFAULT_SCHEMA, settings ) ); this.cleanUpTables = ConfigurationHelper.getBoolean( CLEAN_UP_ID_TABLES, settings, false ); final Iterator<PersistentClass> entityMappings = mappings.iterateClasses(); final List<Table> idTableDefinitions = new ArrayList<Table>(); while ( entityMappings.hasNext() ) { final PersistentClass entityMapping = entityMappings.next(); final Table idTableDefinition = generateIdTableDefinition( entityMapping ); idTableDefinitions.add( idTableDefinition ); } exportTableDefinitions( idTableDefinitions, jdbcServices, connectionAccess, mappings, mapping ); }
public void afterConfigurationBuilt(Mappings mappings, Dialect dialect) { super.afterConfigurationBuilt( mappings, dialect ); Collection children = mappings.getCollection( Parent.class.getName() + ".children" ); Component childComponents = ( Component ) children.getElement(); Formula f = ( Formula ) childComponents.getProperty( "bioLength" ).getValue().getColumnIterator().next(); SQLFunction lengthFunction = ( SQLFunction ) dialect.getFunctions().get( "length" ); if ( lengthFunction != null ) { ArrayList args = new ArrayList(); args.add( "bio" ); f.setFormula( lengthFunction.render( args, null ) ); } }
private Mappings classMapping(Database database, Mappings mappings) { for (Schema schema : database.getSchemas()) { for (com.manydesigns.portofino.model.database.Table aTable : schema.getTables()) { logger.debug("Class - {}", aTable.getQualifiedName()); com.manydesigns.portofino.model.database.PrimaryKey primaryKey = aTable.getPrimaryKey(); if (primaryKey == null) { logger.debug("Skipping table without primary key: {}", aTable.getQualifiedName()); continue; } if (!primaryKey.isValid()) { logger.debug("Skipping table with invalid primary key: {}", aTable.getQualifiedName()); continue; } RootClass clazz = createTableMapping(mappings, aTable); if(clazz != null) { mappings.addClass(clazz); mappings.addImport(clazz.getEntityName(), clazz.getEntityName()); } } } return mappings; }
private void o2mMapping(Database database, Configuration configuration, Mappings mappings) { for (Schema schema : database.getSchemas()) { for (com.manydesigns.portofino.model.database.Table aTable : schema.getTables()) { for (ForeignKey rel : aTable.getOneToManyRelationships()) { logger.debug(MessageFormat.format("One to many - {0} {1}", aTable.getQualifiedName(), rel.getName())); createO2M(configuration, mappings, rel); } } } }
protected Column createColumn(Mappings mappings, Table tab, com.manydesigns.portofino.model.database.Column column) { Column col = new Column(); col.setName(quoteIdentifier(column.getColumnName())); if(column.getLength() != null) { col.setLength(column.getLength()); col.setPrecision(column.getLength()); } if(column.getScale() != null) { col.setScale(column.getScale()); } col.setNullable(column.isNullable()); String columnType = column.getColumnType(); int jdbcType = column.getJdbcType(); col.setSqlTypeCode(jdbcType); col.setSqlType(columnType); SimpleValue value = new SimpleValue(mappings, tab); if (!setHibernateType(value, column)) { logger.error("Skipping column {}", column.getQualifiedName()); return null; } value.addColumn(col); tab.addColumn(col); mappings.addColumnBinding(column.getColumnName(), col, tab); return col; }
private void manageIncrementGenerator(Mappings mappings, Table tab, SimpleValue id, String entityName) { id.setIdentifierGeneratorStrategy("increment"); Properties params = new Properties(); params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, mappings.getObjectNameNormalizer()); params.setProperty(PersistentIdentifierGenerator.SCHEMA, quoteIdentifier(tab.getSchema())); params.put(IncrementGenerator.ENTITY_NAME, entityName); id.setIdentifierGeneratorProperties(params); id.setNullValue(null); }
private void m2oMapping(Database database, Configuration configuration, Mappings mappings) { for (Schema schema : database.getSchemas()) { for (com.manydesigns.portofino.model.database.Table aTable : schema.getTables()) { for (ForeignKey rel : aTable.getForeignKeys()) { logger.debug(MessageFormat.format("Many to one - {0} {1}", aTable.getQualifiedName(), rel.getName())); createM2O(configuration, mappings, rel); } } } }
protected Column createColumn(Mappings mappings, Table tab, com.manydesigns.portofino.model.database.Column column) { Column col = new Column(); col.setName(escapeName(column.getColumnName())); col.setLength(column.getLength()); col.setPrecision(column.getLength()); col.setScale(column.getScale()); col.setNullable(column.isNullable()); String columnType = column.getColumnType(); int jdbcType = column.getJdbcType(); col.setSqlTypeCode(jdbcType); col.setSqlType(columnType); SimpleValue value = new SimpleValue(mappings, tab); if (!setHibernateType(value, column, column.getActualJavaType(), jdbcType)) { logger.error("Skipping column {}", column.getQualifiedName()); return null; } value.addColumn(col); tab.addColumn(col); mappings.addColumnBinding(column.getColumnName(), col, tab); return col; }
private void manageIdentityGenerator(Mappings mappings, Table tab, SimpleValue id) { id.setIdentifierGeneratorStrategy("identity"); Properties params = new Properties(); params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, mappings.getObjectNameNormalizer()); params.setProperty( PersistentIdentifierGenerator.SCHEMA, escapeName(tab.getSchema())); id.setIdentifierGeneratorProperties(params); id.setNullValue(null); }
private void manageSequenceGenerator(Mappings mappings, Table tab, SimpleValue id, SequenceGenerator generator) { id.setIdentifierGeneratorStrategy ("enhanced-sequence"); Properties params = new Properties(); params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, mappings.getObjectNameNormalizer()); params.put(SequenceStyleGenerator.SEQUENCE_PARAM, escapeName(generator.getName())); params.setProperty( SequenceStyleGenerator.SCHEMA, escapeName(tab.getSchema())); id.setIdentifierGeneratorProperties(params); id.setNullValue(null); }
private void manageIncrementGenerator(Mappings mappings, Table tab, SimpleValue id, String entityName) { id.setIdentifierGeneratorStrategy("increment"); Properties params = new Properties(); params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, mappings.getObjectNameNormalizer()); params.setProperty(PersistentIdentifierGenerator.SCHEMA, escapeName(tab.getSchema())); params.put(IncrementGenerator.ENTITY_NAME, entityName); id.setIdentifierGeneratorProperties(params); id.setNullValue(null); }
public RDBMSJDBCBinder(RDBMSConfiguration rdbmsConfiguration, Settings settings, Mappings mappings, ReverseEngineeringStrategy revEngStrategy) { super(rdbmsConfiguration,settings,mappings,revEngStrategy); this.cfg = rdbmsConfiguration; this.settings = settings; this.mappings = mappings; this.revEngStrategy = revEngStrategy; }
protected Mappings getMappings() { return mappings; }
public void setMappings(Mappings mappings) { this.mappings = mappings; }
/** * return true if it's a Fk, false if it's an association table */ protected boolean bindStarToManySecondPass( Map persistentClasses, XClass collType, Ejb3JoinColumn[] fkJoinColumns, Ejb3JoinColumn[] keyColumns, Ejb3JoinColumn[] inverseColumns, Ejb3Column[] elementColumns, boolean isEmbedded, XProperty property, boolean unique, TableBinder associationTableBinder, boolean ignoreNotFound, Mappings mappings) { PersistentClass persistentClass = (PersistentClass) persistentClasses.get( collType.getName() ); boolean reversePropertyInJoin = false; if ( persistentClass != null && StringHelper.isNotEmpty( this.mappedBy ) ) { try { reversePropertyInJoin = 0 != persistentClass.getJoinNumber( persistentClass.getRecursiveProperty( this.mappedBy ) ); } catch (MappingException e) { StringBuilder error = new StringBuilder( 80 ); error.append( "mappedBy reference an unknown target entity property: " ) .append( collType ).append( "." ).append( this.mappedBy ) .append( " in " ) .append( collection.getOwnerEntityName() ) .append( "." ) .append( property.getName() ); throw new AnnotationException( error.toString() ); } } if ( persistentClass != null && !reversePropertyInJoin && oneToMany && !this.isExplicitAssociationTable && ( joinColumns[0].isImplicit() && !BinderHelper.isEmptyAnnotationValue( this.mappedBy ) //implicit @JoinColumn || !fkJoinColumns[0].isImplicit() ) //this is an explicit @JoinColumn ) { //this is a Foreign key bindOneToManySecondPass( getCollection(), persistentClasses, fkJoinColumns, collType, cascadeDeleteEnabled, ignoreNotFound, mappings, inheritanceStatePerClass ); return true; } else { //this is an association table bindManyToManySecondPass( this.collection, persistentClasses, keyColumns, inverseColumns, elementColumns, isEmbedded, collType, ignoreNotFound, unique, cascadeDeleteEnabled, associationTableBinder, property, propertyHolder, mappings ); return false; } }
protected void bindOneToManySecondPass( Collection collection, Map persistentClasses, Ejb3JoinColumn[] fkJoinColumns, XClass collectionType, boolean cascadeDeleteEnabled, boolean ignoreNotFound, Mappings mappings, Map<XClass, InheritanceState> inheritanceStatePerClass) { final boolean debugEnabled = LOG.isDebugEnabled(); if ( debugEnabled ) { LOG.debugf( "Binding a OneToMany: %s.%s through a foreign key", propertyHolder.getEntityName(), propertyName ); } org.hibernate.mapping.OneToMany oneToMany = new org.hibernate.mapping.OneToMany( mappings, collection.getOwner() ); collection.setElement( oneToMany ); oneToMany.setReferencedEntityName( collectionType.getName() ); oneToMany.setIgnoreNotFound( ignoreNotFound ); String assocClass = oneToMany.getReferencedEntityName(); PersistentClass associatedClass = (PersistentClass) persistentClasses.get( assocClass ); if ( jpaOrderBy != null ) { final String orderByFragment = buildOrderByClauseFromHql( jpaOrderBy.value(), associatedClass, collection.getRole() ); if ( StringHelper.isNotEmpty( orderByFragment ) ) { collection.setOrderBy( orderByFragment ); } } if ( mappings == null ) { throw new AssertionFailure( "CollectionSecondPass for oneToMany should not be called with null mappings" ); } Map<String, Join> joins = mappings.getJoins( assocClass ); if ( associatedClass == null ) { throw new MappingException( "Association references unmapped class: " + assocClass ); } oneToMany.setAssociatedClass( associatedClass ); for (Ejb3JoinColumn column : fkJoinColumns) { column.setPersistentClass( associatedClass, joins, inheritanceStatePerClass ); column.setJoins( joins ); collection.setCollectionTable( column.getTable() ); } if ( debugEnabled ) { LOG.debugf( "Mapping collection: %s -> %s", collection.getRole(), collection.getCollectionTable().getName() ); } bindFilters( false ); bindCollectionSecondPass( collection, null, fkJoinColumns, cascadeDeleteEnabled, property, mappings ); if ( !collection.isInverse() && !collection.getKey().isNullable() ) { // for non-inverse one-to-many, with a not-null fk, add a backref! String entityName = oneToMany.getReferencedEntityName(); PersistentClass referenced = mappings.getClass( entityName ); Backref prop = new Backref(); prop.setName( '_' + fkJoinColumns[0].getPropertyName() + '_' + fkJoinColumns[0].getLogicalColumnName() + "Backref" ); prop.setUpdateable( false ); prop.setSelectable( false ); prop.setCollectionRole( collection.getRole() ); prop.setEntityName( collection.getOwner().getEntityName() ); prop.setValue( collection.getKey() ); referenced.addProperty( prop ); } }