## Copyright 2001-2005 The Apache Software Foundation.
##
## Licensed under the Apache License, Version 2.0 (the "License")
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
##     http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
/**
 * Copyright (c) 2006, yher.net
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation 
 *   and/or other materials provided with the distribution.
 * * Neither the name of the nor the names of its contributors may be used to endorse or 
 *   promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
 * SUCH DAMAGE.
 */
package ${packageBaseObject};

#if ($table.BaseClass == "")
  #set ($extendsBaseClass = "" )
#else
  #set ($extendsBaseClass = "extends $table.BaseClass" )
#end

import java.math.BigDecimal;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

#if ($addSaveMethod)
import org.apache.commons.lang.ObjectUtils;
#end
#if ($addIntakeRetrievable)
import $retrievableInterface;
#end
#if (!$complexObjectModel)
import org.apache.torque.Torque;
#end
import org.apache.torque.TorqueException;
import org.apache.torque.om.BaseObject;
import org.apache.torque.om.ComboKey;
import org.apache.torque.om.DateKey;
import org.apache.torque.om.NumberKey;
import org.apache.torque.om.ObjectKey;
import org.apache.torque.om.SimpleKey;
import org.apache.torque.om.StringKey;
import org.apache.torque.om.Persistent;
import org.apache.torque.util.Criteria;
import org.apache.torque.util.Transaction;

#if ($packageBaseObject != $packageObject)
import ${packageObject}.*;
#end

#if ($packageBaseObject != $packagePeer)
import ${packagePeer}.*;
#end

#set ($currentPackage = $table.Database.Package)
#foreach ($col in $table.Columns)
  #if ($col.isForeignKey())
    #set ($fkPackage = $table.Database.getTable($col.RelatedTableName).getPackage())
      #if  (!$fkPackage.equals($currentPackage) )
import ${fkPackage}.${table.Database.getTable($col.RelatedTableName).JavaName};
import ${fkPackage}.${table.Database.getTable($col.RelatedTableName).JavaName}Peer;
      #end
  #end
#end

#if ($generateBeans)
  $generator.parse("om/bean/ObjectBeanImports.vm",$path,"child",$child)
#end

/**
#if ($addTimeStamp)
 * This class was autogenerated by Torque on:
 *
 * [$now]
 *
#end
 * You should not use this class directly.  It should not even be
 * extended all references should be to $table.JavaName
 */
@SuppressWarnings("unused")
public abstract class $basePrefix$table.JavaName $extendsBaseClass
#if ($addIntakeRetrievable)
    implements $retrievableInterface
