Package simpledao

Source Code of simpledao.SimpleDAO

package simpledao;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.sql.*;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayOutputStream;
import java.io.BufferedInputStream;

import simpledao.BoundVariable;
import simpledao.SimpleDAOUtils;
import simpledao.SimpleDBConnection;
import simpledao.SimpleDAOException;
import simpledao.SimpleBean;

/**
* <p>SimpleDAO is exactly as the name implies, a simple set of objects for
* accessing data in a database.  All of the public methods take beans
* inherited from the @see gov.utah.dws.coreweb.dao.simple.SimpleBean base
* class and a Connection object as parameters.  These methods perform
* simple SELECT, INSERT and UPDATES based on data defined in the
* passed in beans.  Users may also pass in a @see java.util.HashMap
* of columns they wish to use instead of all the columns defined
* by the bean</p>
* <p>Uses Jakarta Commons Logger</p>
* <p>
* User: jumiller
* Date: Mar 23, 2006
* Time: 3:55:50 PM
* </p>
* @version 1.1
* @author Justin J Miller
* @see SimpleBean
*/
public class SimpleDAO
{
   
    //todo insert byte array blob
    //todo handle clob in insert

    private static final Log log = LogFactory.getLog( SimpleDAO.class );
    private static final Log sqlLog = LogFactory.getLog( "SQL" );

    public SimpleDAO () {}

    /**
     * Populate the bean passed into the function with the
     * data appropriate to that bean.  An attempt to connect to the
     * database is made by searching the classpath for a DB.Properties file.
     * @param bean the <code>SimpleBean</code> derived class used to map
     * properties to table/column names
     * @return the fully populated bean
     * @throws Exception Any exception generated by the database call
     */
    public SimpleBean simpleSelect( SimpleBean bean ) throws Exception
    {
        Map<String,String> properties = bean.describe();
        SimpleDBConnection dbc = new SimpleDBConnection();
        Connection con = null;
        try
        {
            con = dbc.getDBConnection();
            return simpleSelect( con, bean, properties);
        }
        finally
        {
            dbc.closeDBConnection( con );
        }
    }

    public SimpleBean simpleSelect( SimpleBean bean, Map<String,String> properties) throws Exception
    {
        SimpleDBConnection dbc = new SimpleDBConnection();
        Connection con = null;
        try
        {
            con = dbc.getDBConnection();
            return simpleSelect( con, bean, properties );
        }
        finally
        {
            dbc.closeDBConnection( con );
        }
    }
    /**
     * Get the data from the database based on the bean you pass
     * in and return the fully populated bean.  This method
     * will introspect the associated bean for the public properties
     * to use as the columns in the SELECT statement.
     *
     * @param con   the database connection in use
     * @param bean  the <code>BaseBO</code> derived class you want selected against and populated
     * @return the fully-populated bean based on all the getters
     * @throws Exception catch-all
     * @see SimpleBean
     */
    public SimpleBean simpleSelect( Connection con, SimpleBean bean) throws Exception
    {
        if ( log.isDebugEnabled() ) { log.debug("Get the beans properties");}

        Map<String,String> properties = bean.describe();
        return simpleSelect( con, bean, properties );
    }

