Open Source Repository

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



org/hibernate/persister/collection/BasicCollectionPersister.java
//$Id: BasicCollectionPersister.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.Expectations;
import org.hibernate.jdbc.Expectation;
import org.hibernate.type.AssociationType;
import org.hibernate.persister.entity.Joinable;
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.SubselectCollectionLoader;
import org.hibernate.mapping.Collection;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.sql.Delete;
import org.hibernate.sql.Insert;
import org.hibernate.sql.Update;
import org.hibernate.sql.SelectFragment;
import org.hibernate.util.ArrayHelper;

/**
 * Collection persister for collections of values and many-to-many associations.
 *
 @author Gavin King
 */
public class BasicCollectionPersister extends AbstractCollectionPersister {

  public boolean isCascadeDeleteEnabled() {
    return false;
  }

  public BasicCollectionPersister(Collection collection,
                  CacheConcurrencyStrategy cache,
                  Configuration cfg,
                  SessionFactoryImplementor factory)
      throws MappingException, CacheException {
    supercollection, cache, cfg, factory );
  }

  /**
   * Generate the SQL DELETE that deletes all rows
   */
  protected String generateDeleteString() {
    
    Delete delete = new Delete()
        .setTableNamequalifiedTableName )
        .setPrimaryKeyColumnNameskeyColumnNames );
    
    if hasWhere delete.setWheresqlWhereString );
    
    if getFactory().getSettings().isCommentsEnabled() ) {
      delete.setComment"delete collection " + getRole() );
    }
    
    return delete.toStatementString();
  }

  /**
   * Generate the SQL INSERT that creates a new row
   */
  protected String generateInsertRowString() {
    
    Insert insert = new InsertgetDialect() )
        .setTableNamequalifiedTableName )
        .addColumnskeyColumnNames );
    
    if hasIdentifierinsert.addColumnidentifierColumnName );
    
    if hasIndex /*&& !indexIsFormula*/ ) {
      insert.addColumnsindexColumnNames, indexColumnIsSettable );
    }
    
    if getFactory().getSettings().isCommentsEnabled() ) {
      insert.setComment"insert collection row " + getRole() );
    }
    
    //if ( !elementIsFormula ) {
      insert.addColumnselementColumnNames, elementColumnIsSettable );
    //}
    
    return insert.toStatementString();
  }

  /**
   * Generate the SQL UPDATE that updates a row
   */
  protected String generateUpdateRowString() {
    
    Update update = new UpdategetDialect() )
      .setTableNamequalifiedTableName );
    
    //if ( !elementIsFormula ) {
      update.addColumnselementColumnNames, elementColumnIsSettable );
    //}
    
    if hasIdentifier ) {
      update.setPrimaryKeyColumnNamesnew String[]{ identifierColumnName } );
    }
    else if hasIndex && !indexContainsFormula ) {
      update.setPrimaryKeyColumnNamesArrayHelper.joinkeyColumnNames, indexColumnNames ) );
    }
    else {
      update.setPrimaryKeyColumnNamesArrayHelper.joinkeyColumnNames, elementColumnNames, elementColumnIsInPrimaryKey ) );
    }
    
    if getFactory().getSettings().isCommentsEnabled() ) {
      update.setComment"update collection row " + getRole() );
    }
    
    return update.toStatementString();
  }

  /**
   * Generate the SQL DELETE that deletes a particular row
   */
  protected String generateDeleteRowString() {
    
    Delete delete = new Delete()
      .setTableNamequalifiedTableName );
    
    if hasIdentifier ) {
      delete.setPrimaryKeyColumnNamesnew String[]{ identifierColumnName } );
    }
    else if hasIndex && !indexContainsFormula ) {
      delete.setPrimaryKeyColumnNamesArrayHelper.joinkeyColumnNames, indexColumnNames ) );
    }
    else {
      delete.setPrimaryKeyColumnNamesArrayHelper.joinkeyColumnNames, elementColumnNames, elementColumnIsInPrimaryKey ) );
    }
    
    if getFactory().getSettings().isCommentsEnabled() ) {
      delete.setComment"delete collection row " + getRole() );
    }
    
    return delete.toStatementString();
  }

  public boolean consumesEntityAlias() {
    return false;
  }

  public boolean consumesCollectionAlias() {
//    return !isOneToMany();
    return true;
  }

  public boolean isOneToMany() {
    return false;
  }

  public boolean isManyToMany() {
    return elementType.isEntityType()//instanceof AssociationType;
  }

  protected int doUpdateRows(Serializable id, PersistentCollection collection, SessionImplementor session)
      throws HibernateException {
    
    if ArrayHelper.isAllFalse(elementColumnIsSettable) ) return 0;

    try {
      PreparedStatement st = null;
      Expectation expectation = Expectations.appropriateExpectationgetUpdateCheckStyle() );
      boolean callable = isUpdateCallable();
      boolean useBatch = expectation.canBeBatched();
      Iterator entries = collection.entriesthis );
      String sql = getSQLUpdateRowString();
      int i = 0;
      int count = 0;
      while entries.hasNext() ) {
        Object entry = entries.next();
        if collection.needsUpdatingentry, i, elementType ) ) {
          int offset = 1;

          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 );
            }
          }

          try {
            offset+= expectation.preparest );
            int loc = writeElementst, collection.getElemententry ), offset, session );
            if hasIdentifier ) {
              writeIdentifierst, collection.getIdentifierentry, i ), loc, session );
            }
            else {
              loc = writeKeyst, id, loc, session );
              if hasIndex && !indexContainsFormula ) {
                writeIndexToWherest, collection.getIndexentry, i, this ), loc, session );
              }
              else {
                writeElementToWherest, collection.getSnapshotElemententry, i ), loc, session );
              }
            }

            if useBatch ) {
              session.getBatcher().addToBatchexpectation );
            }
            else {
              expectation.verifyOutcomest.executeUpdate(), st, -);
            }
          }
          catch SQLException sqle ) {
            if useBatch ) {
              session.getBatcher().abortBatchsqle );
            }
            throw sqle;
          }
          finally {
            if !useBatch ) {
              session.getBatcher().closeStatementst );
            }
          }
          count++;
        }
        i++;
      }
      return count;
    }
    catch SQLException sqle ) {
      throw JDBCExceptionHelper.convert(
          getSQLExceptionConverter(),
          sqle,
          "could not update collection rows: " + MessageHelper.collectionInfoStringthis, id, getFactory() ),
          getSQLUpdateRowString()
        );
    }
  }

  public String selectFragment(
          Joinable rhs,
          String rhsAlias,
          String lhsAlias,
          String entitySuffix,
          String collectionSuffix,
          boolean includeCollectionColumns) {
    // we need to determine the best way to know that two joinables
    // represent a single many-to-many...
    if rhs != null && isManyToMany() && !rhs.isCollection() ) {
      AssociationType elementType = ( ( AssociationType getElementType() );
      if rhs.equalselementType.getAssociatedJoinablegetFactory() ) ) ) {
        return manyToManySelectFragmentrhs, rhsAlias, lhsAlias, collectionSuffix );
      }
    }
    return includeCollectionColumns ? selectFragmentlhsAlias, collectionSuffix "";
  }

  private String manyToManySelectFragment(
          Joinable rhs,
          String rhsAlias,
          String lhsAlias,
          String collectionSuffix) {
    SelectFragment frag = generateSelectFragmentlhsAlias, collectionSuffix );

    String[] elementColumnNames = rhs.getKeyColumnNames();
    frag.addColumnsrhsAlias, elementColumnNames, elementColumnAliases );
    appendIndexColumnsfrag, lhsAlias );
    appendIdentifierColumnsfrag, lhsAlias );

    return frag.toFragmentString()
        .substring)//strip leading ','
  }

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

  public String fromJoinFragment(String alias, boolean innerJoin, boolean includeSubclasses) {
    return "";
  }

  public String whereJoinFragment(String alias, boolean innerJoin, boolean includeSubclasses) {
    return "";
  }

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

}