"iBATIS"的簡易實現

java 代碼
  1. package com.viwo.sqlmap.config;   
  2.   
  3. import java.sql.Connection;   
  4. import java.sql.ResultSet;   
  5. import java.sql.ResultSetMetaData;   
  6. import java.sql.SQLException;   
  7. import java.sql.Statement;   
  8. import java.util.ArrayList;   
  9. import java.util.HashMap;   
  10. import java.util.List;   
  11. import java.util.Map;   
  12.   
  13. import org.apache.commons.beanutils.BeanUtils;   
  14. import org.apache.commons.digester.Digester;   
  15.   
  16. import org.apache.log4j.Logger;   
  17.   
  18.   
  19. import com.viwo.sqlmap.factory.ConnectionFactory;   
  20.   
  21. /**  
  22.  * DAO using this class, don't need write jdbc operations.  
  23.  *   
  24.  * @author viwo   
  25.  *    
  26.  */  
  27. public class SqlMapConfig    
  28. {   
  29.  private final static Logger logger = Logger.getLogger(SqlMapConfig.class);   
  30.  private Map selectMap = new HashMap();   
  31.  private Map executeMap = new HashMap();   
  32.  private static Map configMap = new HashMap();   
  33.  private Connection connection = null;   
  34.  private Statement statement = null;   
  35.     /**  
  36.      * get a List object from database  
  37.      *   
  38.      * fit for this sql: select username,password from users  
  39.      *   
  40.      * the " name, password " and its values are packed in an object list of return  
  41.      * list.  
  42.      *   
  43.      * @param selectId  
  44.      * @param paramObject  
  45.      * @return List  
  46.      * @throws Exception   
  47.      */  
  48.  public List QueryForList(String selectId,Object paramObject) throws Exception    
  49.  {   
  50.   logger.debug("[viwo]-->[enter QueryForList]");   
  51.   List list = new ArrayList();   
  52.      
  53.   try    
  54.   {   
  55.    ConfigSelect configSelect =(ConfigSelect)selectMap.get(selectId);   
  56.    if(configSelect!=null)   
  57.    {   
  58.     String sql = configSelect.getSql();   
  59.     String type = configSelect.getType();   
  60.     String param = configSelect.getParam();   
  61.           if(paramObject.getClass() != Class.forName(param))   
  62.           {   
  63.            return null;   
  64.           }   
  65.           String[] sqls = sql.split("#");   
  66.           if(sqls.length>1)   
  67.           {   
  68.            for(int i=0;i            {   
  69.             if(i%2!=0)   
  70.             {   
  71.              String tmpValue = BeanUtils.getProperty(paramObject, sqls[i]);   
  72.              sql = sql.replaceFirst("#"+sqls[i]+"#""'"+tmpValue+"'");   
  73.             }   
  74.            }   
  75.           }   
  76.           logger.debug("[viwo]-->[QueryForList]-->[sql:]"+sql);   
  77.     //PreparedStatement ps = connection.prepareStatement(sql);   
  78.     ResultSet rs = statement.executeQuery(sql);   
  79.     ResultSetMetaData meta =  rs.getMetaData();   
  80.        int columnCount = meta.getColumnCount();   
  81.        while(rs.next())   
  82.        {   
  83.         Object newItem = Class.forName(type).newInstance();   
  84.         for(int i=1;i<=columnCount;i++)   
  85.         {   
  86.          Object rsItem = null;    
  87.          String columnType = meta.getColumnTypeName(i);   
  88.          if(columnType.equals("numeric"))   
  89.           rsItem = new Double(rs.getDouble(meta.getColumnName(i)));   
  90.          else if(columnType.equals("int"))   
  91.           rsItem = new Integer(rs.getInt(meta.getColumnName(i)));   
  92.          else  
  93.           rsItem = rs.getString(meta.getColumnName(i));   
  94.             
  95.          BeanUtils.setProperty(newItem, meta.getColumnName(i), rsItem);   
  96.         }   
  97.         list.add(newItem);   
  98.        }   
  99.    }   
  100.          
  101.   }    
  102.   catch (Exception e)   
  103.   {   
  104.    logger.error("[viwo]-->[QueryForList]-->"+e.getMessage());   
  105.    throw new Exception(e);   
  106.   }   
  107.   return list;   
  108.  }   
  109.     
  110.     /**  
  111.      * get an object from database  
  112.      *   
  113.      * fit for this sql: select username,password from users where username=#username#  
  114.      *   
  115.      * the " name, password " and its values are packed in an object of return  
  116.      * object.  
  117.      *   
  118.      * @param selectId  
  119.      * @param paramObject  
  120.      * @return Object  
  121.      * @throws Exception   
  122.      */  
  123.  public Object QueryForObject(String selectId,Object paramObject) throws Exception    
  124.  {   
  125.   logger.debug("[viwo]-->[enter QueryForObject]");   
  126.   try    
  127.   {   
  128.    ConfigSelect configSelect =(ConfigSelect)selectMap.get(selectId);   
  129.    if(configSelect!=null)   
  130.    {   
  131.     String sql = configSelect.getSql();   
  132.     String type = configSelect.getType();   
  133.     String param = configSelect.getParam();   
  134.           if(paramObject.getClass() != Class.forName(param))   
  135.           {   
  136.            return null;   
  137.           }   
  138.           String[] sqls = sql.split("#");   
  139.           if(sqls.length>1)   
  140.           {   
  141.            for(int i=0;i            {   
  142.             if(i%2!=0)   
  143.             {   
  144.              String tmpValue = BeanUtils.getProperty(paramObject, sqls[i]);   
  145.              sql = sql.replaceFirst("#"+sqls[i]+"#""'"+tmpValue+"'");   
  146.             }   
  147.            }   
  148.           }   
  149.           logger.debug("[viwo]-->[QueryForObject]-->[sql:]"+sql);   
  150.     //PreparedStatement ps = connection.prepareStatement(sql);   
  151.           ResultSet rs = statement.executeQuery(sql);   
  152.     ResultSetMetaData meta =  rs.getMetaData();   
  153.        int columnCount = meta.getColumnCount();   
  154.        if(rs.next())   
  155.        {   
  156.         Object newItem = Class.forName(type).newInstance();   
  157.         for(int i=1;i<=columnCount;i++)   
  158.         {   
  159.          Object rsItem = null;    
  160.          String columnType = meta.getColumnTypeName(i);   
  161.          if(columnType.equals("numeric"))   
  162.           rsItem = new Double(rs.getDouble(meta.getColumnName(i)));   
  163.          else if(columnType.equals("int"))   
  164.           rsItem = new Integer(rs.getInt(meta.getColumnName(i)));   
  165.          else  
  166.           rsItem = rs.getString(meta.getColumnName(i));   
  167.             
  168.          BeanUtils.setProperty(newItem, meta.getColumnName(i), rsItem);   
  169.         }   
  170.         return newItem;   
  171.        }   
  172.    }   
  173.      
  174.   }    
  175.   catch (Exception e)   
  176.   {   
  177.    logger.error("[viwo]-->[QueryForObject]-->"+e.getMessage());   
  178.    throw new Exception(e);   
  179.   }   
  180.   //如果沒有查出結果或者selectId非法則返回null。   
  181.   return null;   
  182.  }   
  183.     
  184.     /**  
  185.      * execute a statement from sqlmap-config.xml by executeId  
  186.      *   
  187.      * fit for this sql: insert into users values(#username#,#password#)  
  188.      *   
  189.      * the " #name#, #password# " will be set value by paramObject  
  190.      *   
  191.      * @param selectId  
  192.      * @param paramObject  
  193.      * @return int  
  194.      * @throws Exception   
  195.      */  
  196.  public int executeStatement(String executeId,Object paramObject) throws Exception    
  197.  {   
  198.   logger.debug("[viwo]-->[enter executeStatement]");   
  199.   try    
  200.   {   
  201.    ConfigExecute configExecute =(ConfigExecute)executeMap.get(executeId);   
  202.    if(configExecute!=null)   
  203.    {   
  204.     String sql = configExecute.getSql();   
  205.     String param = configExecute.getParam();   
  206.           if(paramObject.getClass() != Class.forName(param))   
  207.           {   
  208.            return -1;   
  209.           }   
  210.           String[] sqls = sql.split("#");   
  211.           if(sqls.length>1)   
  212.           {   
  213.            for(int i=0;i            {   
  214.             if(i%2!=0)   
  215.             {   
  216.              String tmpValue = BeanUtils.getProperty(paramObject, sqls[i]);   
  217.              sql = sql.replaceFirst("#"+sqls[i]+"#""'"+tmpValue+"'");   
  218.             }   
  219.            }   
  220.           }   
  221.           logger.debug("[viwo]-->[executeStatement]-->[sql:]"+sql);   
  222.     //PreparedStatement ps = connection.prepareStatement(sql);   
  223.     return statement.executeUpdate(sql);   
  224.    }   
  225.      
  226.   }    
  227.   catch (Exception e)   
  228.   {   
  229.    e.printStackTrace();   
  230.    logger.error("[viwo]-->[executeStatement]-->"+e.getMessage());   
  231.    //throw new Exception(e);   
  232.   }   
  233.   return -1;   
  234.  }   
  235.     
  236.  public void addSelect(ConfigSelect configSelect)   
  237.  {   
  238.   selectMap.put(configSelect.getId(), configSelect);   
  239.  }   
  240.  public void addExecute(ConfigExecute configExecute)   
  241.  {   
  242.   executeMap.put(configExecute.getId(), configExecute);   
  243.  }   
  244.     
  245.  public Map getSelectMap() {   
  246.   return selectMap;   
  247.  }   
  248.     
  249.     /**  
  250.      * a static synchronized method to get the SqlMapConfig from a gived path  
  251.      *    
  252.      * this method will initialize the properity connection   
  253.      *   
  254.      * @param path  
  255.      * @return SqlMapConfig  
  256.      * @throws Exception   
  257.      */  
  258.  public static synchronized SqlMapConfig getInstance(String path) throws Exception   
  259.  {   
  260.   logger.info("[viwo]-->[enter getInstance]-->[path:]"+path);   
  261.   SqlMapConfig sqlMapConfig = null;   
  262.   if(configMap.get(path)!=null)   
  263.   {   
  264.    sqlMapConfig = (SqlMapConfig)configMap.get(path);   
  265.   }   
  266.   else  
  267.   {   
  268.       Digester digester = new Digester();     
  269.          digester.setValidating(false);    
  270.          digester.addObjectCreate("sqlmap-config""com.viwo.sqlmap.config.SqlMapConfig");   
  271.             
  272.          digester.addObjectCreate("sqlmap-config/select""com.viwo.sqlmap.config.ConfigSelect");   
  273.          digester.addSetProperties("sqlmap-config/select");   
  274.          digester.addCallMethod("sqlmap-config/select/sql""setSql"0);   
  275.          digester.addSetNext("sqlmap-config/select""addSelect""com.viwo.sqlmap.config.ConfigSelect");   
  276.             
  277.             digester.addObjectCreate("sqlmap-config/execute""com.viwo.sqlmap.config.ConfigExecute");   
  278.          digester.addSetProperties("sqlmap-config/execute");   
  279.          digester.addCallMethod("sqlmap-config/execute/sql""setSql"0);   
  280.          digester.addSetNext("sqlmap-config/execute""addExecute""com.viwo.sqlmap.config.ConfigExecute");   
  281.             
  282.          try    
  283.          {   
  284.           sqlMapConfig = (SqlMapConfig)digester.parse(Thread.currentThread().getContextClassLoader().getResource("/"+path).getFile());   
  285.           configMap.put(path, sqlMapConfig);   
  286.          }    
  287.       catch (Exception e)   
  288.       {   
  289.        logger.error("[viwo]-->[getInstance]-->"+e.getMessage());   
  290.        throw new Exception(e);   
  291.       }   
  292.   }   
  293.      
  294.   sqlMapConfig.connection = ConnectionFactory.getConnection();   
  295.   sqlMapConfig.statement = sqlMapConfig.connection.createStatement();   
  296.      
  297.      return sqlMapConfig;   
  298.     
  299.  }   
  300.     
  301.     /**  
  302.      * begin transaction   
  303.      * @throws Exception   
  304.      */  
  305.  public void beginTransaction() throws Exception   
  306.  {   
  307.   try    
  308.   {   
  309.    this.connection.setAutoCommit(false);   
  310.   }    
  311.   catch (SQLException e)    
  312.   {   
  313.    logger.error("[viwo]-->[beginTransaction]--beginTransaction error");   
  314.    throw new Exception(e);   
  315.   }   
  316.  }   
  317.     
  318.     /**  
  319.      * commit transaction   
  320.      * @throws Exception   
  321.      */  
  322.  public void commitTransaction() throws Exception   
  323.  {   
  324.   try    
  325.   {   
  326.    this.connection.commit();   
  327.   }    
  328.   catch (SQLException e)    
  329.   {   
  330.    logger.error("[viwo]-->[commitTransaction]--commitTransaction error");   
  331.    throw new Exception(e);   
  332.   }   
  333.  }   
  334.     /**  
  335.      * rollback transaction   
  336.      * @throws Exception   
  337.      */  
  338.  public void rollbackTransaction() throws Exception   
  339.  {   
  340.   try    
  341.   {   
  342.    this.connection.rollback();   
  343.   }    
  344.   catch (SQLException e)    
  345.   {   
  346.    logger.error("[viwo]-->[rollbackTransaction]--rollbackTransaction error");   
  347.    throw new Exception(e);   
  348.   }   
  349.  }   
  350.     /**  
  351.      * close the property of connection   
  352.      */  
  353.  public void closeConnection()   
  354.  {   
  355.   if(statement!=null)   
  356.   {   
  357.   try {   
  358.     statement.close();   
  359.    }    
  360.    catch (SQLException e)    
  361.    {   
  362.       
  363.    }   
  364.   }   
  365.   if(connection!=null)   
  366.   {   
  367.   try {   
  368.     connection.close();   
  369.    }    
  370.    catch (SQLException e)    
  371.    {   
  372.       
  373.    }   
  374.   }   
  375.  }   
  376.   
  377. }   
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章