    /**
     * Same as simpleSelect except this accepts a Map of properties you want
     * selected instead of introspecting it from the bean.
     *
     * @param con  the database connection in use
     * @param bean  the bean to select against
     * @param properties  a Map of columns you want selected
     * @return  a populated bean of type SimpleBean
     * @throws Exception catch-all
     * @see SimpleBean
     */
    public SimpleBean simpleSelect( Connection con, SimpleBean bean, Map<String,String> properties ) throws Exception
  {
    if ( log.isDebugEnabled() ) { log.debug("call simpleSelectList and get the first bean");}

    ArrayList<? extends SimpleBean> beanList = simpleSelectList(con, bean, properties);
    if ( beanList.size() > 0 )
    {
      return beanList.get(0);
    }
    else
    {
      return null;
    }

  }
/* ********** CHANGED TO CALL simpleSelectList and get first record
    public SimpleBean simpleSelect( Connection con, SimpleBean bean, Map<String,String> properties ) throws Exception
    {
        ArrayList<BoundVariable> bindVariables = new ArrayList<BoundVariable>();
        Map<String,String> columns = SimpleDAOUtils.getColumnMapFromProps( properties );

        // get SQL statement
        String sql = buildSelectSQL( bean, columns, bindVariables);
        if ( sqlLog.isDebugEnabled() ) { sqlLog.debug("simpleSelect SQL:" + sql); }

        // create the return bean
        SimpleBean newBean = bean.getClass().newInstance();
        //SimpleBean newBean = (SimpleBean) (Class.forName( bean.getClass().getName()).newInstance() );

        try
        {

            PreparedStatement ps = con.prepareStatement( sql );

            SimpleDAOUtils.bindVariables( ps, bindVariables);

            ResultSet rs = ps.executeQuery();

            HashMap<String,Object> props = new HashMap<String,Object>();

            ResultSetMetaData metaData = rs.getMetaData();

            int columnCount = metaData.getColumnCount();

            if ( log.isDebugEnabled() ) { log.debug("simpleSelect - column count: " + columnCount );}

            if (rs.next())
            {

                if ( log.isDebugEnabled() ) { log.debug("simpleSelect - resultset has rows, process them");}

                for ( int i = 1; i <= columnCount ; i++)
                {
                    if ( metaData.getColumnType(i) == Types.BLOB )
                    {
                        if ( log.isDebugEnabled() ) { log.debug("simpleSelect - column # '" + i + " is a BLOB");}

                        Blob blob = rs.getBlob( metaData.getColumnName(i) );

                        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
                        BufferedInputStream bis = new BufferedInputStream( blob.getBinaryStream() );

                        byte[] buffer = new byte[1024];
                        int curByte;
                        while ( ( curByte = bis.read( buffer, 0, buffer.length ) ) != -1 )
                        {
                            baos.write( buffer, 0, curByte );
                        }
                        //props.put( SimpleDAOUtils.getCamelCaseColumnName( metaData.getColumnName(i) ), baos.toByteArray() );
                        if ( log.isDebugEnabled() ) { log.debug("simpleSelect - write BLOB to bean'" );}

                        props.put( columns.get( metaData.getColumnName(i)), rs.getString(i) );
                    }
                    else if ( metaData.getColumnType(i) == Types.DATE )
                    {
                        if ( log.isDebugEnabled() ) { log.debug("simpleSelect - column # '" + i + " is a DATE");}
                        props.put( columns.get( metaData.getColumnName(i)), rs.getDate(i) );
                    }
                    else if ( metaData.getColumnType(i) == Types.TIME )
                    {
                        if ( log.isDebugEnabled() ) { log.debug("simpleSelect - column # '" + i + " is a TIME");}
                        props.put( columns.get( metaData.getColumnName(i)), rs.getTime(i) );
                    }
                    else if ( metaData.getColumnType(i) == Types.TIMESTAMP )
                    {
                        if ( log.isDebugEnabled() ) { log.debug("simpleSelect - column # '" + i + " is a TIMESTAMP");}
                        props.put( columns.get( metaData.getColumnName(i)), rs.getTimestamp(i) );
                    }
                    else
                    {
                        if ( log.isDebugEnabled() ) { log.debug("simpleSelect - column # '" + i + " is not special");}
                        //props.put( SimpleDAOUtils.getCamelCaseColumnName( metaData.getColumnName(i) ), rs.getString(i) );
                        props.put( columns.get( metaData.getColumnName(i)), rs.getString(i) );
                    }
                }

                ps.close();
                if ( log.isDebugEnabled() ) { log.debug("populate the SimpleBean object");}
                newBean.populate( props );
            }
            else
            {
                log.error("no data found to select");
                throw new SimpleDAOException("No data found to select");
            }
        }
        catch ( SQLException e )
        {
            log.error(e);
            throw new Exception("A database error occurred while selecting the data: " + e.getMessage() ,e);
        }
        return newBean;
    }
*/


