Open Source Repository

Home /hibernate/hibernate-3.2.7.ga | Repository Home



org/hibernate/persister/collection/OneToManyPersister.java
//$Id: OneToManyPersister.java 10040 2006-06-22 19:51:43Z [email protected] $
package org.hibernate.persister.collection;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.jdbc.Expectation;
import org.hibernate.jdbc.Expectations;
import org.hibernate.cache.CacheConcurrencyStrategy;
import org.hibernate.cache.CacheException;
import org.hibernate.cfg.Configuration;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.engine.SubselectFetch;
import org.hibernate.exception.JDBCExceptionHelper;
import org.hibernate.loader.collection.BatchingCollectionInitializer;
import org.hibernate.loader.collection.CollectionInitializer;
import org.hibernate.loader.collection.SubselectOneToManyLoader;
import org.hibernate.loader.entity.CollectionElementLoader;
import org.hibernate.mapping.Collection;
import org.hibernate.persister.entity.Joinable;
import org.hibernate.persister.entity.OuterJoinLoadable;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.sql.Update;
import org.hibernate.util.ArrayHelper;

/**
 * Collection persister for one-to-many associations.
 *
 @author Gavin King
 */
public class OneToManyPersister extends AbstractCollectionPersister {

  private final boolean cascadeDeleteEnabled;
  private final boolean keyIsNullable;
  private final boolean keyIsUpdateable;

  protected boolean isRowDeleteEnabled() {
    return keyIsUpdateable && keyIsNullable;
  }

  protected boolean isRowInsertEnabled() {
    return keyIsUpdateable;
  }

  public boolean isCascadeDeleteEnabled() {
    return cascadeDeleteEnabled;
  }

