All Downloads are FREE. Search and download functionalities are using the official Maven repository.

p.sql2java-maven-plugin.0.9.0.source-code.manager.vm Maven / Gradle / Ivy

##$Id: manager.java.vm,v 1.12 2005/10/17 09:09:59 framiere Exp $
#parse( "header.include.vm" )
#parse( "table.variables.include.vm" )
$codewriter.setCurrentJavaFilename("$table.getPackage()", "${managerClass}.java")
package $table.getPackage();

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.List;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

#foreach ($linkedPackage in $linkedPackages)
import ${linkedPackage}.*;
#end
#if ($useLib)
import $libPath.*;
#end

/**
 * Handles database calls (save, load, count, etc...) for the $tablename table.
#if ( $codewriter.hasRemarks() )
 * Remarks: $codewriter.getRemarks()
#end
 */
public class $managerClass extends BaseManager<$beanClass>
{
    private static final Logger log = LoggerFactory.getLogger(${managerClass}.class.getName());

#foreach ( $column in $columns ) #set ( $vcmo = $velocityCount - 1 )
    /**
     * Identify the $column.getName() field.
     */
    public static final int ID_$column.getConstName() = $vcmo;

#end
    /**
     * Contains all the full fields of the $tablename table.
     */
    private static final String[] FULL_FIELD_NAMES =
    {
#foreach ( $column in $columns )
        #if ( $velocityCount > 1 ),#end"$column.getFullName()"
#end
    };

    /**
     * Contains all the fields of the $tablename table.
     */
    private static final String[] FIELD_NAMES =
    {
#foreach ( $column in $columns )
        #if ( $velocityCount > 1 ),#end"$column.getName()"
#end
    };

    /**
     * Field that contains the comma separated fields of the $tablename table.
     */
    public static final String ALL_FULL_FIELDS = #foreach( $column in $columns )
#if ( $velocityCount > 1 )

                            + ",#else"#end$column.getFullName()"#end;

    /**
     * Field that contains the comma separated fields of the $tablename table.
     */
    public static final String ALL_FIELDS = #foreach( $column in $columns )
#if ( $velocityCount > 1 )

                            + ",#else"#end$column.getName()"#end;

    /**
     * Contains all the full fields of the table.
     */
    protected String[] getFullFieldNames() { return FULL_FIELD_NAMES; }

    /**
     * Contains all the fields of the table.
     */
    protected String[] getFieldNames() { return FIELD_NAMES; }

    /**
     * Field that contains the comma separated fields of the table.
     */
    protected String getAllFullFields() { return ALL_FULL_FIELDS; }

    /**
     * Field that contains the comma separated fields of the table.
     */
    protected String getAllFields() { return ALL_FIELDS; }

    /**
     * Constructor
     */
    public $managerClass(DataSource dataSource)
    {
        super(dataSource);
    }

    /**
     * Creates a new $beanClass instance.
     *
     * @return the new $beanClass
     */
    public $beanClass create$beanClass()
    {
        return new $beanClass();
    }

    /**
     * Creates a new $beanClass instance.
     *
     * @return the new $beanClass
     */
    public $beanClass createBean()
    {
        return create$beanClass();
    }