    /**
     * return a list of business objects based on the where clause
     * as built by the populated properties in the bean
     * @param con  Database Connection
     * @param bean bean holding the data and the return type
     * @return return ArrayList with the populated beans
     * @throws Exception catch-all
     * @see SimpleBean
     */
    public ArrayList<? extends SimpleBean> simpleSelectList( Connection con, SimpleBean bean ) throws Exception
    {
        Map<String,String> columns = bean.describe();
        return simpleSelectList( con, bean, columns );
    }

    public ArrayList<? extends SimpleBean> simpleSelectList( SimpleBean bean ) throws Exception
    {
        Map<String,String> columns = bean.describe();
        SimpleDBConnection dbc = new SimpleDBConnection();
        Connection con = null;
        try
        {
            con = dbc.getDBConnection();
            return simpleSelectList( con, bean, columns);
        }
        finally
        {
            dbc.closeDBConnection(con);
        }
    }

    /**
     * Same as above except with a Map of columns to use
     * @param con Database Connection object
     * @param bean the SimpleBean you want populated
     * @param properties properties on the bean
     * @return An ArrayList populated with objects of the type passed in as the bean parameter
     * @throws Exception catch-all
     * @see SimpleBean
     */
    public ArrayList< ? extends SimpleBean> simpleSelectList( Connection con, SimpleBean bean, Map<String,String> properties ) throws Exception
    {
        ArrayList<SimpleBean> beanList = new ArrayList<SimpleBean>();
        ArrayList<BoundVariable> bindVariables = new ArrayList<BoundVariable>();
        Map<String,String> columns = SimpleDAOUtils.getColumnMapFromProps( properties );

        // get SQL statement
        String sql = buildSelectSQL( bean, columns, bindVariables );
        if ( sqlLog.isDebugEnabled() ) { sqlLog.debug("simpleSelectList SQL:" + sql); }

        try
        {
            PreparedStatement ps = con.prepareStatement( sql );

            SimpleDAOUtils.bindVariables( ps, bindVariables);

            ResultSet rs = ps.executeQuery();

      // CHANGED TO ALLOW ALL TYPES
//            HashMap<String,String> props = new HashMap<String,String>();
      HashMap<String,Object> props = new HashMap<String,Object>();

            ResultSetMetaData metaData = rs.getMetaData();

            int columnCount = metaData.getColumnCount();

            while ( rs.next() )
            {
                for ( int i = 1; i <= columnCount ; i++)
                {
          // CHANGD TO ALLOW ALL TYPES
//                    props.put( columns.get( metaData.getColumnName(i)), rs.getString(i) );
          if ( metaData.getColumnType(i) == Types.BLOB )
          {
            if ( log.isDebugEnabled() ) { log.debug("simpleSelectList - column # '" + i + " is a BLOB");}

            Blob blob = rs.getBlob( metaData.getColumnName(i) );

            ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
            BufferedInputStream bis = new BufferedInputStream( blob.getBinaryStream() );

            byte[] buffer = new byte[1024];
            int curByte;
            while ( ( curByte = bis.read( buffer, 0, buffer.length ) ) != -1 )
            {
              baos.write( buffer, 0, curByte );
            }
            //props.put( SimpleDAOUtils.getCamelCaseColumnName( metaData.getColumnName(i) ), baos.toByteArray() );
            if ( log.isDebugEnabled() ) { log.debug("simpleSelectList - write BLOB to bean'" );}

            props.put( columns.get( metaData.getColumnName(i)), rs.getString(i) );
          }
          else if ( metaData.getColumnType(i) == Types.DATE )
          {
            if ( log.isDebugEnabled() ) { log.debug("simpleSelectList - column # '" + i + "' is a DATE");}
            props.put( columns.get( metaData.getColumnName(i)), rs.getTimestamp(i) );
          }
          else if ( metaData.getColumnType(i) == Types.TIME )
          {
            if ( log.isDebugEnabled() ) { log.debug("simpleSelectList - column # '" + i + "' is a TIME");}
            props.put( columns.get( metaData.getColumnName(i)), rs.getTime(i) );
          }
          else if ( metaData.getColumnType(i) == Types.TIMESTAMP )
          {
            if ( log.isDebugEnabled() ) { log.debug("simpleSelectList - column # '" + i + "' is a TIMESTAMP");}
            props.put( columns.get( metaData.getColumnName(i)), rs.getTimestamp(i) );
          }
          else
          {
            if ( log.isDebugEnabled() ) { log.debug("simpleSelectList - column # '" + i + "' is not special");}
            //props.put( SimpleDAOUtils.getCamelCaseColumnName( metaData.getColumnName(i) ), rs.getString(i) );
            props.put( columns.get( metaData.getColumnName(i)), rs.getString(i) );
          }
         
        }

                // create the return bean
                SimpleBean newBean = bean.getClass().newInstance();
                newBean.populate( props );

                beanList.add( newBean );
            }
            ps.close();
        }
        catch ( SQLException e )
        {
            log.error(e);
            throw new Exception("A database error occurred while selecting the data: " + e.getMessage() ,e);
        }
        return beanList;
    }