#end
{
    /** The Peer class */
    private static final ${table.JavaName}Peer peer =
        new ${table.JavaName}Peer();

#if (!$table.isAlias())
  ## member variables
  #foreach ($col in $table.Columns)
    #set ( $cjtype = $col.JavaNative )
    #set ( $clo=$col.UncapitalisedJavaName )
    #set ($defVal = "")
    #if ($col.DefaultValue && !$col.DefaultValue.equalsIgnoreCase("NULL") )
      #set ( $quote = '' )
      #if ( $cjtype == "String" )
        #set ( $quote = '"' )
      #end
      #set ( $defaultValue = $col.DefaultValue )
      #if ( $cjtype == "boolean" || $cjtype == "Boolean" )
        #if ( $defaultValue == "1" || $defaultValue == "Y" )
          #set ( $defaultValue = "true" )
        #elseif ( $defaultValue == "0" || $defaultValue == "N" )
          #set ( $defaultValue = "false" )
        #end
      #end
      #if ($cjtype == "BigDecimal")
        #set ($defVal = "= new BigDecimal($defaultValue)")
      #elseif ($cjtype == "NumberKey")
        #set ( $quote = '"' )
        #set ($defVal = "= new NumberKey($quote$defaultValue$quote)")
      #elseif ($cjtype == "StringKey")
        #set ( $quote = '"' )
        #set ($defVal = "= new StringKey($quote$defaultValue$quote)")
      #elseif ($cjtype == 'Byte')
        #set ($defVal = "= new ${cjtype}((byte) $defaultValue)")
      #elseif ($cjtype == "Short")
        #set ( $quote = '"' )
        #set ($defVal = "= new Short($quote$defaultValue$quote)")
      #else
        #if (!$col.isPrimitive() && $cjtype != "String")
          #set ( $defaultValue = "new ${cjtype}($defaultValue)" )
        #end
        #set ($defVal = " = $quote$defaultValue$quote")
      #end
    #end

    /** The value for the $clo field */
    private $cjtype $clo$defVal;
  #end

  ## getter and setter methods
  #foreach ($col in $table.Columns)
    #set ( $cfc=$col.JavaName )
    #set ( $clo=$col.UncapitalisedJavaName )
    #set ( $cjtype = $col.JavaNative )
    #if ( $col.isProtected() )
      #set ( $accessLevel = "protected" )
    #else
      #set ( $accessLevel = "public" )
    #end

    /**
     * Get the $cfc
     *
     * @return $cjtype
     */
    $accessLevel $cjtype ${col.GetterName}()
    {
        return $clo;
    }

    #set ( $throwsClause = "" )
    #if ($complexObjectModel)
      #if ($col.isForeignKey())
        #set ( $throwsClause = "throws TorqueException" )
      #end
      #if ( $col.Referrers.size() > 0 )
        #if ($throwsClause == "")
          #set ( $throwsClause = "throws TorqueException" )
        #end
      #end
    #end

    /**
     * Set the value of $cfc
     *
     * @param v new value
     */
    $accessLevel void ${col.SetterName}($cjtype v) $throwsClause
    {
    #if (($cjtype == "NumberKey") || ($cjtype == "StringKey") || ($cjtype == "DateKey"))
        if (v != null && v.getValue() == null)
        {
            // If this is an Objectkey than this set method is
            // probably storing the id of this object or some
            // associated object.  If the objectKey value is null
            // then we convert the parameter to null so that this
            // property is consistently null to indicate that no
            // object is associated or defined.
            v = null;
        }
    #end

    #if ($addSaveMethod)
      #if ($col.isPrimitive())
        if (this.$clo != v)
      #else
        if (!ObjectUtils.equals(this.$clo, v))
      #end
        {
            this.$clo = v;
            setModified(true);
        }
    #else
        this.$clo = v;
    #end

    #if ($complexObjectModel)
      #if ($col.isForeignKey())
        #set ( $tblFK = $table.Database.getTable($col.RelatedTableName) )
        #set ($interfaceName = $tblFK.JavaName)
        #if ($tblFK.Interface)
          #set ($interfaceName = $tblFK.Interface)
        #end
        #set ( $colFK = $tblFK.getColumn($col.RelatedColumnName) )
        #if ($col.isMultipleFK() || $col.RelatedTableName.equals($table.Name))
          #set ( $relCol = "" )
          #foreach ($columnName in $col.foreignKey.LocalColumns)
            #set ( $column = $table.getColumn($columnName) )
            #set ( $relCol = "$relCol$column.JavaName" )
          #end
          #if ($relCol != "")
            #set ( $relCol = "RelatedBy$relCol" )
          #end
          #set ( $varName = "a${interfaceName}$relCol" )
        #else
          #set ( $varName = "a$interfaceName" )
        #end

        #if($colFK.Primitive)
        if ($varName != null && !(${varName}.${colFK.GetterName}() == v))
        #else
        if ($varName != null && !ObjectUtils.equals(${varName}.${colFK.GetterName}(), v))
        #end
        {
            $varName = null;
        }
      #end

      #foreach ($fk in $col.Referrers)
        #set ( $fkColName = $fk.ForeignLocalMapping.get($col.Name) )
        #set ( $tblFK = $fk.Table )
        #if ( !($tblFK.Name.equals($table.Name)) )
          #set ( $colFK = $tblFK.getColumn($fkColName) )
          #if ($colFK.isMultipleFK())
            #set ( $collName = "coll${tblFK.JavaName}sRelatedBy$colFK.JavaName" )
          #else
            #set ( $collName = "coll${tblFK.JavaName}s" )
          #end

          #if ($objectIsCaching)
        // update associated $tblFK.JavaName
        if ($collName != null)
        {
            for (int i = 0; i < ${collName}.size(); i++)
            {
                ((${tblFK.JavaName}) ${collName}.get(i))
                    .${colFK.SetterName}(v);
            }
        }
          #end
        #end
      #end
    #end
    }
  #end
#end

## association code
#if ($complexObjectModel)
  #set($pVars = [])  ## Array of object set method names for later reference.
  #set($aVars = [])  ## Array of object field names for later reference.
  #foreach ($fk in $table.ForeignKeys)

    #set ( $tblFK = $table.Database.getTable($fk.ForeignTableName) )
    #set ( $className = $tblFK.JavaName )
    #set ($interfaceName = $tblFK.JavaName)
    #if ($tblFK.Interface)
      #set ($interfaceName = $tblFK.Interface)
    #end

    #set ( $relCol = "" )
    #foreach ($columnName in $fk.LocalColumns)
      #set ( $column = $table.getColumn($columnName) )
      #if ($column.isMultipleFK() || $fk.ForeignTableName.equals($table.Name))
        #set ( $relCol = "$relCol$column.JavaName" )
      #end
    #end

    #if ($relCol != "")
      #set ( $relCol = "RelatedBy$relCol" )
    #end

    #set ( $pVarName = "$interfaceName$relCol" )
    #set ( $varName = "a$pVarName" )
    #set ( $retVal = $pVars.add($pVarName) )
    #set ( $retVal = $aVars.add($varName) )
    private $interfaceName $varName;

    /**
     * Declares an association between this object and a $interfaceName object
     *
     * @param v $interfaceName
     * @throws TorqueException
     */
    public void set${pVarName}($interfaceName v) throws TorqueException
    {
    #foreach ($columnName in $fk.LocalColumns)
      #set ( $column = $table.getColumn($columnName) )
      #set ( $colFKName = $fk.LocalForeignMapping.get($columnName) )
      #set ( $colFK = $tblFK.getColumn($colFKName) )
      #set ( $fktype = $colFK.JavaNative )
      #set ( $casttype = "" )
        if (v == null)
        {
      #if($colFK.Primitive)
        #if ($fktype == "short")
          #set ($casttype = "(short)")
        #elseif($fktype == "byte")
          #set ($casttype = "(byte)")
        #end
        #set ($coldefval =  "0")
        #set ($coldefval = $column.DefaultValue)
            ${column.SetterName}($casttype $coldefval);
      #else
            ${column.SetterName}(($column.JavaNative) null);
      #end
        }
        else
        {
            ${column.SetterName}(v.${colFK.GetterName}());
        }
    #end
        $varName = v;
    }

    #set ( $and = "" )
    #set ( $comma = "" )
    #set ( $conditional = "" )
    #set ( $arglist = "" )
    #set ( $argsize = 0 )
    #foreach ($columnName in $fk.LocalColumns)
      #set ( $column = $table.getColumn($columnName) )
      #set ( $cjtype = $column.JavaNative )
      #set ( $clo=$column.UncapitalisedJavaName )
      #if ($cjtype == "short" || $cjtype == "int" || $cjtype == "long" || $cjtype == "byte" || $cjtype == "float" || $cjtype == "double")
        #set ( $conditional = "$conditional${and}this.${clo} != 0" )
      #else
        #set ( $conditional = "$conditional${and}!ObjectUtils.equals(this.${clo}, null)" )
      #end
      #set ( $arglist = "$arglist${comma}this.$clo" )
      #set ( $and = " && " )
      #set ( $comma = ", " )
      #set ( $argsize = $argsize + 1 )
    #end

    /**
     * Returns the associated $interfaceName object.
      #if ($silentDbFetch)
     * If it was not retrieved before, the object is retrieved from
     * the database
      #end
     *
     * @return the associated $interfaceName object
      #if ($silentDbFetch)
     * @throws TorqueException
      #end
     */
    public $interfaceName get${pVarName}()
      #if ($silentDbFetch)
        throws TorqueException
      #end
    {
      #if ($silentDbFetch)
        if ($varName == null && ($conditional))
        {
        #if ($tblFK.isAlias())
          #if ($argsize > 1)
            $varName = ${className}Peer.retrieve${className}ByPK($arglist);
          #else
            $varName = ${className}Peer.retrieve${className}ByPK(SimpleKey.keyFor($arglist));
          #end
        #else
          #if ($argsize > 1)
            $varName = ${className}Peer.retrieveByPK($arglist);
          #else
            $varName = ${className}Peer.retrieveByPK(SimpleKey.keyFor($arglist));
          #end
        #end

            /* The following can be used instead of the line above to
               guarantee the related object contains a reference
               to this object, but this level of coupling
               may be undesirable in many circumstances.
               As it can lead to a db query with many results that may
               never be used.
               $className obj = ${className}Peer.retrieveByPK($arglist);
               obj.add${pCollName}(this);
            */
        }
      #end
        return $varName;
    }

    /**
     * Return the associated $interfaceName object
     * If it was not retrieved before, the object is retrieved from
     * the database using the passed connection
     *
     * @param connection the connection used to retrieve the associated object
     *        from the database, if it was not retrieved before
     * @return the associated $interfaceName object
     * @throws TorqueException
     */
    public $interfaceName get${pVarName}(Connection connection)
        throws TorqueException
    {
        if ($varName == null && ($conditional))
        {
      #if ($tblFK.isAlias())
        #if ($argsize > 1)
            $varName = ${className}Peer.retrieve${className}ByPK($arglist, connection);
        #else
            $varName = ${className}Peer.retrieve${className}ByPK(SimpleKey.keyFor($arglist), connection);
        #end
      #else
        #if ($argsize > 1)
            $varName = ${className}Peer.retrieveByPK($arglist, connection);
        #else
            $varName = ${className}Peer.retrieveByPK(SimpleKey.keyFor($arglist), connection);
        #end
      #end

            /* The following can be used instead of the line above to
               guarantee the related object contains a reference
               to this object, but this level of coupling
               may be undesirable in many circumstances.
               As it can lead to a db query with many results that may
               never be used.
               $className obj = ${className}Peer.retrieveByPK($arglist, connection);
               obj.add${pCollName}(this);
            */
        }
        return $varName;
    }

    /**
     * Provides convenient way to set a relationship based on a
     * ObjectKey, for example
     * <code>bar.setFooKey(foo.getPrimaryKey())</code>
     *
    #if ($fk.LocalColumns.size() > 1)
     * Note: It is important that the xml schema used to create this class
     * maintains consistency in the order of related columns between
     * $table.Name and ${tblFK.Name}.
     * If for some reason this is impossible, this method should be
     * overridden in <code>$table.JavaName</code>.
    #end
     */
    public void set${pVarName}Key(ObjectKey key) throws TorqueException
    {
      #if ($fk.LocalColumns.size() > 1)
        SimpleKey[] keys = (SimpleKey[]) key.getValue();
        #set ($i = 0)
        #foreach ($colName in $fk.LocalColumns)
          #set ($col = $table.getColumn($colName) )

          #set ($fktype = $col.JavaNative)
          #if ($fktype == "short")
        ${col.SetterName}(((NumberKey) keys[$i]).shortValue());
          #elseif($fktype == "int")
        ${col.SetterName}(((NumberKey) keys[$i]).intValue());
          #elseif($fktype == "long")
        ${col.SetterName}(((NumberKey) keys[$i]).longValue());
          #elseif($fktype == "BigDecimal")
        ${col.SetterName}(((NumberKey) keys[$i]).getBigDecimal());
          #elseif($fktype == "byte")
        ${col.SetterName}(((NumberKey) keys[$i]).byteValue());
          #elseif($fktype == "float")
        ${col.SetterName}(((NumberKey) keys[$i]).floatValue());
          #elseif($fktype == "double")
        ${col.SetterName}(((NumberKey) keys[$i]).doubleValue());
          #elseif($fktype == "Short")
        ${col.SetterName}(new Short(((NumberKey) keys[$i]).shortValue()));
          #elseif($fktype == "Integer")
        ${col.SetterName}(new Integer(((NumberKey) keys[$i]).intValue()));
          #elseif($fktype == "Long")
        ${col.SetterName}(new Long(((NumberKey) keys[$i]).longValue()));
          #elseif($fktype == "Byte")
        ${col.SetterName}(new Byte(((NumberKey) keys[$i]).byteValue()));
          #elseif($fktype == "Float")
        ${col.SetterName}(new Float(((NumberKey) keys[$i]).floatValue()));
          #elseif($fktype == "Double")
        ${col.SetterName}(new Double(((NumberKey) keys[$i]).doubleValue()));
          #elseif($fktype == "String")
        ${col.SetterName}(keys[$i].toString());
          #elseif($fktype == "Date")
        ${col.SetterName}(((DateKey)keys[$i]).getDate());
          #end
          #set ( $i = $i + 1 )
        #end
      #else
        #set ($colName = $fk.LocalColumns.get(0))
        #set ($col = $table.getColumn($colName) )

        #set ($fktype = $col.JavaNative)
        #if ($fktype == "short")
        ${col.SetterName}(((NumberKey) key).shortValue());
        #elseif($fktype == "int")
        ${col.SetterName}(((NumberKey) key).intValue());
        #elseif($fktype == "long")
        ${col.SetterName}(((NumberKey) key).longValue());
        #elseif($fktype == "BigDecimal")
        ${col.SetterName}(((NumberKey) key).getBigDecimal());
        #elseif($fktype == "byte")
        ${col.SetterName}(((NumberKey) key).byteValue());
        #elseif($fktype == "float")
        ${col.SetterName}(((NumberKey) key).floatValue());
        #elseif($fktype == "double")
        ${col.SetterName}(((NumberKey) key).doubleValue());
        #elseif($fktype == "Short")
        ${col.SetterName}(new Short(((NumberKey) key).shortValue()));
        #elseif($fktype == "Integer")
        ${col.SetterName}(new Integer(((NumberKey) key).intValue()));
        #elseif($fktype == "Long")
        ${col.SetterName}(new Long(((NumberKey) key).longValue()));
        #elseif($fktype == "Byte")
        ${col.SetterName}(new Byte(((NumberKey) key).byteValue()));
        #elseif($fktype == "Float")
        ${col.SetterName}(new Float(((NumberKey) key).floatValue()));
        #elseif($fktype == "Double")
        ${col.SetterName}(new Double(((NumberKey) key).doubleValue()));
        #elseif($fktype == "String")
        ${col.SetterName}(key.toString());
        #elseif($fktype == "Date")
        ${col.SetterName}(((DateKey)key).getDate());
        #end
      #end
    }
    #end   ## end of foreach loop over foreign keys

  ##
  ## setup foreign key associations
  ##
  #foreach ($fk in $table.Referrers)
    #set ( $tblFK = $fk.Table )
    #if ( !($tblFK.Name.equals($table.Name)) )
      #set ( $className = $tblFK.JavaName )
      #set ( $relatedByCol = "" )
      #foreach ($columnName in $fk.LocalColumns)
        #set ( $column = $tblFK.getColumn($columnName) )
        #if ($column.isMultipleFK())
          #set ($relatedByCol= "$relatedByCol$column.JavaName")
        #end
      #end

      #if ($relatedByCol == "")
        #set ( $suffix = "" )
        #set ( $relCol = "${className}s" )
        #set ( $relColMs = $className )
      #else
        #set ( $suffix = "RelatedBy$relatedByCol" )
        #set ( $relCol= "${className}sRelatedBy$relatedByCol" )
        #set ( $relColMs= "${className}RelatedBy$relatedByCol" )
      #end
      #set ( $collName = "coll$relCol" )

      #if ($objectIsCaching)
    /**
     * Collection to store aggregation of $collName
     */
    protected List<${className}> $collName;

    /**
     * Temporary storage of $collName to save a possible db hit in
     * the event objects are add to the collection, but the
     * complete collection is never requested.
     */
    protected void init${relCol}()
    {
        if ($collName == null)
        {
            $collName = new ArrayList<${className}>();
        }
    }

    #set ($interfaceName = $table.JavaName)
    #if ($table.Interface)
      #set ($interfaceName = $table.Interface)
    #end

    /**
     * Method called to associate a $tblFK.JavaName object to this object
     * through the $className foreign key attribute
     *
     * @param l $className
     * @throws TorqueException
     */
    public void add${relColMs}($className l) throws TorqueException
    {
        get${relCol}().add(l);
        l.set${interfaceName}${suffix}(($table.JavaName) this);
    }

    /**
     * The criteria used to select the current contents of $collName
     */
    private Criteria last${relCol}Criteria = null;
      #end

    /**
      #if ($objectIsCaching)
        #if (!$silentDbFetch)
     * returns the Collection.
        #else
     * If this collection has already been initialized, returns
     * the collection. Otherwise returns the results of
     * get${relCol}(new Criteria())
        #end
      #else
     * A wrapper for get${relCol}(new Criteria())
      #end
     *
     * @return the collection of associated objects
      #if ($silentDbFetch)
     * @throws TorqueException
      #end
     */
    public List<${className}> get${relCol}()
      #if ($silentDbFetch)
        throws TorqueException
      #end
    {
      #if ($objectIsCaching)
        #if (!$silentDbFetch)
        if (isNew())
        {
            init${relCol}();
        }
        #else
        if ($collName == null)
        {
            $collName = get${relCol}(new Criteria(10));
        }
        #end
        return $collName;
      #else
        return get${relCol}(new Criteria(10));
      #end
    }

    /**
      #if ($objectIsCaching)
     * If this collection has already been initialized with
     * an identical criteria, it returns the collection.
     * Otherwise if this $table.JavaName has previously
      #else
     * If this $table.JavaName has previously
      #end
     * been saved, it will retrieve related ${relCol} from storage.
     * If this $table.JavaName is new, it will return
     * an empty collection or the current collection, the criteria
     * is ignored on a new object.
     *
     * @throws TorqueException
     */
    public List<${className}> get${relCol}(Criteria criteria) throws TorqueException
    {
      #if ($objectIsCaching)
        if ($collName == null)
        {
            if (isNew())
            {
               $collName = new ArrayList<${className}>();
            }
            else
            {
        #foreach ($columnName in $fk.ForeignColumns)
          #set ( $column = $table.getColumn($columnName) )
          #set ( $colFKName = $fk.ForeignLocalMapping.get($columnName) )
          #set ( $colFK = $tblFK.getColumn($colFKName) )
                criteria.add(${className}Peer.${colFK.Name.toUpperCase()}, ${column.GetterName}() );
        #end
                $collName = ${className}Peer.doSelect(criteria);
            }
        }
        else
        {
            // criteria has no effect for a new object
            if (!isNew())
            {
                // the following code is to determine if a new query is
                // called for.  If the criteria is the same as the last
                // one, just return the collection.
      #end
      #foreach ($columnName in $fk.ForeignColumns)
        #set ( $column = $table.getColumn($columnName) )
        #set ( $colFKName = $fk.ForeignLocalMapping.get($columnName) )
        #set ( $colFK = $tblFK.getColumn($colFKName) )
                criteria.add(${className}Peer.${colFK.Name.toUpperCase()}, ${column.GetterName}());
      #end
      #if ($objectIsCaching)
                if (!last${relCol}Criteria.equals(criteria))
                {
                    $collName = ${className}Peer.doSelect(criteria);
                }
            }
        }
        last${relCol}Criteria = criteria;

        return $collName;
      #else
                return ${className}Peer.doSelect(criteria);
      #end
    }

    /**
      #if ($objectIsCaching)
     * If this collection has already been initialized, returns
     * the collection. Otherwise returns the results of
     * get${relCol}(new Criteria(),Connection)
      #else
     * A wrapper for get${relCol}(new Criteria(),Connection)
      #end
     * This method takes in the Connection also as input so that
     * referenced objects can also be obtained using a Connection
     * that is taken as input
     */
    public List<${className}> get${relCol}(Connection con) throws TorqueException
    {
      #if ($objectIsCaching)
        if ($collName == null)
        {
            $collName = get${relCol}(new Criteria(10), con);
        }
        return $collName;
      #else
        return get${relCol}(new Criteria(10), con);
      #end
    }

    /**
      #if ($objectIsCaching)
     * If this collection has already been initialized with
     * an identical criteria, it returns the collection.
     * Otherwise if this $table.JavaName has previously
      #else
     * If this $table.JavaName has previously
      #end
     * been saved, it will retrieve related ${relCol} from storage.
     * If this $table.JavaName is new, it will return
     * an empty collection or the current collection, the criteria
     * is ignored on a new object.
     * This method takes in the Connection also as input so that
     * referenced objects can also be obtained using a Connection
     * that is taken as input
     */
    public List<${className}> get${relCol}(Criteria criteria, Connection con)
            throws TorqueException
    {
      #if ($objectIsCaching)
        if ($collName == null)
        {
            if (isNew())
            {
               $collName = new ArrayList<${className}>();
            }
            else
            {
        #foreach ($columnName in $fk.ForeignColumns)
          #set ( $column = $table.getColumn($columnName) )
          #set ( $colFKName = $fk.ForeignLocalMapping.get($columnName) )
          #set ( $colFK = $tblFK.getColumn($colFKName) )
                 criteria.add(${className}Peer.${colFK.Name.toUpperCase()}, ${column.GetterName}());
        #end
                 $collName = ${className}Peer.doSelect(criteria, con);
             }
         }
         else
         {
             // criteria has no effect for a new object
             if (!isNew())
             {
                 // the following code is to determine if a new query is
                 // called for.  If the criteria is the same as the last
                 // one, just return the collection.
      #end
      #foreach ($columnName in $fk.ForeignColumns)
        #set ( $column = $table.getColumn($columnName) )
        #set ( $colFKName = $fk.ForeignLocalMapping.get($columnName) )
        #set ( $colFK = $tblFK.getColumn($colFKName) )
                 criteria.add(${className}Peer.${colFK.Name.toUpperCase()}, ${column.GetterName}());
      #end
      #if ($objectIsCaching)
                 if (!last${relCol}Criteria.equals(criteria))
                 {
                     $collName = ${className}Peer.doSelect(criteria, con);
                 }
             }
         }
         last${relCol}Criteria = criteria;

         return $collName;
      #else
                 return ${className}Peer.doSelect(criteria, con);
      #end
     }

      #set ( $countFK = 0 )
      #foreach ($dummyFK in $tblFK.ForeignKeys)
        #set ( $countFK = $countFK + 1 )
      #end

## ------------------------------------------------------------
##
      #if ($countFK >= 1)
        #set ( $lastTable = "" )
        #foreach ($fk2 in $tblFK.ForeignKeys)

          ## Add join methods if the fk2 table is not this table or
          ## the fk2 table references this table multiple times.

          #set ( $doJoinGet = true )
          #if ( $fk2.ForeignTableName.equals($table.Name) )
            #set ( $doJoinGet = false )
          #end

          #foreach ($columnName in $fk2.LocalColumns)
            #set ( $column = $tblFK.getColumn($columnName) )
            #if ($column.isMultipleFK())
              #set ( $doJoinGet = true )
            #end
          #end

          #set ( $tblFK2 = $table.Database.getTable($fk2.ForeignTableName) )
          #if ($tblFK2.isForReferenceOnly())
            #set ($doJoinGet = false)
          #else
            #set ($doJoinGet = true)
          #end
          #set ( $relatedByCol2 = "" )
          #foreach ($columnName in $fk2.LocalColumns)
            #set ( $column = $tblFK.getColumn($columnName) )
            #if ($column.isMultipleFK())
              #set($relatedByCol2 = "$relatedByCol2$column.JavaName")
            #end
          #end

          #set ( $fkClassName = $tblFK2.JavaName )
          ## do not generate code for self-referencing fk's, it would be
          ## good to do, but it is just not implemented yet.
          #if ($className == $fkClassName)
            #set ( $doJoinGet = false )
          #end

          #if ($relatedByCol2 == "")
            #set ( $relCol2 = $fkClassName )
          #else
            #set ($relCol2 = "${fkClassName}RelatedBy$relatedByCol2")
          #end

          #if ( $relatedByCol == "")
          #else
            #if ( $relatedByCol.equals($relatedByCol2) )
              #set ( $doJoinGet = false )
            #end
          #end

          #if ($doJoinGet)

    /**
            #if ($objectIsCaching)
     * If this collection has already been initialized with
     * an identical criteria, it returns the collection.
     * Otherwise if this $table.JavaName is new, it will return
            #else
     * If this $table.JavaName is new, this method will return
            #end
     * an empty collection; or if this $table.JavaName has previously
     * been saved, it will retrieve related ${relCol} from storage.
     *
     * This method is protected by default in order to keep the public
     * api reasonable.  You can provide public methods for those you
     * actually need in ${table.JavaName}.
     */
    protected List get${relCol}Join${relCol2}(Criteria criteria)
        throws TorqueException
    {
            #if ($objectIsCaching)
        if ($collName == null)
        {
            if (isNew())
            {
               $collName = new ArrayList<${className}>();
            }
            else
            {
              #foreach ($columnName in $fk.ForeignColumns)
                #set ( $column = $table.getColumn($columnName) )
                #set ( $colFKName = $fk.ForeignLocalMapping.get($columnName) )
                #set ( $colFK = $tblFK.getColumn($colFKName) )
                criteria.add(${className}Peer.${colFK.Name.toUpperCase()}, ${column.GetterName}());
              #end
                $collName = ${className}Peer.doSelectJoin${relCol2}(criteria);
            }
        }
        else
        {
            // the following code is to determine if a new query is
            // called for.  If the criteria is the same as the last
            // one, just return the collection.
            #end
            #foreach ($columnName in $fk.ForeignColumns)
              #set ( $column = $table.getColumn($columnName) )
              #set ( $colFKName = $fk.ForeignLocalMapping.get($columnName) )
              #set ( $colFK = $tblFK.getColumn($colFKName) )
            criteria.add(${className}Peer.${colFK.Name.toUpperCase()}, ${column.GetterName}());
            #end
            #if ($objectIsCaching)
            if (!last${relCol}Criteria.equals(criteria))
            {
                $collName = ${className}Peer.doSelectJoin${relCol2}(criteria);
            }
        }
        last${relCol}Criteria = criteria;

        return $collName;
            #else
        return ${className}Peer.doSelectJoin${relCol2}(criteria);
            #end
    }
          #end
        #end
      #end
    #end

## ===========================================================
#*
  #if ($countFK > 2)

    /**
    #if ($objectIsCaching)
     * If this collection has already been initialized with
     * an identical criteria, it returns the collection.
     * Otherwise if this $table.JavaName is new, it will return
    #else
     * If this $table.JavaName is new, this method will return
    #end
    * an empty collection; or if this $table.JavaName has previously
     * been saved, it will retrieve related ${relCol} from storage.
     *
     * This method is protected by default in order to keep the public
     * api reasonable.  You can provide public methods for those you
     * actually need in ${table.JavaName}.
     */
    protected List get${relCol}JoinAllExcept${table.JavaName}(Criteria criteria)
        throws TorqueException
    {
    #if ($objectIsCaching)
        if ($collName == null)
        {
            if (isNew())
            {
               $collName = new ArrayList<${className}>();
            }
            else
            {
     #foreach ($columnName in $fk.ForeignColumns)
         #set ( $column = $table.getColumn($columnName) )
         #set ( $colFKName = $fk.ForeignLocalMapping.get($columnName) )
         #set ( $colFK = $tblFK.getColumn($colFKName) )
                criteria.add(${className}Peer.${colFK.Name.toUpperCase()}, ${column.GetterName}());
     #end
                $collName = ${className}Peer.doSelectJoinAllExcept${table.JavaName}${suffix}(criteria);
            }
        }
        else
        {
            // the following code is to determine if a new query is
            // called for.  If the criteria is the same as the last
            // one, just return the collection.
   #end

   #foreach ($columnName in $fk.ForeignColumns)
       #set ( $column = $table.getColumn($columnName) )
       #set ( $colFKName = $fk.ForeignLocalMapping.get($columnName) )
       #set ( $colFK = $tblFK.getColumn($colFKName) )
                criteria.add(${className}Peer.${colFK.Name.toUpperCase()}, ${column.GetterName}());
   #end
   #if ($objectIsCaching)
            if (!last${relCol}Criteria.equals(criteria))
            {
                $collName = ${className}Peer.doSelectJoinAllExcept${table.JavaName}${suffix}(criteria);
            }
        }
        last${relCol}Criteria = criteria;

        return $collName;
   #else
        return ${className}Peer.doSelectJoinAllExcept${table.JavaName}${suffix}(criteria);
   #end
    }

  #end

*#
## ------------------------------------------------------------

  #end    ## ends foreach over table.Referrers
#end    ##ends the if(complexObjectModel)

##
## getByName code
##
#if (!$table.isAlias() && $addGetByNameMethod)
    private static List<String> fieldNames = null;

    /**
     * Generate a list of field names.
     *
     * @return a list of field names
     */
    public static synchronized List getFieldNames()
    {
        if (fieldNames == null)
        {
            fieldNames = new ArrayList<String>();
  #foreach ($col in $table.Columns)
            fieldNames.add("${col.JavaName}");
  #end
            fieldNames = Collections.unmodifiableList(fieldNames);
        }
        return fieldNames;
    }

    /**
     * Retrieves a field from the object by name passed in as a String.
     *
     * @param name field name
     * @return value
     */
    public Object getByName(String name)
    {
  #foreach ($col in $table.Columns)
    #set ( $cjtype = $col.JavaNative )
        if (name.equals("${col.JavaName}"))
        {
    #if ($cjtype == "int")
            return new Integer(${col.GetterName}());
    #elseif ($cjtype == "long")
            return new Long(${col.GetterName}());
    #elseif ($cjtype == "float")
            return new Float(${col.GetterName}());
    #elseif ($cjtype == "double")
            return new Double(${col.GetterName}());
    #elseif ($cjtype == "boolean")
            return Boolean.valueOf(${col.GetterName}());
    #elseif ($cjtype == "short")
            return new Short(${col.GetterName}());
    #elseif ($cjtype == "byte")
            return new Byte(${col.GetterName}());
    #elseif ($cjtype == "char")
            return new Character(${col.GetterName}());
    #else
            return ${col.GetterName}();
    #end
        }
  #end
        return null;
    }

    /**
     * Retrieves a field from the object by name passed in
     * as a String.  The String must be one of the static
     * Strings defined in this Class' Peer.
     *
     * @param name peer name
     * @return value
     */
    public Object getByPeerName(String name)
    {
  #foreach ($col in $table.Columns)
    #set ( $cup=$col.Name.toUpperCase() )
    #set ( $cjtype = $col.JavaNative )
        if (name.equals(${table.JavaName}Peer.$cup))
        {
    #if ($cjtype == "int")
            return new Integer(${col.GetterName}());
    #elseif ($cjtype == "long")
            return new Long(${col.GetterName}());
    #elseif ($cjtype == "float")
            return new Float(${col.GetterName}());
    #elseif ($cjtype == "double")
            return new Double(${col.GetterName}());
    #elseif ($cjtype == "boolean")
            return Boolean.valueOf(${col.GetterName}());
    #elseif ($cjtype == "short")
            return new Short(${col.GetterName}());
    #elseif ($cjtype == "byte")
            return new Byte(${col.GetterName}());
    #elseif ($cjtype == "char")
            return new Character(${col.GetterName}());
    #else
            return ${col.GetterName}();
    #end
        }
  #end
        return null;
    }

    /**
     * Retrieves a field from the object by Position as specified
     * in the xml schema.  Zero-based.
     *
     * @param pos position in xml schema
     * @return value
     */
    public Object getByPosition(int pos)
    {
  #set ($i = 0)
  #foreach ($col in $table.Columns)
    #set ( $cjtype = $col.JavaNative )
        if (pos == $i)
        {
    #if ($cjtype == "int")
            return new Integer(${col.GetterName}());
    #elseif ($cjtype == "long")
            return new Long(${col.GetterName}());
    #elseif ($cjtype == "float")
            return new Float(${col.GetterName}());
    #elseif ($cjtype == "double")
            return new Double(${col.GetterName}());
    #elseif ($cjtype == "boolean")
            return Boolean.valueOf(${col.GetterName}());
    #elseif ($cjtype == "short")
            return new Short(${col.GetterName}());
    #elseif ($cjtype == "byte")
            return new Byte(${col.GetterName}());
    #elseif ($cjtype == "char")
            return new Character(${col.GetterName}());
    #else
            return ${col.GetterName}();
    #end
        }
    #set ($i = $i + 1)
  #end
        return null;
    }
#end     ## ends the if(addGetByNameMethod)

#if (!$table.isAlias() && $addSaveMethod)
    /**
     * Stores the object in the database.  If the object is new,
     * it inserts it; otherwise an update is performed.
     *
     * @throws $saveException
     */
    public void save() throws $saveException
    {
  #if ($complexObjectModel)
        save(${table.JavaName}Peer.getMapBuilder()
                .getDatabaseMap().getName());
  #else
        if (isModified())
        {
            if (isNew())
            {
                ${table.JavaName}Peer.doInsert(($table.JavaName) this);
                setNew(false);
            }
            else
            {
                ${table.JavaName}Peer.doUpdate(($table.JavaName) this);
            }
        }
  #end
    }

    /**
     * Stores the object in the database.  If the object is new,
     * it inserts it; otherwise an update is performed.
  #if ($complexObjectModel)
     * Note: this code is here because the method body is
     * auto-generated conditionally and therefore needs to be
     * in this file instead of in the super class, BaseObject.
  #end
     *
     * @param dbName
     * @throws TorqueException
     */
    public void save(String dbName) throws TorqueException
    {
        Connection con = null;
  #if ($complexObjectModel)
        try
        {
            con = Transaction.begin(dbName);
            save(con);
            Transaction.commit(con);
        }
        catch(TorqueException e)
        {
            Transaction.safeRollback(con);
            throw e;
        }
  #else
        if (isModified())
        {
            try
            {
                con = Torque.getConnection(dbName);
                if (isNew())
                {
                    ${table.JavaName}Peer
                        .doInsert(($table.JavaName) this, con);
                    setNew(false);
                }
                else
                {
                    ${table.JavaName}Peer
                        .doUpdate(($table.JavaName) this, con);
                }
            }
            finally
            {
                Torque.closeConnection(con);
            }
        }
  #end
    }

  #if ($complexObjectModel)
    /** flag to prevent endless save loop, if this object is referenced
        by another object which falls in this transaction. */
    private boolean alreadyInSave = false;
  #end
    /**
     * Stores the object in the database.  If the object is new,
     * it inserts it; otherwise an update is performed.  This method
     * is meant to be used as part of a transaction, otherwise use
     * the save() method and the connection details will be handled
     * internally
     *
     * @param con
     * @throws TorqueException
     */
    public void save(Connection con) throws TorqueException
    {
  #if ($complexObjectModel)
        if (!alreadyInSave)
        {
            alreadyInSave = true;

#* FIXME! the following code can cause an infinite loop, needs more thought
shows the infinite loop: System.out.println("Entering save for " + this);
    #if ($pVars.size() != 0)

        // We call the save method on the following object(s) if they
        // were passed to this object by their coresponding set
        // method.  This object relates to these object(s) by a
        // foreign key reference.  If the object(s) being saved were
        // new to the database, an insert was performed, then they may
        // have a new PrimaryKey.  We call the coresponding set method
        // for the given object(s) to set this object's Id reference
        // to this new Primary key so that it will be saved.
      #foreach ($aVarName in $aVars)
        #set($i = $velocityCount - 1)
        if ($aVarName != null)
        {
            ${aVarName}.save(con);
            set$pVars.get($i)($aVarName);
        }
      #end
    #end
*#
  #end

            // If this object has been modified, then save it to the database.
            if (isModified())
            {
                if (isNew())
                {
                    ${table.JavaName}Peer.doInsert(($table.JavaName) this, con);
                    setNew(false);
                }
                else
                {
                    ${table.JavaName}Peer.doUpdate(($table.JavaName) this, con);
                }
  #if ($table.PrimaryKey.size() > 0)
    #set ($tableHasPrimaryKey = true)
  #else
    #set ($tableHasPrimaryKey = false)
  #end
            }

  #if ($complexObjectModel)
    #foreach ($fk in $table.Referrers)
      #set ( $tblFK = $fk.Table )
      #if ( !($tblFK.Name.equals($table.Name)) )
        #set ( $className = $tblFK.JavaName )
        #set ( $relCol = "" )
        #foreach ($columnName in $fk.LocalColumns)
          #set ( $column = $tblFK.getColumn($columnName) )
          #if ($column.isMultipleFK())
            #set ( $relCol = "$relCol$column.JavaName" )
          #end
        #end

        #if ($relCol == "")
          #set ( $relCol = "${className}s" )
        #else
          #set ( $relCol = "${className}sRelatedBy$relCol" )
        #end
        #set ( $collName = "coll$relCol" )
        #if ($objectIsCaching)
            if ($collName != null)
            {
                for (int i = 0; i < ${collName}.size(); i++)
                {
                    ((${className}) ${collName}.get(i)).save(con);
                }
            }
        #end
      #end
    #end
  #end
  #if ($complexObjectModel)
            alreadyInSave = false;
        }
  #end
    }
#end

## PrimaryKey methods
#if (!$table.isAlias())
  #set ( $throwsClause = "" )
  #set ( $argList = "" )
  #set ( $argList2 = "" )
  #set ( $comma = "" )
  #foreach ($col in $table.PrimaryKey)
    #if ($complexObjectModel)
      #if ( $col.isForeignKey() || ($col.Referrers.size() > 0) )
        #set ( $throwsClause = "throws TorqueException" )
      #end
    #end
    #set ( $clo=$col.UncapitalisedJavaName )
    #set ( $cjtype = $col.JavaNative )
    #set ($argList = "${argList}$comma $cjtype $clo")
    #set ($argList2 = "${argList2}$comma String $clo")
    #set ( $comma = "," )
  #end

  #if ($table.PrimaryKey.size() == 1)
    #set ($col = $table.PrimaryKey.get(0) )
    #set ( $clo=$col.UncapitalisedJavaName )
    #set ( $cjtype= $col.JavaNative )
    /**
     * Set the PrimaryKey using ObjectKey.
     *
     * @param key $clo ObjectKey
     */
    public void setPrimaryKey(ObjectKey key)
        $throwsClause
    {
    #if ($cjtype == "short")
        ${col.SetterName}(((NumberKey) key).shortValue());
    #elseif($cjtype == "int")
        ${col.SetterName}(((NumberKey) key).intValue());
    #elseif($cjtype == "long")
        ${col.SetterName}(((NumberKey) key).longValue());
    #elseif($cjtype == "BigDecimal")
        ${col.SetterName}(((NumberKey) key).getBigDecimal());
    #elseif($cjtype == "byte")
        ${col.SetterName}(((NumberKey) key).byteValue());
    #elseif($cjtype == "float")
        ${col.SetterName}(((NumberKey) key).floatValue());
    #elseif($cjtype == "double")
        ${col.SetterName}(((NumberKey) key).doubleValue());
    #elseif($cjtype == "Short")
        ${col.SetterName}(new Short(((NumberKey) key).shortValue()));
    #elseif($cjtype == "Integer")
        ${col.SetterName}(new Integer(((NumberKey) key).intValue()));
    #elseif($cjtype == "Long")
        ${col.SetterName}(new Long(((NumberKey) key).longValue()));
    #elseif($cjtype == "Byte")
        ${col.SetterName}(new Byte(((NumberKey) key).byteValue()));
    #elseif($cjtype == "Float")
        ${col.SetterName}(new Float(((NumberKey) key).floatValue()));
    #elseif($cjtype == "Double")
        ${col.SetterName}(new Double(((NumberKey) key).doubleValue()));
    #elseif($cjtype == "String")
        ${col.SetterName}(key.toString());
    #elseif($cjtype == "Date")
        ${col.SetterName}(((DateKey) key).getDate());
    #else
        ${col.SetterName}(($cjtype) key);
    #end
    }

    /**
     * Set the PrimaryKey using a String.
     *
     * @param key
     */
    public void setPrimaryKey(String key) $throwsClause
    {
    #if ($cjtype == "short")
        ${col.SetterName}(Short.parseShort(key));
    #elseif($cjtype == "int")
        ${col.SetterName}(Integer.parseInt(key));
    #elseif($cjtype == "long")
        ${col.SetterName}(Long.parseLong(key));
    #elseif($cjtype == "BigDecimal")
        ${col.SetterName}(new BigDecimal(key));
    #elseif($cjtype == "byte")
        ${col.SetterName}(Byte.parseByte(key));
    #elseif($cjtype == "float")
        ${col.SetterName}(Float.parseFloat(key));
    #elseif($cjtype == "double")
        ${col.SetterName}(Double.parseDouble(key));
    #elseif($cjtype == "Short")
        ${col.SetterName}(new Short(key));
    #elseif($cjtype == "Integer")
        ${col.SetterName}(new Integer(key));
    #elseif($cjtype == "Long")
        ${col.SetterName}(new Long(key));
    #elseif($cjtype == "Byte")
        ${col.SetterName}(new Byte(key));
    #elseif($cjtype == "Float")
        ${col.SetterName}(new Float(key));
    #elseif($cjtype == "Double")
        ${col.SetterName}(new Double(key));
    #elseif($cjtype == "String")
        ${col.SetterName}(key);
    #elseif($cjtype == "Date")
        ${col.SetterName}(new Date(key));
    #else
        ${col.SetterName}(new ${cjtype}(key));
    #end
    }

  #elseif ($table.PrimaryKey.size() > 1)

    private final SimpleKey[] pks = new SimpleKey[$table.PrimaryKey.size()];
    private final ComboKey comboPK = new ComboKey(pks);

    /**
     * Set the PrimaryKey with an ObjectKey
     *
     * @param key
     */
    public void setPrimaryKey(ObjectKey key) throws TorqueException
    {
        SimpleKey[] keys = (SimpleKey[]) key.getValue();
        SimpleKey tmpKey = null;
    #set ($i = 0)
    #foreach ($pk in $table.PrimaryKey)
      #set ($pktype = $pk.JavaNative)
      #if ($pktype == "short")
        ${pk.SetterName}(((NumberKey)keys[$i]).shortValue());
      #elseif($pktype == "int")
        ${pk.SetterName}(((NumberKey)keys[$i]).intValue());
      #elseif($pktype == "long")
        ${pk.SetterName}(((NumberKey)keys[$i]).longValue());
      #elseif($pktype == "BigDecimal")
        ${pk.SetterName}(((NumberKey)keys[$i]).getBigDecimal());
      #elseif($pktype == "byte")
        ${pk.SetterName}(((NumberKey)keys[$i]).byteValue());
      #elseif($pktype == "float")
        ${pk.SetterName}(((NumberKey)keys[$i]).floatValue());
      #elseif($pktype == "double")
        ${pk.SetterName}(((NumberKey)keys[$i]).doubleValue());
      #elseif($pktype == "Short")
        ${pk.SetterName}(new Short(((NumberKey)keys[$i]).shortValue()));
      #elseif($pktype == "Integer")
        ${pk.SetterName}(new Integer(((NumberKey)keys[$i]).intValue()));
      #elseif($pktype == "Long")
        ${pk.SetterName}(new Long(((NumberKey)keys[$i]).longValue()));
      #elseif($pktype == "Byte")
        ${pk.SetterName}(new Byte(((NumberKey)keys[$i]).byteValue()));
      #elseif($pktype == "Float")
        ${pk.SetterName}(new Float(((NumberKey)keys[$i]).floatValue()));
      #elseif($pktype == "Double")
        ${pk.SetterName}(new Double(((NumberKey)keys[$i]).doubleValue()));
      #elseif($pktype == "String")
        ${pk.SetterName}(keys[$i].toString());
      #elseif($pktype == "Date")
        ${pk.SetterName}(((DateKey)keys[$i]).getDate());
      #end
      #set ( $i = $i + 1 )
    #end
    }

    /**
     * Set the PrimaryKey using SimpleKeys.
     *
    #foreach ($col in $table.PrimaryKey)
      #set ( $clo=$col.UncapitalisedJavaName )
      #set ( $cjtype= $col.JavaNative )
     * @param $clo $cjtype
    #end
     */
    public void setPrimaryKey($argList)
        $throwsClause
    {
    #foreach ($col in $table.PrimaryKey)
        ${col.SetterName}($col.UncapitalisedJavaName);
    #end
    }

    /**
     * Set the PrimaryKey using a String.
     */
    public void setPrimaryKey(String key) throws TorqueException
    {
        setPrimaryKey(new ComboKey(key));
    }
  #end

    /**
     * returns an id that differentiates this object from others
     * of its class.
     */
    public ObjectKey getPrimaryKey()
    {
  #if ($table.PrimaryKey.size() == 1)
        return SimpleKey.keyFor(${table.PrimaryKey.get(0).GetterName}());
  #elseif ($table.PrimaryKey.size() > 1)
    #set ($i = 0)
    #foreach ($pk in $table.PrimaryKey)
        pks[$i] = SimpleKey.keyFor(${pk.GetterName}());
      #set ($i = $i +1)
    #end
        return comboPK;
  #else
        return null;
  #end
    }
#end ##ends if(!$table.isAlias())

#if ($addIntakeRetrievable)
    /**
     * get an id that differentiates this object from others
     * of its class.
     */
    public String getQueryKey()
    {
        if (getPrimaryKey() == null)
        {
            return "";
        }
        else
        {
            return getPrimaryKey().toString();
        }
    }

    /**
     * set an id that differentiates this object from others
     * of its class.
     */
    public void setQueryKey(String key)
        throws TorqueException
    {
  ## Work around the fact that BaseObject.setPrimaryKey() declares
  ## that it throws Exception instead of TorqueException.
  #if (!$tableHasPrimaryKey)
        try
        {
  #end
        setPrimaryKey(key);
  #if (!$tableHasPrimaryKey)
        }
        catch (Exception e)
        {
            throw new TorqueException("Unable to set query key", e);
        }
  #end
    }
#end

#if (!$table.isAlias())
    /**
     * Makes a copy of this object.
     * It creates a new object filling in the simple attributes.
  #if ($complexObjectModel)
     * It then fills all the association collections and sets the
     * related objects to isNew=true.
  #end
     */
  #if ($table.isAbstract())
    public abstract $table.JavaName copy() throws TorqueException;
  #else
    public $table.JavaName copy() throws TorqueException
    {
        return copyInto(new ${table.JavaName}());
    }
  #end

    protected $table.JavaName copyInto($table.JavaName copyObj) throws TorqueException
    {
  #foreach ($col in $table.Columns)
        copyObj.${col.SetterName}($col.UncapitalisedJavaName);
  #end

  #foreach ($col in $table.Columns)
    #if ($col.isPrimaryKey())
      #if($col.Primitive)
		#set ($fktype = $col.JavaNative)
	    #set ($casttype = "")
        #if ($fktype == "short")
          #set ($casttype = "(short)")
        #elseif($fktype == "byte")
          #set ($casttype = "(byte)")
        #end
        #set ($coldefval = "0")
        #set ($coldefval = $col.DefaultValue)
        copyObj.${col.SetterName}($casttype $coldefval);
      #else
        #set ( $pkid = "null" )
        #set ( $cjtype = $col.JavaNative )
        copyObj.${col.SetterName}((${cjtype})${pkid});
      #end
    #end
  #end

  #if ($complexObjectModel)
    #set ( $list = "List " )
    #foreach ($fk in $table.Referrers)
      #set ( $tblFK = $fk.Table )
      #if ( !($tblFK.Name.equals($table.Name)) )
        #set ( $className = $tblFK.JavaName )
        #set ( $relCol = "" )
        #foreach ($columnName in $fk.LocalColumns)
          #set ( $column = $tblFK.getColumn($columnName) )
          #if ($column.isMultipleFK())
            #set ( $relCol = "$relCol$column.JavaName" )
          #end
        #end

        #if ($objectIsCaching)
          #if ($relCol == "")
            #set ( $pCollName = "${className}s" )
            #set ( $pCollNameNoS = "${className}" )
          #else
            #set ( $pCollName = "${className}sRelatedBy$relCol" )
            #set ( $pCollNameNoS = "${className}RelatedBy$relCol" )
          #end

        ${list}v = get${pCollName}();
          ## v can be null if the generator property
          ## torque.silentDbFetch is set to false
        if (v != null)
        {
            for (int i = 0; i < v.size(); i++)
            {
                $className obj = ($className) v.get(i);
                copyObj.add$pCollNameNoS(obj.copy());
            }
        }
        else
        {
            copyObj.coll${pCollName} = null;
        }
        #end
        #set ( $list = "" )
      #end
    #end
  #end
        return copyObj;
    }
#end

#if (!$table.isAlias())
    /**
     * returns a peer instance associated with this om.  Since Peer classes
     * are not to have any instance attributes, this method returns the
     * same instance for all member of this class. The method could therefore
     * be static, but this would prevent one from overriding the behavior.
     */
    public ${table.JavaName}Peer getPeer()
    {
        return peer;
    }
#end

#if ($generateBeans)
  $generator.parse("om/bean/ObjectBeanMethods.vm",$path,"child",$child)
#end

    public String toString()
    {
        StringBuffer str = new StringBuffer();
        str.append("$table.JavaName:\n");
#foreach ($col in $table.Columns)
        str.append("$col.JavaName = ")
  #set ( $cjtype = $col.JavaNative )
  #if ( $cjtype == "byte[]" )
           .append("<binary>")
  #else
           .append(${col.GetterName}())
  #end
           .append("\n");
#end
        return(str.toString());
    }
}