    /**
     * Table managed by this manager
     *
     * @return tablename
     */
    public String getTableName()
    {
        return "$tablename";
    }

#if ( $primaryKeys.size() > 0 )
    //////////////////////////////////////
    // PRIMARY KEY METHODS
    //////////////////////////////////////

#set ( $keys = "" )
#foreach ( $pk in $primaryKeys )
#if ( $velocityCount > 1 )#set( $keys = "$keys, " )#end
#set ( $keys = "$keys${pk.getJavaType()} $strUtil.getVarName($pk)" )
#end
##set ( $noWhereSelect = "SELECT \" + ALL_FIELDS + \" FROM \" + $tablename" )
##set ( $baseSelect = "$noWhereSelect WHERE " )
#set ( $sql = "" )
#foreach( $pk in $primaryKeys )
#if ( $velocityCount > 1 )#set ( $sql = "$sql and " )#end
#set ( $sql = "$sql$pk.getName()=?" )
#end
    /**
     * Loads a $beanClass from the $tablename using its key fields.
     *
     * @return a unique $beanClass
     */
    //1
    public $beanClass loadByPrimaryKey($keys) throws SQLException {
        Connection c = null;
        PreparedStatement ps = null;
        try {
            c = getConnection();
            StringBuilder sql = new StringBuilder("SELECT ").append(ALL_FIELDS).append(" FROM $tablename WHERE $sql");
            if (log.isTraceEnabled()) log.trace("loadByPrimaryKey: {}", sql);
            ps = c.prepareStatement(sql.toString(),
                                    ResultSet.TYPE_SCROLL_INSENSITIVE,
                                    ResultSet.CONCUR_READ_ONLY);
#foreach( $pk in $primaryKeys )
            $pk.getPreparedStatementMethod($strUtil.getVarName($pk), $velocityCount)
#end
            List<$beanClass> pReturn = loadByPreparedStatement(ps);
            if (pReturn.size() < 1) return null;
            else return pReturn.get(0);
        } finally {
            close(ps);
            releaseConnection(c);
        }
    }

#set ( $sql = "" )
#foreach( $pk in $primaryKeys )
#if ( $velocityCount > 1 )#set ( $sql = "$sql and " )#end
#set ( $sql = "$!sql$pk.getName()=?" )
#end
    /**
     * Deletes rows according to its keys.
     *
     * @return the number of deleted rows
     */
    //2
    public int deleteByPrimaryKey($keys) throws SQLException {
        Connection c = null;
        PreparedStatement ps = null;
        try {
            c = getConnection();
            StringBuilder sql = new StringBuilder("DELETE FROM $tablename WHERE $sql");
            if (log.isTraceEnabled()) log.trace("loadByPrimaryKey: {}", sql);
            ps = c.prepareStatement(sql.toString(),
                                    ResultSet.TYPE_SCROLL_INSENSITIVE,
                                    ResultSet.CONCUR_READ_ONLY);
#foreach( $pk in $primaryKeys )
            $pk.getPreparedStatementMethod($strUtil.getVarName($pk), $velocityCount)
#end
            return ps.executeUpdate();
        } finally {
            close(ps);
            releaseConnection(c);
        }
    }
#end
## ======================================================
## xForeignKeys template
## ======================================================
#set ( $keysDone = [] )
#set ( $keysImported = [] )
#foreach ($impKey in $foreignKeys)
#if ( $velocityCount == 1 )

    //////////////////////////////////////
    // GET/SET FOREIGN KEY BEAN METHOD
    //////////////////////////////////////
#end
#set ( $importedtable = $impKey.getForeignColumn().getTableName() )
#set ( $importedClass = "${strUtil.getBeanClass($importedtable)}" )
#set ( $importedClassManager = "${strUtil.getManagerClass($importedtable)}" )
#if ( !$keysImported.contains( $importedClass ) )
#if ( $keysImported.add($importedClass) )#*squelch*##end
    /**
     * Retrieves the $importedClass object from the $tablename.$impKey.getName() field.
     *
     * @param bean the $beanClass
     * @return the associated $importedClass bean
     */
    //3 GET IMPORTED
    public $importedClass[] get${importedClass}s($beanClass bean) throws SQLException {
        $importedClass other = ${importedClassManager}.getInstance().create${importedClass}();
        other.${strUtil.getSetMethod($impKey.getForeignColumn())}(bean.${strUtil.getGetMethod($impKey)}());
        return ${importedClassManager}.getInstance().loadUsingTemplate(other);
    }

    /**
     * Associates the $beanClass object to the $importedClass object.
     *
     * @param bean the $beanClass object to use
     * @param beanToSet the $importedClass object to associate to the $beanClass
     * @return the associated $importedClass bean
     */
    //4 SET IMPORTED
    public $beanClass set${importedClass}($beanClass bean,$importedClass beanToSet)
    {
        bean.${strUtil.getSetMethod($impKey)}(beanToSet.${strUtil.getGetMethod($impKey.getForeignColumn())}());
        return bean;
    }

#end
#end