    public ArrayList<? extends SimpleBean> simpleSelectList( SimpleBean bean, Map<String,String> properties ) throws Exception
    {
        SimpleDBConnection dbc = new SimpleDBConnection();
        Connection con = null;
        try
        {
            con = dbc.getDBConnection();
            return simpleSelectList( con, bean, properties );
        }
        finally
        {
            dbc.closeDBConnection(con);
        }
    }

    /**
     * Insert data into the database based on columns introspected from the bean
     * @param con Connection object used to communicate with the database (JDBC)
     * @param bean SimpleBean derived class that has the approprate getters/setters
     * @throws Exception catch-all
     * @see SimpleBean
     */
    public void simpleInsert( Connection con, SimpleBean bean ) throws Exception
    {
        Map<String,String> properties = bean.describe();
        simpleInsert( con, bean, properties );
    }

    public void simpleInsert( SimpleBean bean ) throws Exception
    {
        Map<String,String> properties = bean.describe();
        SimpleDBConnection dbc = new SimpleDBConnection();
        Connection con = null;
        try
        {
            con = dbc.getDBConnection();
            simpleInsert( con, bean, properties );
        }
        finally
        {
            dbc.closeDBConnection(con);
        }
    }

    public void simpleInsert( SimpleBean bean, Map<String,String> properties ) throws Exception
    {
        SimpleDBConnection dbc = new SimpleDBConnection();
        Connection con = null;
        try
        {
            con = dbc.getDBConnection();
            simpleInsert( con, bean, properties );
        }
        finally
        {
            dbc.closeDBConnection(con);
        }
    }

    /**
     * Creates and executes a SQL INSERT statement against the passed in Connection object.
     * The columns to be inserted along with their values are ascertained from the passed in
     * SimpleBean derived class and the associated Map of bean proeprties.
     * @param con Connection object used to communicate with the database (JDBC)
     * @param bean SimpleBean derived class that has the approprate getters/setters
     * @param properties A Map of columns that have values to insert
     * @throws Exception catch-all
     * @see SimpleBean
     */
    public void simpleInsert( Connection con, SimpleBean bean, Map<String,String> properties ) throws Exception
    {
        ArrayList<BoundVariable> bindVariables = new ArrayList<BoundVariable>();

        String sql = buildInsertSQL( bean, properties, bindVariables);
        if ( sqlLog.isDebugEnabled() ) { sqlLog.debug("simpleInsert SQL:" + sql); }
        try
        {
            PreparedStatement ps = con.prepareStatement( sql );
            SimpleDAOUtils.bindVariables( ps, bindVariables);
            ps.executeUpdate();
            ps.close();
        }
        catch ( SQLException e )
        {
            log.error(e);
            throw new Exception ("A database occurred while inserting: " + e.getMessage(), e);
        }
    }

    /**
     * Introspects the passed SimpleBean for columns that need to be updated.  The
     * resulting Map of columns is then passed to the simpleUpdate method that
     * accepts a Map parameter.
     *
     * @param con Connection object used to communicate with the database (JDBC) and run the UPDATE
     * @param bean  SimpleBean derived class with getters and setters that holds the values to update.
     * This method introspects the passed SimpleBean for columns to update
     * @throws Exception catch-all
     * @see SimpleBean
     */
    public void simpleUpdate( Connection con, SimpleBean bean ) throws Exception
    {
        Map<String,String> properties = bean.describe();
        simpleUpdate( con, bean , properties );
    }

