数据库操作基类设计心得

数据库操作是应用中最多的一个操作,代码也非常冗余,取得连接-建立statement-查询-释放所有资源,所以,这里做了一个基类,见下。

另外,此次基类的设计有一个心得,就是基类中只能设计成抛出异常,不能将异常处理的try/catch代码也放在基类中,虽然这样作,给将来的继 承类带来一些try/catch的代码的工作量,但还是十分必要的。因为如果将try/catch的代码都放在基类中,那么,可能会出现以下的一些问题:

1、以后的应用只要数据库操作异常,那么我们记录的日志中所出现的就都是基类的文件名,无法定位到具体是哪个实现类。这对于一个动作要牵动到很多实现类的时候,就不知道到底是那个实现步骤(实现类)出了问题。

2、如果将异常处理也集成进基类,那么就不能针对每个Action给出各种方式、各种类型的错误返回信息,而这一点是必须在各个Action针对的Bean里面做的。

3、Thinking in java中也是建议我们将异常处理放在逻辑类中进行的

4、在实现类中做异常处理,方便扩展,比如有些实现类就要catch其他种类的异常。

最后给出基类代码:

    /*
    * BaseBean.java
    *
    * Created on 2004年11月11日, 下午3:26
    
*/

    
package com.jointforce.logic;

    
import com.jointforce.entity.ECConfig;
    
import javax.sql.*;
    
import java.sql.*;
    
import java.net.*;
    
import java.io.*;
    
import java.util.*;
    
import org.apache.commons.logging.*;

    
/**
    *
    * 
@author  Super
    
*/
    
public class BaseBean {
       
        
/** Creates a new instance of BaseBean */
        
public BaseBean() {
        }
       
        
/*
         * Get a log instance
         * Many beans will extend from basebean
         * so we should define this.getClass here
         
*/
        
private Log log = LogFactory.getLog(this.getClass());
       
        
/*
         * Define config info
         
*/
        
protected ECConfig ecconfig = null;
       
        
public ECConfig getEcconfig() {
            
return ecconfig;
        }
        
public void setEcconfig(Object value) {
            ecconfig 
= (ECConfig)value;
        }
       
        
/*
         * Cache JNDI lookup result - DataSource
         
*/
        
protected DataSource datasource = null;
        
public DataSource getDatasource() {
            
return datasource;
        }
        
public void setDatasource(Object value) {
            datasource 
= (DataSource)value;
        }
       
        
// ============================================================= DataBase Operation
        /**
         * The connection of the database
         
*/
        
protected Connection conn = null;
       
        
public Connection getConn() throws SQLException {
            
if (conn == null) {
                conn 
= datasource.getConnection();
            }
            
return conn;
        }
       
        
/**
         * The container of db statements
         
*/
        
protected HashMap statements = new HashMap();
        
/**
         * Get statements from connection
         * the new statement will be registered in statements instance
         * so that we can release all statements in this basebean
         
*/
        
public Statement getStmt() throws SQLException {
            Statement tmp_stmt 
= conn.createStatement();
            
int statements_size = statements.size();
            String register_key 
= "statement" + Integer.toString(statements_size);
            statements.put(register_key, tmp_stmt);
           
            
return tmp_stmt;
        }
       
        
/**
         * The container of db resultset
         
*/
        
protected HashMap resultsets = new HashMap();
        
/**
         * Define a temp resultset to be used by classes which extend from basebean
         
*/
        
protected ResultSet tmp_rst = null;
       
        
/**
         * do Query action
         
*/
        
public ResultSet startQuery(String sql) throws SQLException {
            
// Get DataBase connection first
            getConn();
           
            
// Create Statement
            Statement tmp_stmt = getStmt();
           
            
// Get resultset
            ResultSet tmp_rst = tmp_stmt.executeQuery(sql);
            
//System.out.println(tmp_rst);
            int resultsets_size = resultsets.size();
            String register_key 
= "resultset" + Integer.toString(resultsets_size);
            resultsets.put(register_key, tmp_rst);
           
            
return tmp_rst;
        }
       
        
/**
         * do Update action
         
*/
        
public void startUpdate(String sql) throws SQLException {
            
// Get DataBase connection first
            getConn();
           
            
// Create Statement
            Statement tmp_stmt = getStmt();
           
            tmp_stmt.executeUpdate(sql);
        }
       
        
/**
         * Release all database resources
         
*/
        
public void releaseDBResources() throws SQLException {
            
// Release resultsets
            Iterator it = resultsets.keySet().iterator();
            
while (it.hasNext())
            {
                String key 
= (String)it.next();
                ResultSet temprs 
= (ResultSet)resultsets.get(key);
                
if (temprs != null) {
                    temprs.close();
                    temprs 
= null;
                }
            }
           
            
// Release statements
            it = statements.keySet().iterator();
            
while (it.hasNext())
            {
                String key 
= (String)it.next();
                Statement tempst 
= (Statement)statements.get(key);
                
if (tempst != null) {
                    tempst.close();
                    tempst 
= null;
                }
            }
           
            
// Release Connection
            if (conn != null && !conn.isClosed()) {
                conn.close();
                conn 
= null;
            } 
else if (conn != null) {
                conn 
= null;
            }
        }
       
       
        
// ============================================================= Socket Operation
    }
原文地址:https://www.cnblogs.com/super119/p/1988607.html