Java—如何在DAO内处理JDBC连接

Java—如何在DAO内处理JDBC连接,java,jdbc,object-pooling,Java,Jdbc,Object Pooling,我有一个DAO,我实现了一个连接池。我使用单例实例化连接池,使其只有一个实例。我调用getConnection函数来获取DAO内部的连接。我对DAO中的每个方法都这样做?这是处理DAO连接的好方法吗?有没有更有效的方法来设置我的池并使其与我的DAO一起工作?特别是JDBC public class SQLUserDAO implements GenericDAO<User, String, Boolean> { @Override public void updat

我有一个DAO,我实现了一个连接池。我使用单例实例化连接池,使其只有一个实例。我调用getConnection函数来获取DAO内部的连接。我对DAO中的每个方法都这样做?这是处理DAO连接的好方法吗?有没有更有效的方法来设置我的池并使其与我的DAO一起工作?特别是JDBC

public class SQLUserDAO implements GenericDAO<User, String, Boolean>
{

    @Override
    public void update(User user, Boolean active) throws NotFoundException
        {
            // Create the ConnectionPool:
            JDBCConnectionPool pool = JDBCConnectionPool.getPoolInstance();




            // Get a connection:
            Connection con = pool.checkOut();

            // Return the connection:
            pool.checkIn(con);
        }

    @Override
    public void delete(User user, Boolean active) throws NotFoundException
        {
            // Create the ConnectionPool:
            JDBCConnectionPool pool = JDBCConnectionPool.getPoolInstance();

            // Get a connection:
            Connection con = pool.checkOut();

            // Return the connection:
            pool.checkIn(con);

        }

    @Override
    public User findByKey(String key, Boolean active) throws NotFoundException
        {
            // Create the ConnectionPool:
            JDBCConnectionPool pool = JDBCConnectionPool.getPoolInstance();

            // Get a connection:
            Connection con = pool.checkOut();

            // Return the connection:
            pool.checkIn(con);
            return null;
        }

    @Override
    public User findByValue(User object, Boolean active)
            throws NotFoundException
        {
            // Create the ConnectionPool:
            JDBCConnectionPool pool = JDBCConnectionPool.getPoolInstance();

            // Get a connection:
            Connection con = pool.checkOut();

            // Return the connection:
            pool.checkIn(con);
            return null;
        }

    @Override
    public void insert(User user, Boolean active) throws NotFoundException
        {
            // Create the ConnectionPool:
            JDBCConnectionPool pool = JDBCConnectionPool.getPoolInstance();

            // Get a connection:
            Connection conn = pool.checkOut();

            PreparedStatement preparedStatement;

            try
            {
                preparedStatement = conn
                        .prepareStatement("INSERT INTO users(user_id, user_name, user_password) VALUES (?,?,?)");

                preparedStatement.setString(1, user.getUserId().toString());
                preparedStatement.setString(2, user.getUserName());
                preparedStatement.setString(3, user.getClearTextPassword());

                // execute insert SQL stetement
                preparedStatement.executeUpdate();
            }
            catch (SQLException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // Return the connection:
            pool.checkIn(conn);
        }
}
公共类SQLUserDAO实现GenericDAO
{
@凌驾
公共无效更新(用户,布尔活动)引发NotFoundException
{
//创建连接池:
JDBCConnectionPool-pool=JDBCConnectionPool.getPoolStance();
//获取连接:
连接con=pool.checkOut();
//返回连接:
池。签入(con);
}
@凌驾
公共void delete(用户用户,布尔活动)引发NotFoundException
{
//创建连接池:
JDBCConnectionPool-pool=JDBCConnectionPool.getPoolStance();
//获取连接:
连接con=pool.checkOut();
//返回连接:
池。签入(con);
}
@凌驾
公共用户findByKey(字符串键,布尔活动)引发NotFoundException
{
//创建连接池:
JDBCConnectionPool-pool=JDBCConnectionPool.getPoolStance();
//获取连接:
连接con=pool.checkOut();
//返回连接:
池。签入(con);
返回null;
}
@凌驾
公共用户findByValue(用户对象,布尔活动)
抛出NotFoundException
{
//创建连接池:
JDBCConnectionPool-pool=JDBCConnectionPool.getPoolStance();
//获取连接:
连接con=pool.checkOut();
//返回连接:
池。签入(con);
返回null;
}
@凌驾
公共void insert(用户用户,布尔活动)引发NotFoundException
{
//创建连接池:
JDBCConnectionPool-pool=JDBCConnectionPool.getPoolStance();
//获取连接:
连接conn=pool.checkOut();
编制报表编制报表;
尝试
{
preparedStatement=conn
.prepareStatement(“插入用户(用户id、用户名、用户密码)值(?,?)”;
preparedStatement.setString(1,user.getUserId().toString());
preparedStatement.setString(2,user.getUserName());
preparedStatement.setString(3,user.getClearTextPassword());
//执行insert SQL语句
preparedStatement.executeUpdate();
}
捕获(SQLE异常)
{
//TODO自动生成的捕捉块
e、 printStackTrace();
}
//返回连接:
游泳池登记(康涅狄格州);
}
}
对象池

public abstract class ObjectPool<T>
{
    private long expirationTime;
    private Hashtable<T, Long> locked, unlocked;

    public ObjectPool()
    {
        expirationTime = 30000; // 30 seconds
        locked = new Hashtable<T, Long>();
        unlocked = new Hashtable<T, Long>();
    }

    protected abstract T create();

    public abstract boolean validate(T o);

    public abstract void expire(T o);

    public synchronized T checkOut()
        {
            long now = System.currentTimeMillis();
            T t;
            if (unlocked.size() > 0)
            {
                Enumeration<T> e = unlocked.keys();
                while (e.hasMoreElements())
                {
                    t = e.nextElement();
                    if ((now - unlocked.get(t)) > expirationTime)
                    {
                        // object has expired
                        unlocked.remove(t);
                        expire(t);
                        t = null;
                    }
                    else
                    {
                        if (validate(t))
                        {
                            unlocked.remove(t);
                            locked.put(t, now);
                            return (t);
                        }
                        else
                        {
                            // object failed validation
                            unlocked.remove(t);
                            expire(t);
                            t = null;
                        }
                    }
                }
            }
            // no objects available, create a new one
            t = create();
            locked.put(t, now);
            return (t);
        }

    public synchronized void checkIn(T t)
        {
            locked.remove(t);
            unlocked.put(t, System.currentTimeMillis());
        }
}
公共抽象类对象池
{
私人长到期时间;
私有哈希表已锁定,未锁定;
公共对象池()
{
expirationTime=30000;//30秒
锁定=新哈希表();
unlocked=新哈希表();
}
受保护的抽象T create();
公共抽象布尔验证(TO);
公开摘要失效;
公共同步T签出()
{
long now=System.currentTimeMillis();
T;
如果(未锁定的.size()>0)
{
枚举e=unlockes.keys();
而(e.hasMoreElements())
{
t=e.nextElement();
if((现在-unlocked.get(t))>expirationTime)
{
//对象已过期
解锁。移除(t);
过期(t);
t=零;
}
其他的
{
如果(验证(t))
{
解锁。移除(t);
锁定。放置(t,现在);
返回(t);
}
其他的
{
//对象验证失败
解锁。移除(t);
过期(t);
t=零;
}
}
}
}
//没有可用对象,请创建一个新对象
t=创建();
锁定。放置(t,现在);
返回(t);
}
公共同步无效签入(T)
{
锁定。移除(t);
unlocked.put(t,System.currentTimeMillis());
}
}
连接池

public class JDBCConnectionPool extends ObjectPool<Connection>
{
private String dsn, usr, pwd;

private JDBCConnectionPool()
{
    super();

    try
    {
        Properties p = new Properties();
        FileInputStream input = new FileInputStream(
                "src/dbproperties");
        p.load(input);
        String driver = p.getProperty("driver");
        this.dsn = p.getProperty("url");
        this.usr = p.getProperty("user");
        this.pwd = p.getProperty("password");

        DriverManager
                .registerDriver((oracle.jdbc.driver.OracleDriver) Class
                        .forName(driver).newInstance());

        input.close();

    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    catch (InstantiationException e)
    {

        e.printStackTrace();
    }
    catch (IllegalAccessException e)
    {

        e.printStackTrace();
    }
    catch (SQLException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (ClassNotFoundException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

private static class LazySingleton
{
    private static final JDBCConnectionPool SINGLETONINSTANCE = new JDBCConnectionPool();
}

public static JDBCConnectionPool getPoolInstance()
    {
        return LazySingleton.SINGLETONINSTANCE;
    }

@Override
protected Connection create()
    {
        try
        {
            return (DriverManager.getConnection(dsn, usr, pwd));
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return (null);
        }
    }

@Override
public void expire(Connection o)
    {
        try
        {
            ((Connection) o).close();
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

@Override
public boolean validate(Connection o)
    {
        try
        {
            return (!((Connection) o).isClosed());
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return (false);
        }
    }
公共类JDBCConnectionPool扩展了ObjectPool
{
专用字符串dsn、usr、pwd;
私有JDBCConnectionPool()
{
超级();
尝试
{
属性p=新属性();
FileInputStream输入=新FileInputStream(
“src/dbproperties”);
p、 负载(输入);
字符串驱动程序=p.getProperty(“驱动程序”);
this.dsn=p.getProperty(“url”);
this.usr=p.getProperty(“用户”);
this.pwd=p.getProperty(“密码”);
驱动管理器
.registerDriver((oracle.jdbc.driver.OracleDriver)类
.forName(驱动程序).newInstance());
input.close();
}
catch(filenotfounde异常)
{
e、 printStackTrace();
}
捕获(IOE异常)
{
e、 printStackTrace();
}
捕获(实例化异常e)
{
e、 printStackTrace();
}
捕获(非法捕获)