    public void simpleUpdate( SimpleBean bean ) throws Exception
    {
        Map<String,String> properties = bean.describe();
        SimpleDBConnection dbc = new SimpleDBConnection();
        Connection con = null;
        try
        {
            con = dbc.getDBConnection();
            simpleUpdate( con, bean, properties );
        }
        finally
        {
            dbc.closeDBConnection(con);
        }
    }

    /**
     * Creates and runs a SQL UPDATE statement against the passed database connection object.
     * The columns to be updated along with their values are ascertained from the passed in
     * SimpleBean derived class and Map of columns.
     *
     * @param con Connection object used to communicate with the database (JDBC) and run the UPDATE
     * @param bean  SimpleBean derived class with getters and setters that holds the values to update
     * @param properties A Map of SimpleBean properties that will be used as columns to update
     * @throws Exception catch-all
     * @see SimpleBean
     */
    public void simpleUpdate( Connection con, SimpleBean bean, Map<String,String> properties ) throws Exception
    {
        ArrayList<BoundVariable> bindVariables = new ArrayList<BoundVariable>();

        String sql = buildUpdateSQL( bean, properties, bindVariables);

        try
        {
            if ( sqlLog.isDebugEnabled() ) { sqlLog.debug("simpleUpdate SQL:" + sql); }
            PreparedStatement ps = con.prepareStatement( sql );
            SimpleDAOUtils.bindVariables( ps, bindVariables);
            ps.executeUpdate();
            ps.close();
        }
        catch ( SQLException e )
        {
            log.error(e);
            throw new Exception("A database error occurred while saving: " + e.getMessage() ,e);
        }
    }

    public void simpleUpdate(SimpleBean bean, Map<String,String> properties ) throws Exception
    {
        SimpleDBConnection dbc = new SimpleDBConnection();
        Connection con = null;
        try
        {
            con = dbc.getDBConnection();
            simpleUpdate( con, bean, properties );
        }
        finally
        {
            dbc.closeDBConnection(con);
        }
    }

    /**
     *
     * @param con Connection object used to run the DELETE statement against
     * @param bean SimpleBean derived class used to determine the table name and WHERE clause
     * @throws Exception catch-all
     * @see SimpleBean
     */
    public void simpleDelete( Connection con, SimpleBean bean ) throws Exception
    {
        Map<String,String> properties = bean.describe();
        simpleDelete( con, bean , properties );
    }

    public void simpleDelete( SimpleBean bean ) throws Exception
    {
        SimpleDBConnection dbc = new SimpleDBConnection();
        Map<String,String> properties = bean.describe();
        Connection con = null;
        try
        {
            con = dbc.getDBConnection();
            simpleDelete( con, bean, properties );
        }
        finally
        {
            dbc.closeDBConnection(con);
        }
    }

    /**
     * Creates and executes a SQL DELETE statement against the Connection parameter.
     * The table name is determined from the SimpleBean derived class and the WHERE clause
     * is asertained from the Map of SimpleBean properties.
     *
     * @param con Connection object used to run the DELETE statement against
     * @param bean SimpleBean derived class used to determine the table name and WHERE clause
     * @param properties Map of SimpleBean properties used to determine WHERE clause
     * @throws Exception catch-all
     */
    public void simpleDelete( Connection con, SimpleBean bean, Map<String,String> properties ) throws Exception
    {
        ArrayList<BoundVariable> bindVariables = new ArrayList<BoundVariable>();

        String sql = buildDeleteSQL( bean, properties, bindVariables);

        try
        {
            if ( sqlLog.isDebugEnabled() ) { sqlLog.debug("simpleDelete SQL:" + sql); }
            PreparedStatement ps = con.prepareStatement( sql );
            SimpleDAOUtils.bindVariables( ps, bindVariables);
            ps.executeUpdate();
            ps.close();
        }
        catch ( SQLException e )
        {
            log.error(e);
            throw new Exception("A database error occurred while deleting." ,e);
        }
    }