  public OneToManyPersister(Collection collection,
                CacheConcurrencyStrategy cache,
                Configuration cfg,
                SessionFactoryImplementor factory)
      throws MappingException, CacheException {
    supercollection, cache, cfg, factory );
    cascadeDeleteEnabled = collection.getKey().isCascadeDeleteEnabled() &&
        factory.getDialect().supportsCascadeDelete();
    keyIsNullable = collection.getKey().isNullable();
    keyIsUpdateable = collection.getKey().isUpdateable();
  }

  /**
   * Generate the SQL UPDATE that updates all the foreign keys to null
   */
  protected String generateDeleteString() {
    
    Update update = new UpdategetDialect() )
        .setTableNamequalifiedTableName )
        .addColumnskeyColumnNames, "null" )
        .setPrimaryKeyColumnNameskeyColumnNames );
    
    if hasIndex && !indexContainsFormula update.addColumnsindexColumnNames, "null" );
    
    if hasWhere update.setWheresqlWhereString );
    
    if getFactory().getSettings().isCommentsEnabled() ) {
      update.setComment"delete one-to-many " + getRole() );
    }
    
    return update.toStatementString();
  }

  /**
   * Generate the SQL UPDATE that updates a foreign key to a value
   */
  protected String generateInsertRowString() {
    
    Update update = new UpdategetDialect() )
        .setTableNamequalifiedTableName )
        .addColumnskeyColumnNames );
    
    if hasIndex && !indexContainsFormula update.addColumnsindexColumnNames );
    
    //identifier collections not supported for 1-to-many
    if getFactory().getSettings().isCommentsEnabled() ) {
      update.setComment"create one-to-many row " + getRole() );
    }
    
    return update.setPrimaryKeyColumnNameselementColumnNames )
        .toStatementString();
  }

  /**
   * Not needed for one-to-many association
   */
  protected String generateUpdateRowString() {
    return null;
  }

  /**
   * Generate the SQL UPDATE that updates a particular row's foreign
   * key to null
   */
  protected String generateDeleteRowString() {
    
    Update update = new UpdategetDialect() )
        .setTableNamequalifiedTableName )
        .addColumnskeyColumnNames, "null" );
    
    if hasIndex && !indexContainsFormula update.addColumnsindexColumnNames, "null" );
    
    if getFactory().getSettings().isCommentsEnabled() ) {
      update.setComment"delete one-to-many row " + getRole() );
    }
    
    //use a combination of foreign key columns and pk columns, since
    //the ordering of removal and addition is not guaranteed when
    //a child moves from one parent to another
    String[] rowSelectColumnNames = ArrayHelper.join(keyColumnNames, elementColumnNames);
    return update.setPrimaryKeyColumnNamesrowSelectColumnNames )
        .toStatementString();
  }

  public boolean consumesEntityAlias() {
    return true;
  }
  public boolean consumesCollectionAlias() {
    return true;
  }

  public boolean isOneToMany() {
    return true;
  }

  public boolean isManyToMany() {
    return false;
  }

  protected int doUpdateRows(Serializable id, PersistentCollection collection, SessionImplementor session)
      throws HibernateException {

    // we finish all the "removes" first to take care of possible unique
    // constraints and so that we can take better advantage of batching
    
    try {
      int count = 0;
      if isRowDeleteEnabled() ) {
        boolean useBatch = true;
        PreparedStatement st = null;
        // update removed rows fks to null
        try {
          int i = 0;
  
          Iterator entries = collection.entriesthis );
          int offset = 1;
          Expectation expectation = Expectations.NONE;
          while entries.hasNext() ) {
  
            Object entry = entries.next();
            if collection.needsUpdatingentry, i, elementType ) ) {  // will still be issued when it used to be null
              if st == null ) {
                String sql = getSQLDeleteRowString();
                if isDeleteCallable() ) {
                  expectation = Expectations.appropriateExpectationgetDeleteCheckStyle() );
                  useBatch = expectation.canBeBatched();
                  st = useBatch
                      ? session.getBatcher().prepareBatchCallableStatementsql )
                            : session.getBatcher().prepareCallableStatementsql );
                  offset += expectation.preparest );
                }
                else {
                  st = session.getBatcher().prepareBatchStatementgetSQLDeleteRowString() );
                }
              }
              int loc = writeKeyst, id, offset, session );
              writeElementToWherest, collection.getSnapshotElement(entry, i), loc, session );
              if useBatch ) {
                session.getBatcher().addToBatchexpectation );
              }
              else {
                expectation.verifyOutcomest.executeUpdate(), st, -);
              }
              count++;
            }
            i++;
          }
        }
        catch SQLException sqle ) {
          if useBatch ) {
            session.getBatcher().abortBatchsqle );
          }
          throw sqle;
        }
        finally {
          if !useBatch ) {
            session.getBatcher().closeStatementst );
          }
        }
      }
      
      if isRowInsertEnabled() ) {
        Expectation expectation = Expectations.appropriateExpectationgetInsertCheckStyle() );
        boolean callable = isInsertCallable();
        boolean useBatch = expectation.canBeBatched();
        String sql = getSQLInsertRowString();
        PreparedStatement st = null;
        // now update all changed or added rows fks
        try {
          int i = 0;
          Iterator entries = collection.entriesthis );
          while entries.hasNext() ) {
            Object entry = entries.next();
            int offset = 1;
            if collection.needsUpdatingentry, i, elementType ) ) {
              if useBatch ) {
                if st == null ) {
                  if callable ) {
                    st = session.getBatcher().prepareBatchCallableStatementsql );
                  }
                  else {
                    st = session.getBatcher().prepareBatchStatementsql );
                  }
                }
              }
              else {
                if callable ) {
                  st = session.getBatcher().prepareCallableStatementsql );
                }
                else {
                  st = session.getBatcher().prepareStatementsql );
                }
              }

              offset += expectation.preparest );

              int loc = writeKeyst, id, offset, session );
              if hasIndex && !indexContainsFormula ) {
                loc = writeIndexToWherest, collection.getIndexentry, i, this ), loc, session );
              }

              writeElementToWherest, collection.getElemententry ), loc, session );

              if useBatch ) {
                session.getBatcher().addToBatchexpectation );
              }
              else {
                expectation.verifyOutcomest.executeUpdate(), st, -);
              }
              count++;
            }
            i++;
          }
        }
        catch SQLException sqle ) {
          if useBatch ) {
            session.getBatcher().abortBatchsqle );
          }
          throw sqle;
        }
        finally {
          if !useBatch ) {
            session.getBatcher().closeStatementst );
          }
        }
      }

      return count;
    }
    catch SQLException sqle ) {
      throw JDBCExceptionHelper.convert(
          getSQLExceptionConverter(),
          sqle,
          "could not update collection rows: " 
          MessageHelper.collectionInfoStringthis, id, getFactory() ),
          getSQLInsertRowString()
      );
    }
  }

  public String selectFragment(
          Joinable rhs,
          String rhsAlias,
          String lhsAlias,
          String entitySuffix,
          String collectionSuffix,
          boolean includeCollectionColumns) {
    StringBuffer buf = new StringBuffer();
    if includeCollectionColumns ) {
//      buf.append( selectFragment( lhsAlias, "" ) )//ignore suffix for collection columns!
      buf.appendselectFragmentlhsAlias, collectionSuffix ) )
          .append", " );
    }
    OuterJoinLoadable ojl = OuterJoinLoadable getElementPersister();
    return buf.appendojl.selectFragmentlhsAlias, entitySuffix ) )//use suffix for the entity columns
        .toString();
  }

  /**
   * Create the <tt>OneToManyLoader</tt>
   *
   @see org.hibernate.loader.collection.OneToManyLoader
   */
  protected CollectionInitializer createCollectionInitializer(java.util.Map enabledFiltersthrows MappingException {
    return BatchingCollectionInitializer.createBatchingOneToManyInitializerthis, batchSize, getFactory(), enabledFilters );
  }

  public String fromJoinFragment(String alias,
                   boolean innerJoin,
                   boolean includeSubclasses) {
    return ( ( Joinable getElementPersister() ).fromJoinFragmentalias, innerJoin, includeSubclasses );
  }

  public String whereJoinFragment(String alias,
                  boolean innerJoin,
                  boolean includeSubclasses) {
    return ( ( Joinable getElementPersister() ).whereJoinFragmentalias, innerJoin, includeSubclasses );
  }

  public String getTableName() {
    return ( ( Joinable getElementPersister() ).getTableName();
  }

  public String filterFragment(String aliasthrows MappingException {
    String result = super.filterFragmentalias );
    if getElementPersister() instanceof Joinable ) {
      result += ( ( Joinable getElementPersister() ).oneToManyFilterFragmentalias );
    }
    return result;

  }

  protected CollectionInitializer createSubselectInitializer(SubselectFetch subselect, SessionImplementor session) {
    return new SubselectOneToManyLoader
        this,
        subselect.toSubselectStringgetCollectionType().getLHSPropertyName() ),
        subselect.getResult(),
        subselect.getQueryParameters(),
        subselect.getNamedParameterLocMap(),
        session.getFactory(),
        session.getEnabledFilters() 
      );
  }

  public Object getElementByIndex(Serializable key, Object index, SessionImplementor session, Object owner) {
    return new CollectionElementLoaderthis, getFactory(), session.getEnabledFilters() )
        .loadElementsession, key, incrementIndexByBase(index) );
  }

}