    //_____________________________________________________________________
    //
    // SAVE
    //_____________________________________________________________________
    /**
     * Insert the $beanClass bean into the database.
     *
     * @param bean the $beanClass bean to be saved
     * @param orUpdate on duplicate key update
     * @param delayed use INSERT DELAYED and don't get generated keys
     */
    //13
    public $beanClass insert($beanClass bean, boolean orUpdate, boolean delayed) throws SQLException {
        // mini checks
        if (!bean.isModified()) {
            return bean; // should not we log something ?
        }
        if (!bean.isNew()){
            return update(bean);
        }
        Connection c = null;
        PreparedStatement ps = null;
        StringBuilder sql = null;
        try {
            c = getConnection();
##-------------writePreInsert
#set( $genKeyRetrieve = $codewriter.getProperty("generatedkey.retrieve", "") )
#set ( $hint = $codewriter.getProperty("generatedkey.statement").replaceAll("", $tablename) )
#if ( $primaryKeys.size() > 0 )#set ( $pKey = $primaryKeys.get(0) )#end
#if ( $genKeyRetrieve == "before" && $primaryKeys.size() == 1 && $pKey.isColumnNumeric() )
            if (!bean.$strUtil.getModifiedMethod($pKey)()) {
                StringBuilder hint = new StringBuilder("$hint");
                if (log.isTraceEnabled()) log.trace("generatedKey : {}", hint);
                ps = c.prepareStatement(hint.toString());
                ResultSet rs = null;
                try {
                    rs = ps.executeQuery();
                    if(rs.next()) {
                        bean.$strUtil.getSetMethod($pKey)($pKey.getResultSetMethodObject("1"));
                    } else {
                        if (delayed || orUpdate) log.trace("Could not retrieve generated key");
                        else log.warn("Could not retrieve generated key");
                    }
                } finally {
                    close(ps, rs);
                    ps=null;
                }
            }
#end
##------------/writePreInsert
            int _dirtyCount = 0;
#set ( $isPresentLock = $codewriter.isPresentLock( $columns ) )
#if ( $isPresentLock )
#set ($lockColumn = $codewriter.getLockColumn($columns))
        bean.$strUtil.getSetMethod($lockColumn)(new $lockColumn.getJavaType()(String.valueOf(System.curentTimeMillis())));

#end
            sql = new StringBuilder();
            if (delayed) sql.append("INSERT DELAYED into $tablename (");
            else sql.append("INSERT into $tablename (");

#foreach( $column in $columns )
            if (bean.$strUtil.getModifiedMethod($column)()) {
                if (_dirtyCount>0) {
                    sql.append(",");
                }
                sql.append("$column.getName()");
                _dirtyCount++;
            }

#end
            sql.append(") values (");
            if(_dirtyCount > 0) {
                sql.append("?");
                for(int i = 1; i < _dirtyCount; i++) {
                    sql.append(",?");
                }
            }
            sql.append(")");

#if ( $genKeyRetrieve == "auto" )
#set( $prestArgs = "Statement.RETURN_GENERATED_KEYS" )
#else
#set( $prestArgs = "ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY" )
#end

 	    if (orUpdate) {
 		sql.append(" ON duplicate KEY UPDATE ");
                boolean useComma=false;
#foreach( $column in $columns )

                if (bean.$strUtil.getModifiedMethod($column)()) {
                    if (useComma) {
                        sql.append(",");
                    } else {
                        useComma=true;
                    }
                    sql.append("$column.getName()").append("=VALUES(").append("$column.getName()").append(")");
                }
#end

	    }
            if (log.isTraceEnabled()) log.trace("insert : {}", sql);
            ps = c.prepareStatement(sql.toString(),
                                    $prestArgs);

            fillPreparedStatement(ps, bean, SEARCH_EXACT);

            ps.executeUpdate();
##------------------writePostInsert
#if ( $primaryKeys.size() == 1 )
#set($pKey = $primaryKeys.get(0))
#if ( $pKey.isColumnNumeric() )
#set ( $hint = $codewriter.getProperty("generatedkey.statement").replaceAll("
", $tablename) ) #if ( $genKeyRetrieve == "after" ) if (!bean.$strUtil.getModifiedMethod($pKey)()) { PreparedStatement ps2 = null; ResultSet rs = null; try { ps2 = c.prepareStatement("$hint"); rs = ps2.executeQuery(); if(rs.next()) { bean.$strUtil.getSetMethod($pKey)($pKey.getResultSetMethodObject("1")); } else { if (delayed || orUpdate) log.trace("Could not retrieve generated key"); else log.warn("Could not retrieve generated key"); } } finally { close(ps2, rs); } } #elseif ( $genKeyRetrieve == "auto" ) if (!bean.$strUtil.getModifiedMethod($pKey)() && !delayed) { ResultSet rs = ps.getGeneratedKeys(); try { if(rs.next()) { bean.$strUtil.getSetMethod($pKey)($pKey.getResultSetMethodObject("1")); } else { if (delayed || orUpdate) log.trace("Could not retrieve generated key"); else log.warn("Could not retrieve generated key"); } } finally { close(rs); } } #end #end #end ##-------------------/writePostInsert bean.isNew(false); bean.resetIsModified(); return bean; } finally { close(ps); releaseConnection(c); } } /** * Update the $beanClass bean record in the database according to the changes. * * @param bean the $beanClass bean to be updated */ //14 public $beanClass update($beanClass bean) throws SQLException { // mini checks if (!bean.isModified()) { return bean; // should not we log something ? } if (bean.isNew()){ return save(bean); } Connection c = null; PreparedStatement ps = null; StringBuilder sql = null; try { c = getConnection(); #if ( $primaryKeys.size() == 0 ) $codewriter.log(" WARN : $tablename does not have any primary key...") #end #if ( $isPresentLock ) $lockColumn.getJavaType() oldLockValue = bean.$strUtil.getGetMethod($lockColumn)(); bean.$strUtil.getSetMethod($lockColumn))(new $lockColumn.getJavaType()(String.valueOf(System.currentTimeMillis()))); #end sql = new StringBuilder("UPDATE $tablename SET "); boolean useComma=false; #foreach( $column in $columns ) if (bean.$strUtil.getModifiedMethod($column)()) { if (useComma) { sql.append(","); } else { useComma=true; } sql.append("$column.getName()").append("=?"); } #end #if ( $primaryKeys.size() > 0 ) sql.append(" WHERE "); #end #set ($sql = "" ) #macro ( sqlAppend $somestr ) #set ( $sql = "$!sql$somestr" ) #end #foreach( $primaryKey in $primaryKeys ) #if ( $velocityCount > 1 )#sqlAppend( " AND " )#end #sqlAppend( "$primaryKey.getName()=?" ) #end #if ( $isPresentLock ) #if ( $primaryKeys.size() > 0 )#sqlAppend( " AND " )#end #sqlAppend( "$lockColumn.getName()=?") #end sql.append("$sql"); if (log.isTraceEnabled()) log.trace("update : {}", sql); ps = c.prepareStatement(sql.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); int _dirtyCount = fillPreparedStatement(ps, bean, SEARCH_EXACT); if (_dirtyCount == 0) { if (log.isTraceEnabled()) log.trace("The bean to look is not initialized... do not update."); return bean; } #foreach ( $pKey in $primaryKeys ) $pKey.getPreparedStatementMethod("bean.$strUtil.getGetMethod($pKey)()", "++_dirtyCount") #end #if ( $isPresentLock ) $lockColumn.getPreparedStatementMethod( "oldLockValue", "++_dirtyCount") if (ps.executeUpdate()==0) { throw new SQLException("sql2java.exception.optimisticlock"); } #else ps.executeUpdate(); #end bean.resetIsModified(); return bean; } finally { close(ps); releaseConnection(c); } } //_____________________________________________________________________ // // USING TEMPLATE //_____________________________________________________________________ /** * Deletes rows using a $beanClass template. * * @param bean the $beanClass object(s) to be deleted * @return the number of deleted objects */ //21 public int deleteUsingTemplate($beanClass bean) throws SQLException { #if ( $primaryKeys.size() == 1) if (bean.$strUtil.getInitializedMethod($primaryKeys.get(0))()) return deleteByPrimaryKey(bean.$strUtil.getGetMethod($primaryKeys.get(0))()); #end Connection c = null; PreparedStatement ps = null; StringBuilder sql = new StringBuilder("DELETE FROM $tablename ");; StringBuilder sqlWhere = new StringBuilder(""); try { if (fillWhere(sqlWhere, bean, SEARCH_EXACT) == 0) { if (log.isTraceEnabled()) log.trace("The bean to look is not initialized... deleting all"); } else { sql.append(" WHERE ").append(sqlWhere); } if (log.isTraceEnabled()) log.trace("deleteUsingTemplate: {}", sql); c = getConnection(); ps = c.prepareStatement(sql.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); fillPreparedStatement(ps, bean, SEARCH_EXACT); int _rows = ps.executeUpdate(); return _rows; } finally { close(ps); releaseConnection(c); } } /** * fills the given stringbuilder with the sql where clausis constructed using the bean and the search type * @param sqlWhere the stringbuilder that will be filled * @param bean the bean to use for creating the where clausis * @param searchType exact ? like ? starting like ? * @return the number of clausis returned */ protected int fillWhere(StringBuilder sqlWhere, $beanClass bean, int searchType) throws SQLException { if (bean == null) return 0; int _dirtyCount = 0; StringBuilder sqlEqualsOperation = new StringBuilder("="); StringBuilder sqlOperation = new StringBuilder("="); if (searchType != SEARCH_EXACT) sqlOperation = new StringBuilder(" like "); #foreach( $column in $columns ) if (bean.$strUtil.getModifiedMethod($column)()) { _dirtyCount ++; #if ($column.isString()) sqlWhere.append((sqlWhere.length() == 0) ? " " : " AND ").append("$column.getName() ").append(sqlOperation).append("?"); #else sqlWhere.append((sqlWhere.length() == 0) ? " " : " AND ").append("$column.getName() ").append(sqlEqualsOperation).append("?"); #end } #end return _dirtyCount; } /** * fill the given prepared statement with the bean values and a search type * @param ps the preparedStatement that will be filled * @param bean the bean to use for creating the where clausis * @param searchType exact ? like ? starting like ? * @return the number of clausis returned */ protected int fillPreparedStatement(PreparedStatement ps, $beanClass bean, int searchType) throws SQLException { if (bean == null) return 0; int _dirtyCount = 0; #foreach ( $column in $columns ) if (bean.$strUtil.getModifiedMethod($column)()) { #if ($column.isString()) switch (searchType){ case SEARCH_EXACT: if (log.isTraceEnabled()) log.trace("Setting for {} [{}]", _dirtyCount, bean.$strUtil.getGetMethod($column)()); $column.getPreparedStatementMethod("bean.$strUtil.getGetMethod($column)()", "++_dirtyCount"); break; case SEARCH_LIKE: if (log.isTraceEnabled()) log.trace("Setting for {} [%{}%]", _dirtyCount, bean.$strUtil.getGetMethod($column)()); $column.getPreparedStatementMethod("${Q}%${Q} + bean.$strUtil.getGetMethod($column)() + ${Q}%${Q}", "++_dirtyCount"); break; case SEARCH_STARTING_LIKE: if (log.isTraceEnabled()) log.trace("Setting for {} [{}%]", _dirtyCount, bean.$strUtil.getGetMethod($column)()); $column.getPreparedStatementMethod("${Q}%${Q} + bean.$strUtil.getGetMethod($column)()", "++_dirtyCount"); break; case SEARCH_ENDING_LIKE: if (log.isTraceEnabled()) log.trace("Setting for {} [%{}]", _dirtyCount, bean.$strUtil.getGetMethod($column)()); $column.getPreparedStatementMethod("bean.$strUtil.getGetMethod($column)() + ${Q}%${Q}", "++_dirtyCount"); break; } #else if (log.isTraceEnabled()) log.trace("Setting for {} [{}]", _dirtyCount, bean.$strUtil.getGetMethod($column)()); $column.getPreparedStatementMethod("bean.$strUtil.getGetMethod($column)()", "++_dirtyCount"); #end } #end return _dirtyCount; } /** * Transforms a ResultSet iterating on the $tablename on a $beanClass bean. * * @param rs the ResultSet to be transformed * @return bean resulting $beanClass bean */ public $beanClass decodeRow(ResultSet rs) throws SQLException { $beanClass bean = create$beanClass(); ## the set statement casts $velocityCount to a string #foreach ( $column in $columns ) #set ($vCount = "$velocityCount" ) bean.$strUtil.getSetMethod($column)($column.getResultSetMethodObject($vCount)); #end bean.isNew(false); bean.resetIsModified(); return bean; } /** * Transforms a ResultSet iterating on the $tablename on a $beanClass bean using the names of the columns * * @param rs the ResultSet to be transformed * @return bean resulting $beanClass bean */ public $beanClass metaDataDecodeRow(ResultSet rs) throws SQLException { $beanClass bean = create$beanClass(); #foreach ( $column in $columns ) bean.$strUtil.getSetMethod($column)($column.getResultSetMethodObject("${Q}$column.getName()${Q}")); #end bean.isNew(false); bean.resetIsModified(); return bean; } }