    public void simpleDelete( SimpleBean bean, Map<String,String> properties ) throws Exception
    {
        SimpleDBConnection dbc = new SimpleDBConnection();
        Connection con = null;
        try
        {
            con = dbc.getDBConnection();
            simpleDelete( con, bean, properties );
        }
        finally
        {
            dbc.closeDBConnection(con);
        }
    }

    private String buildSelectSQL( SimpleBean bean, Map<String,String> columns, ArrayList<BoundVariable> bindVariables ) throws Exception
    {
        StringBuffer selectSQL = new StringBuffer( "SELECT ");
        StringBuffer whereSQL = new StringBuffer(" FROM " );
        StringBuffer orderSQL = new StringBuffer("");

        whereSQL.append( bean.getDBTableName() );

        Iterator iter = columns.keySet().iterator();

        int colCount = 0;
        int whereCount = 0;
        int orderCount = 0;
        while ( iter.hasNext() )
        {
            String column = (String) iter.next();
            String property = columns.get(column);
            Map <String,Boolean> orderBy = bean.getDBOrderByProps();
            if ( orderBy != null && orderBy.get(property) != null )
            {
                if ( orderCount > 0 )
                {
                    orderSQL.append(", ");
                }
                orderSQL.append(column);
                if ( !orderBy.get(property))
                {
                    orderSQL.append(" DESC");
                }
                orderCount++;
            }

            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor( bean, property );
            Object value = PropertyUtils.getProperty ( bean, property );
            Class type = pd.getPropertyType();

            if ( colCount > 0 )
            {
                selectSQL.append(", " );
            }
            selectSQL.append( column );
            colCount++;

            // check to see if the value of this column is null
            // if so, add it to the SELECT list
            // if not, add it to WHERE clause
/*
            if ( value == null ||
                 ( ( type == Integer.class || "int".equals( type.getName() ) ) &&  ( ((Integer)value).intValue()  < 0 ) ) )
*/
            if ( SimpleDAOUtils.isPropertyNull( type, value ) )
            {
                //continue;
            }
            else
            {
                if ( whereCount == 0 )
                {
                    whereSQL.append( " WHERE " );
                }
                else
                {
                    whereSQL.append(" AND " );
                }
                whereSQL.append( column );
                if ( value.toString().indexOf("%") > -1 )
        {
          whereSQL.append( " LIKE ? " );
        }
        else
        {
          whereSQL.append( " = ? " );
        }
                whereCount ++;
                bindVariables.add( new BoundVariable( whereCount, column, type, value));
            }
/*
                if ( colCount > 0 )
                {
                    selectSQL.append(", " );
                }
                selectSQL.append( SimpleDAOUtils.getPropertyDBName( column ) );
                colCount++;
            }
            else
            {
*/
        }
        selectSQL.append ( whereSQL );
        return selectSQL.toString();
    }

