Package org.hibernate.mapping

Examples of org.hibernate.mapping.Join


      else {
        //find the appropriate reference key, can be in a join
        Iterator joinsIt = referencedEntity.getJoinIterator();
        KeyValue key = null;
        while ( joinsIt.hasNext() ) {
          Join join = (Join) joinsIt.next();
          if ( join.containsProperty( property ) ) {
            key = join.getKey();
            break;
          }
        }
        if ( key == null ) key = property.getPersistentClass().getIdentifier();
        mappedByColumns = key.getColumnIterator();
View Full Code Here


    // else {
    return false;
  }

  public Join getJoin() {
    Join join = joins.get( secondaryTableName );
    if ( join == null ) {
      throw new AnnotationException(
          "Cannot find the expected secondary table: no "
              + secondaryTableName + " available for " + propertyHolder.getClassName()
      );
View Full Code Here

    Iterator joins = secondaryTables.values().iterator();
    Iterator joinColumns = secondaryTableJoins.values().iterator();

    while ( joins.hasNext() ) {
      Object uncastedColumn = joinColumns.next();
      Join join = (Join) joins.next();
      createPrimaryColumnsToSecondaryTable( uncastedColumn, propertyHolder, join );
    }
    mappings.addJoins( persistentClass, secondaryTables );
  }
View Full Code Here

      SecondaryTable secondaryTable,
      JoinTable joinTable,
      PropertyHolder propertyHolder,
      boolean noDelayInPkColumnCreation) {
    // A non null propertyHolder means than we process the Pk creation without delay
    Join join = new Join();
    join.setPersistentClass( persistentClass );

    final String schema;
    final String catalog;
    final SecondaryTableNameSource secondaryTableNameContext;
    final Object joinColumns;
    final List<UniqueConstraintHolder> uniqueConstraintHolders;

    if ( secondaryTable != null ) {
      schema = secondaryTable.schema();
      catalog = secondaryTable.catalog();
      secondaryTableNameContext = new SecondaryTableNameSource( secondaryTable.name() );
      joinColumns = secondaryTable.pkJoinColumns();
      uniqueConstraintHolders = TableBinder.buildUniqueConstraintHolders( secondaryTable.uniqueConstraints() );
    }
    else if ( joinTable != null ) {
      schema = joinTable.schema();
      catalog = joinTable.catalog();
      secondaryTableNameContext = new SecondaryTableNameSource( joinTable.name() );
      joinColumns = joinTable.joinColumns();
      uniqueConstraintHolders = TableBinder.buildUniqueConstraintHolders( joinTable.uniqueConstraints() );
    }
    else {
      throw new AssertionFailure( "Both JoinTable and SecondaryTable are null" );
    }

    final Table table = TableBinder.buildAndFillTable(
        schema,
        catalog,
        secondaryTableNameContext,
        SEC_TBL_NS_HELPER,
        false,
        uniqueConstraintHolders,
        null,
        null,
        mappings,
        null
    );

    //no check constraints available on joins
    join.setTable( table );

    //somehow keep joins() for later.
    //Has to do the work later because it needs persistentClass id!
    log.info(
        "Adding secondary table to entity {} -> {}", persistentClass.getEntityName(), join.getTable().getName()
    );
    org.hibernate.annotations.Table matchingTable = findMatchingComplimentTableAnnotation( join );
    if ( matchingTable != null ) {
      join.setSequentialSelect( FetchMode.JOIN != matchingTable.fetch() );
      join.setInverse( matchingTable.inverse() );
      join.setOptional( matchingTable.optional() );
      if ( !BinderHelper.isDefault( matchingTable.sqlInsert().sql() ) ) {
        join.setCustomSQLInsert( matchingTable.sqlInsert().sql().trim(),
            matchingTable.sqlInsert().callable(),
            ExecuteUpdateResultCheckStyle.parse( matchingTable.sqlInsert().check().toString().toLowerCase() )
        );
      }
      if ( !BinderHelper.isDefault( matchingTable.sqlUpdate().sql() ) ) {
        join.setCustomSQLUpdate( matchingTable.sqlUpdate().sql().trim(),
            matchingTable.sqlUpdate().callable(),
            ExecuteUpdateResultCheckStyle.parse( matchingTable.sqlUpdate().check().toString().toLowerCase() )
        );
      }
      if ( !BinderHelper.isDefault( matchingTable.sqlDelete().sql() ) ) {
        join.setCustomSQLDelete( matchingTable.sqlDelete().sql().trim(),
            matchingTable.sqlDelete().callable(),
            ExecuteUpdateResultCheckStyle.parse( matchingTable.sqlDelete().check().toString().toLowerCase() )
        );
      }
    }
    else {
      //default
      join.setSequentialSelect( false );
      join.setInverse( false );
      join.setOptional( true ); //perhaps not quite per-spec, but a Good Thing anyway
    }

    if ( noDelayInPkColumnCreation ) {
      createPrimaryColumnsToSecondaryTable( joinColumns, propertyHolder, join );
    }
View Full Code Here

      else {
        //find the appropriate reference key, can be in a join
        Iterator joinsIt = referencedEntity.getJoinIterator();
        KeyValue key = null;
        while ( joinsIt.hasNext() ) {
          Join join = (Join) joinsIt.next();
          if ( join.containsProperty( property ) ) {
            key = join.getKey();
            break;
          }
        }
        if ( key == null ) key = property.getPersistentClass().getIdentifier();
        mappedByColumns = key.getColumnIterator();
View Full Code Here

      if ( otherSideProperty.getValue() instanceof OneToOne ) {
        propertyHolder.addProperty( prop, inferredData.getDeclaringClass() );
      }
      else if ( otherSideProperty.getValue() instanceof ManyToOne ) {
        Iterator it = otherSide.getJoinIterator();
        Join otherSideJoin = null;
        while ( it.hasNext() ) {
          Join otherSideJoinValue = (Join) it.next();
          if ( otherSideJoinValue.containsProperty( otherSideProperty ) ) {
            otherSideJoin = otherSideJoinValue;
            break;
          }
        }
        if ( otherSideJoin != null ) {
          //@OneToOne @JoinTable
          Join mappedByJoin = buildJoinFromMappedBySide(
              (PersistentClass) persistentClasses.get( ownerEntity ), otherSideProperty, otherSideJoin
          );
          ManyToOne manyToOne = new ManyToOne( mappings, mappedByJoin.getTable() );
          //FIXME use ignore not found here
          manyToOne.setIgnoreNotFound( ignoreNotFound );
          manyToOne.setCascadeDeleteEnabled( value.isCascadeDeleteEnabled() );
          manyToOne.setEmbedded( value.isEmbedded() );
          manyToOne.setFetchMode( value.getFetchMode() );
          manyToOne.setLazy( value.isLazy() );
          manyToOne.setReferencedEntityName( value.getReferencedEntityName() );
          manyToOne.setUnwrapProxy( value.isUnwrapProxy() );
          prop.setValue( manyToOne );
          Iterator otherSideJoinKeyColumns = otherSideJoin.getKey().getColumnIterator();
          while ( otherSideJoinKeyColumns.hasNext() ) {
            Column column = (Column) otherSideJoinKeyColumns.next();
            Column copy = new Column();
            copy.setLength( column.getLength() );
            copy.setScale( column.getScale() );
            copy.setValue( manyToOne );
            copy.setName( column.getQuotedName() );
            copy.setNullable( column.isNullable() );
            copy.setPrecision( column.getPrecision() );
            copy.setUnique( column.isUnique() );
            copy.setSqlType( column.getSqlType() );
            copy.setCheckConstraint( column.getCheckConstraint() );
            copy.setComment( column.getComment() );
            copy.setDefaultValue( column.getDefaultValue() );
            manyToOne.addColumn( copy );
          }
          mappedByJoin.addProperty( prop );
        }
        else {
          propertyHolder.addProperty( prop, inferredData.getDeclaringClass() );
        }
View Full Code Here

   * <li>From the mappedBy side we should not create the PK nor the FK, this is handled from the other side.</li>
   * <li>This method is a dirty dupe of EntityBinder.bindSecondaryTable</i>.
   * </p>
   */
  private Join buildJoinFromMappedBySide(PersistentClass persistentClass, Property otherSideProperty, Join originalJoin) {
    Join join = new Join();
    join.setPersistentClass( persistentClass );

    //no check constraints available on joins
    join.setTable( originalJoin.getTable() );
    join.setInverse( true );
    SimpleValue key = new DependantValue( mappings, join.getTable(), persistentClass.getIdentifier() );
    //TODO support @ForeignKey
    join.setKey( key );
    join.setSequentialSelect( false );
    //TODO support for inverse and optional
    join.setOptional( true ); //perhaps not quite per-spec, but a Good Thing anyway
    key.setCascadeDeleteEnabled( false );
    Iterator mappedByColumns = otherSideProperty.getValue().getColumnIterator();
    while ( mappedByColumns.hasNext() ) {
      Column column = (Column) mappedByColumns.next();
      Column copy = new Column();
View Full Code Here

        boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
        OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
        boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
        JoinTable assocTable = propertyHolder.getJoinTable( property );
        if ( assocTable != null ) {
          Join join = propertyHolder.addJoin( assocTable, false );
          for ( Ejb3JoinColumn joinColumn : joinColumns ) {
            joinColumn.setSecondaryTableName( join.getTable().getName() );
          }
        }
        final boolean mandatory = !ann.optional() || forcePersist;
        bindManyToOne(
            getCascadeStrategy( ann.cascade(), hibernateCascade, false, forcePersist ),
            joinColumns,
            !mandatory,
            ignoreNotFound, onDeleteCascade,
            ToOneBinder.getTargetEntity( inferredData, mappings ),
            propertyHolder,
            inferredData, false, isIdentifierMapper,
            inSecondPass, propertyBinder, mappings
        );
      }
      else if ( property.isAnnotationPresent( OneToOne.class ) ) {
        OneToOne ann = property.getAnnotation( OneToOne.class );

        //check validity
        if ( property.isAnnotationPresent( Column.class )
            || property.isAnnotationPresent( Columns.class ) ) {
          throw new AnnotationException(
              "@Column(s) not allowed on a @OneToOne property: "
                  + BinderHelper.getPath( propertyHolder, inferredData )
          );
        }

        //FIXME support a proper PKJCs
        boolean trueOneToOne = property.isAnnotationPresent( PrimaryKeyJoinColumn.class )
            || property.isAnnotationPresent( PrimaryKeyJoinColumns.class );
        Cascade hibernateCascade = property.getAnnotation( Cascade.class );
        NotFound notFound = property.getAnnotation( NotFound.class );
        boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
        OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
        boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
        JoinTable assocTable = propertyHolder.getJoinTable( property );
        if ( assocTable != null ) {
          Join join = propertyHolder.addJoin( assocTable, false );
          for ( Ejb3JoinColumn joinColumn : joinColumns ) {
            joinColumn.setSecondaryTableName( join.getTable().getName() );
          }
        }
        //MapsId means the columns belong to the pk => not null
        //@PKJC must be constrained
        final boolean mandatory = !ann.optional() || forcePersist || trueOneToOne;
        bindOneToOne(
            getCascadeStrategy( ann.cascade(), hibernateCascade, ann.orphanRemoval(), forcePersist ),
            joinColumns,
            !mandatory,
            getFetchMode( ann.fetch() ),
            ignoreNotFound, onDeleteCascade,
            ToOneBinder.getTargetEntity( inferredData, mappings ),
            propertyHolder,
            inferredData,
            ann.mappedBy(),
            trueOneToOne,
            isIdentifierMapper,
            inSecondPass,
            propertyBinder,
            mappings
        );
      }
      else if ( property.isAnnotationPresent( org.hibernate.annotations.Any.class ) ) {

        //check validity
        if ( property.isAnnotationPresent( Column.class )
            || property.isAnnotationPresent( Columns.class ) ) {
          throw new AnnotationException(
              "@Column(s) not allowed on a @Any property: "
                  + BinderHelper.getPath( propertyHolder, inferredData )
          );
        }

        Cascade hibernateCascade = property.getAnnotation( Cascade.class );
        OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
        boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
        JoinTable assocTable = propertyHolder.getJoinTable( property );
        if ( assocTable != null ) {
          Join join = propertyHolder.addJoin( assocTable, false );
          for ( Ejb3JoinColumn joinColumn : joinColumns ) {
            joinColumn.setSecondaryTableName( join.getTable().getName() );
          }
        }
        bindAny(
            getCascadeStrategy( null, hibernateCascade, false, forcePersist ),
            //@Any has not cascade attribute
View Full Code Here

    //Span of the tables directly mapped by this entity and super-classes, if any
    int coreTableSpan = tables.size();
   
    Iterator joinIter = persistentClass.getJoinClosureIterator();
    while ( joinIter.hasNext() ) {
      Join join = (Join) joinIter.next();
     
      Table tab = join.getTable();
      
      String tabname = tab.getQualifiedName(
          factory.getDialect(),
          factory.getSettings().getDefaultCatalogName(),
          factory.getSettings().getDefaultSchemaName()
      );
      tables.add(tabname);
     
      KeyValue key = join.getKey();
      int joinIdColumnSpan =   key.getColumnSpan();   
     
      String[] keyCols = new String[joinIdColumnSpan];
      String[] keyColReaders = new String[joinIdColumnSpan];
      String[] keyColReaderTemplates = new String[joinIdColumnSpan];
           
      Iterator citer = key.getColumnIterator();
     
      for ( int k=0; k<joinIdColumnSpan; k++ ) {
        Column column = (Column) citer.next();
        keyCols[k] = column.getQuotedName( factory.getDialect() );
        keyColReaders[k] = column.getReadExpr( factory.getDialect() );
        keyColReaderTemplates[k] = column.getTemplate( factory.getDialect(), factory.getSqlFunctionRegistry() );
      }
      keyColumns.add(keyCols);
      keyColumnReaders.add(keyColReaders);
      keyColumnReaderTemplates.add(keyColReaderTemplates);
      cascadeDeletes.add( new Boolean( key.isCascadeDeleteEnabled() && factory.getDialect().supportsCascadeDelete() ) );
    }
   
    naturalOrderTableNames = ArrayHelper.toStringArray(tables);
    naturalOrderTableKeyColumns = ArrayHelper.to2DStringArray(keyColumns);
    naturalOrderTableKeyColumnReaders = ArrayHelper.to2DStringArray(keyColumnReaders);
    naturalOrderTableKeyColumnReaderTemplates = ArrayHelper.to2DStringArray(keyColumnReaderTemplates);
    naturalOrderCascadeDeleteEnabled = ArrayHelper.toBooleanArray(cascadeDeletes);

    ArrayList subtables = new ArrayList();
    ArrayList isConcretes = new ArrayList();
    ArrayList isDeferreds = new ArrayList();
    ArrayList isLazies = new ArrayList();
   
    keyColumns = new ArrayList();
    titer = persistentClass.getSubclassTableClosureIterator();
    while ( titer.hasNext() ) {
      Table tab = (Table) titer.next();
      isConcretes.add( new Boolean( persistentClass.isClassOrSuperclassTable(tab) ) );
      isDeferreds.add(Boolean.FALSE);
      isLazies.add(Boolean.FALSE);
      String tabname = tab.getQualifiedName(
          factory.getDialect(),
          factory.getSettings().getDefaultCatalogName(),
          factory.getSettings().getDefaultSchemaName()
      );
      subtables.add(tabname);
      String[] key = new String[idColumnSpan];
      Iterator citer = tab.getPrimaryKey().getColumnIterator();
      for ( int k=0; k<idColumnSpan; k++ ) {
        key[k] = ( (Column) citer.next() ).getQuotedName( factory.getDialect() );
      }
      keyColumns.add(key);
    }
   
    //Add joins
    joinIter = persistentClass.getSubclassJoinClosureIterator();
    while ( joinIter.hasNext() ) {
      Join join = (Join) joinIter.next();
     
      Table tab = join.getTable();
      
      isConcretes.add( new Boolean( persistentClass.isClassOrSuperclassTable(tab) ) );
      isDeferreds.add( new Boolean( join.isSequentialSelect() ) );
      isLazies.add(new Boolean(join.isLazy()));
     
      String tabname = tab.getQualifiedName(
          factory.getDialect(),
          factory.getSettings().getDefaultCatalogName(),
          factory.getSettings().getDefaultSchemaName()
      );
      subtables.add(tabname);
      String[] key = new String[idColumnSpan];
      Iterator citer = tab.getPrimaryKey().getColumnIterator();
      for ( int k=0; k<idColumnSpan; k++ ) {
        key[k] = ( (Column) citer.next() ).getQuotedName( factory.getDialect() );
      }
      keyColumns.add(key);
           
    }
       
    String [] naturalOrderSubclassTableNameClosure = ArrayHelper.toStringArray(subtables);
    String[][] naturalOrderSubclassTableKeyColumnClosure = ArrayHelper.to2DStringArray(keyColumns);
    isClassOrSuperclassTable = ArrayHelper.toBooleanArray(isConcretes);
    subclassTableSequentialSelect = ArrayHelper.toBooleanArray(isDeferreds);
    subclassTableIsLazyClosure = ArrayHelper.toBooleanArray(isLazies);
   
    constraintOrderedTableNames = new String[naturalOrderSubclassTableNameClosure.length];
    constraintOrderedKeyColumnNames = new String[naturalOrderSubclassTableNameClosure.length][];
    int currentPosition = 0;
    for ( int i = naturalOrderSubclassTableNameClosure.length - 1; i >= 0 ; i--, currentPosition++ ) {
      constraintOrderedTableNames[currentPosition] = naturalOrderSubclassTableNameClosure[i];
      constraintOrderedKeyColumnNames[currentPosition] = naturalOrderSubclassTableKeyColumnClosure[i];
    }

    /**
     * Suppose an entity Client extends Person, mapped to the tables CLIENT and PERSON respectively.
     * For the Client entity:
     * naturalOrderTableNames -> PERSON, CLIENT; this reflects the sequence in which the tables are
     * added to the meta-data when the annotated entities are processed.
     * However, in some instances, for example when generating joins, the CLIENT table needs to be
     * the first table as it will the driving table.
     * tableNames -> CLIENT, PERSON
     */
       
    tableSpan = naturalOrderTableNames.length;
     tableNames = reverse(naturalOrderTableNames, coreTableSpan);
    tableKeyColumns = reverse(naturalOrderTableKeyColumns, coreTableSpan);
    tableKeyColumnReaders = reverse(naturalOrderTableKeyColumnReaders, coreTableSpan);
    tableKeyColumnReaderTemplates = reverse(naturalOrderTableKeyColumnReaderTemplates, coreTableSpan);
    subclassTableNameClosure = reverse(naturalOrderSubclassTableNameClosure, coreTableSpan);
    subclassTableKeyColumnClosure = reverse(naturalOrderSubclassTableKeyColumnClosure, coreTableSpan);
    spaces = ArrayHelper.join(
        tableNames,
        ArrayHelper.toStringArray( persistentClass.getSynchronizedTables() )
    );

    // Custom sql
    customSQLInsert = new String[tableSpan];
    customSQLUpdate = new String[tableSpan];
    customSQLDelete = new String[tableSpan];
    insertCallable = new boolean[tableSpan];
    updateCallable = new boolean[tableSpan];
    deleteCallable = new boolean[tableSpan];
    insertResultCheckStyles = new ExecuteUpdateResultCheckStyle[tableSpan];
    updateResultCheckStyles = new ExecuteUpdateResultCheckStyle[tableSpan];
    deleteResultCheckStyles = new ExecuteUpdateResultCheckStyle[tableSpan];

    PersistentClass pc = persistentClass;
    int jk = coreTableSpan-1;
    while (pc!=null) {
      customSQLInsert[jk] = pc.getCustomSQLInsert();
      insertCallable[jk] = customSQLInsert[jk] != null && pc.isCustomInsertCallable();
      insertResultCheckStyles[jk] = pc.getCustomSQLInsertCheckStyle() == null
                                    ? ExecuteUpdateResultCheckStyle.determineDefault( customSQLInsert[jk], insertCallable[jk] )
                                      : pc.getCustomSQLInsertCheckStyle();
      customSQLUpdate[jk] = pc.getCustomSQLUpdate();
      updateCallable[jk] = customSQLUpdate[jk] != null && pc.isCustomUpdateCallable();
      updateResultCheckStyles[jk] = pc.getCustomSQLUpdateCheckStyle() == null
                                    ? ExecuteUpdateResultCheckStyle.determineDefault( customSQLUpdate[jk], updateCallable[jk] )
                                      : pc.getCustomSQLUpdateCheckStyle();
      customSQLDelete[jk] = pc.getCustomSQLDelete();
      deleteCallable[jk] = customSQLDelete[jk] != null && pc.isCustomDeleteCallable();
      deleteResultCheckStyles[jk] = pc.getCustomSQLDeleteCheckStyle() == null
                                    ? ExecuteUpdateResultCheckStyle.determineDefault( customSQLDelete[jk], deleteCallable[jk] )
                                      : pc.getCustomSQLDeleteCheckStyle();
      jk--;
      pc = pc.getSuperclass();
    }
   
    if ( jk != -1 ) {
      throw new AssertionFailure( "Tablespan does not match height of joined-subclass hiearchy." );
    }
    joinIter = persistentClass.getJoinClosureIterator();
    int j = coreTableSpan;
    while ( joinIter.hasNext() ) {
      Join join = (Join) joinIter.next();
     
      customSQLInsert[j] = join.getCustomSQLInsert();
      insertCallable[j] = customSQLInsert[j] != null && join.isCustomInsertCallable();
      insertResultCheckStyles[j] = join.getCustomSQLInsertCheckStyle() == null
                                    ? ExecuteUpdateResultCheckStyle.determineDefault( customSQLInsert[j], insertCallable[j] )
                                      : join.getCustomSQLInsertCheckStyle();
      customSQLUpdate[j] = join.getCustomSQLUpdate();
      updateCallable[j] = customSQLUpdate[j] != null && join.isCustomUpdateCallable();
      updateResultCheckStyles[j] = join.getCustomSQLUpdateCheckStyle() == null
                                    ? ExecuteUpdateResultCheckStyle.determineDefault( customSQLUpdate[j], updateCallable[j] )
                                      : join.getCustomSQLUpdateCheckStyle();
      customSQLDelete[j] = join.getCustomSQLDelete();
      deleteCallable[j] = customSQLDelete[j] != null && join.isCustomDeleteCallable();
      deleteResultCheckStyles[j] = join.getCustomSQLDeleteCheckStyle() == null
                                    ? ExecuteUpdateResultCheckStyle.determineDefault( customSQLDelete[j], deleteCallable[j] )
                                      : join.getCustomSQLDeleteCheckStyle();
      j++;
    }
   
    // PROPERTIES
    int hydrateSpan = getPropertySpan();
View Full Code Here

            inheritedMetas,
            false
          );
      }
      else if ( "join".equals( name ) ) {
        Join join = new Join();
        join.setPersistentClass( persistentClass );
        bindJoin( subnode, join, mappings, inheritedMetas );
        persistentClass.addJoin( join );
      }
      else if ( "subclass".equals( name ) ) {
        handleSubclass( persistentClass, mappings, subnode, inheritedMetas );
View Full Code Here

TOP

Related Classes of org.hibernate.mapping.Join

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.