    private String buildInsertSQL(SimpleBean bean, Map<String,String> properties, ArrayList<BoundVariable> bindVariables ) throws Exception
    {
        StringBuffer sql = new StringBuffer("INSERT INTO " );
        StringBuffer valuesSQL = new StringBuffer(" ) VALUES ( ");
        int propCount = 0;

        sql.append( bean.getDBTableName() );
        sql.append( " ( " );

        for (String property : properties.keySet())
        {
            String column = properties.get(property);
            // if the database column is not already specified (unlikely), then determine it
            if (column == null || "".equals(column))
            {
                column = SimpleDAOUtils.getPropertyDBName(property);
            }
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, property);

            Object value = PropertyUtils.getProperty(bean, property);

            Class type = pd.getPropertyType();

            if (value == null ||
        (type == Integer.class || "int".equals(type.getName())) && ((Integer) value < 0) ||
        ( type == Double.class || "double".equals( type.getName() ) ) && ((Double) value < 0.0d))
            {
                continue;
            }

            if (propCount > 0)
            {
                sql.append(", ");
                valuesSQL.append(", ");
            }
            sql.append(column);
            valuesSQL.append("?");

            propCount++;
            bindVariables.add(new BoundVariable(propCount, column, type, value));
        }
        sql.append( valuesSQL );
        sql.append( " )");
        return sql.toString();
    }

    private String buildUpdateSQL( SimpleBean bean, Map<String,String> properties, ArrayList<BoundVariable> bindVariables ) throws Exception
    {
        StringBuffer sql = new StringBuffer( "UPDATE " );
        StringBuffer whereSQL = new StringBuffer(" WHERE ");
        ArrayList<BoundVariable> keyBindVariables = new ArrayList<BoundVariable>();

        int columnCount = 0;
        int keyCount = 0;


        sql.append( bean.getDBTableName()  );

        sql.append( " SET " );

        String[] keys = bean.getDBPrimaryKey();

        for (String property : properties.keySet())
        {

            String column = properties.get(property);
            if (column == null || "".equals(column))
            {
                column = SimpleDAOUtils.getPropertyDBName(property);
            }
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, property);

            Object value = PropertyUtils.getProperty(bean, property);

            if ( isColumnAKey( keys,column ))
            {
                //if ( ( (Integer) value).intValue()  < 1 )
                if (SimpleDAOUtils.isPropertyNull(pd.getPropertyType(), value))
                {
                    throw new SimpleDAOException("Key may not have a null/0 value;");
                }
                whereSQL.append(column);
                whereSQL.append(" = ?");

                keyCount++;
                keyBindVariables.add( new BoundVariable( keyCount, column, pd.getPropertyType(), value ) );
            }
            else
            {
                Class type = pd.getPropertyType();
                StringBuffer col = new StringBuffer();
        if (value == null ||
          (type == Integer.class || "int".equals(type.getName())) && ((Integer) value < 0) ||
          ( type == Double.class || "double".equals( type.getName() ) ) && ((Double) value < 0.0d))
        {
          continue;
        }

                if (columnCount > 0)
                {
                    col.append(", ");
                }
                col.append(column);
                col.append(" = ");
                col.append("?");
                columnCount++;
                bindVariables.add(new BoundVariable(columnCount, column, type, value));
                sql.append(col);
            }
        }

        // add the keys to the bind variable list
        for ( BoundVariable bv : keyBindVariables)
        {
            bindVariables.add( new BoundVariable(columnCount + bv.getPosition(), bv.getName(), bv.getType(), bv.getValue() ) );
        }

        sql.append( whereSQL );
        return sql.toString();
    }

    private String buildDeleteSQL( SimpleBean bean, Map<String,String> properties, ArrayList<BoundVariable> bindVariables ) throws Exception
    {
        StringBuffer sql = new StringBuffer( "DELETE ");

        sql.append( bean.getDBTableName() );
        sql.append( " WHERE " );

//        Iterator iter = properties.keySet().iterator();

        int colCount = 0;
/*
        while ( iter.hasNext() )
        {
*/
        for (String property : properties.keySet())
        {
            String column = properties.get( property );
            if ( column == null || "".equals( column ) )
            {
                column = SimpleDAOUtils.getPropertyDBName( property );
            }
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor( bean, property );
            Object value = PropertyUtils.getProperty ( bean, property );
            Class type = pd.getPropertyType();

/*
            if ( value != null )
            {
                if  ( ( type == Integer.class || "int".equals( type.getName() ) ) &&  ( ((Integer)value).intValue()  < 0 ) )
                {
                    continue;
                }
*/
/*
            if ( value == null ||
                 ( ( type == Integer.class || "int".equals( type.getName() ) ) &&  ( ((Integer)value).intValue()  < 0 ) ) )
*/
            if ( !SimpleDAOUtils.isPropertyNull( type, value ) )
            {

                if ( colCount > 0 )
                {
                    sql.append(" AND ");
                }
                sql.append( column );
                sql.append( " = ? " );
                colCount ++;
                bindVariables.add( new BoundVariable( colCount, column, type, value ));
            }
        }
        return sql.toString();
    }
    private boolean isColumnAKey( String[] keys, String column)
    {
        for ( String key : keys )
        {
            if ( key.equalsIgnoreCase( column ))
            {
        if ( log.isDebugEnabled()) { log.debug("Key column found: " + column) ;}
        return true;
            }
        }
        return false;
    }

}
TOP

Related Classes of simpledao.SimpleDAO

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