Java学习-JDBC(五)

JDBC优化及工具类封装
现有问题
  • ①创建连接池
  • ②获取连接
  • ③连接回收
ThreadLocal
  • 为解决多线程程序的并发问题提供了一种新的思路,使用这个工具类可以很简洁地编写出优美的多线程程序,通常用在多线程中管理共享数据库连接、Session等
  • ThreadLocal用于保存某个线程共享变量,原因是Java中,每一个线程对象都有一个ThreadLocalMap<ThreadLocal,Object>,其key就是一个ThreadLocal,而Object即为该线程的共享变量
  • 这个map通过ThreadLocal的set和get方法操作,对于同一个static ThreadLocal,不同线程只能从中get,set,remove自己的变量,而不影响其他线程的变量
    • 在进行对象跨层传递的时候,使用ThreadLocal可以避免多次传递,打破层次间的约束
    • 线程间数据隔离
    • 进行事务操作,用于存储线程事务信息
    • 数据库连接,Session会话管理
  • ThreadLocal对象.get:获取ThreadLocal中当前线程共享变量的值
  • ThreadLocal对象.set:设置ThreadLocal中当前线程共享变量的值
  • ThreadLocal对象.remove:移除ThreadLocal中当前线程共享变量的值
package com.lotus.senior.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Administrator
 * JDBC 工具类(v2.0)
 * 1.维护一个连接池对象,维护了一个线程绑定变量的ThreadLocal对象
 * 2.对外提供在ThreadLocal中获取连接的方法
 * 3.对外提供回收连接的方法,回收过程中,将要回收的连接从ThreadLocal中移除
 * 注:工具类仅对外提供共性功能代码,方法为静态代码
 * 使用ThreadLocal为了一个线程在多次数据库操作过程中,使用的是同一个线程
 */
public class JDBCUtilV2 {
    //创建连接池引用,给当前项目全局使用
    private static DataSource dataSource;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    //在项目启动时,创建连接池对象,赋值给dataSource
    static {
        Properties properties = new Properties();
        InputStream is = JDBCUtilV2.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //对外提供在连接池中获取连接方法
    public static Connection getConnection() {
        try {
            //在threadLocal中获取connection
            Connection connection = threadLocal.get();
            if (connection == null) {
                //从连接池中获取一个连接,存储到ThreadLocal中
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            }
            return connection;
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }
    }
    //回收连接
    public static void destory() {
        try {
            Connection conn = threadLocal.get();
            if (conn != null) {
                //从threadLocal中移除当前已经存储的Connection对象
                threadLocal.remove();
                //将connection连接归还连接
                conn.close();
            }

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

DAO封装
DAO概念
  • DAO(Data Access Object)数据访问对象
  • Java面向对象语言,数据在Java中通常以对象形式存在,一张表对应一个实体类,一张表的操作对应一个DAO对象
  • 在Java操作数据库时,我们会将对同一张表的增删改查操作统一维护起来,维护的这个类即DAO层
  • DAO只关注数据库操作,供业务层Service调用,将职责划分清楚
BaseDAO概念
  • 基本上每个数据表都应该有一个对应的DAO接口及实现类,发现对所有表的操作(增删改查)代码重复度很高,所以可以抽取公共代码,给这些DAO的实现类抽取一个公共的父类,复用基本操作,称为BaseDAO
BaseDAO搭建
/**
 * Administrator
 * 将共性的数据库代码封装在BaseDAO
 */
public class BaseDAO {
    /**
     * 通用的增删改方法
     * @param sql   调用要执行的SQL语句
     * @param params SQL语句中占位符要赋的值
     * @return 受影响的行数
     */
    public int executeUpdate(String sql,Object ... params) {
        int row = 0;
        Connection conn = JDBCUtilV2.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            //预编译SQL
            preparedStatement = conn.prepareStatement(sql);
            //为占位符赋值,执行SQL,接收返回结果
            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    preparedStatement.setObject(i+1,params[i]);
                }
            }
            row = preparedStatement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            JDBCUtilV2.destory();
        }
        //返回影响行数
        return row;
    }
    /**
     * 查询结果:
     * 单行单列:封装一个结果
     * 多行多列:List<Employee>
     * 单行多列:Employee
     * 封装过程:
     *  ①返回类型,调用时,将此次查询的结果类型告知BaseDAO就可以了
     *  ③返回结果,通用List,可存储多个结果或一个结果
     *  ③结果封装,反射,要求调用者告知BaseDAO要封装对象的类对象,Class
     */
    public <T> List<T> executeQuery(Class<T> clazz,String sql,Object ... params) throws SQLException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        //获取连接
        Connection conn = JDBCUtilV2.getConnection();
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        //设置占位符值
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i+1,params[i]);
            }
        }
        //执行SQL,并接收返回结果集
        ResultSet rs = preparedStatement.executeQuery();
        //获取结果集中的元数据对象--包含了列的数量和列名
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        List<T> list = new ArrayList<>();
        while (rs.next()) {
            //循环一次,代表有一条数据,使用反射创建一个对象
            T t = clazz.newInstance();
            //循环遍历当前行的列,循环几次,有多少列
            for (int i = 1; i <= columnCount; i++) {
                //通过下表获取列的值
                Object value = rs.getObject(i);
                //获取到的列的value值,这个值是t这个对象的某个属性
                String fieldName = metaData.getColumnLabel(i);
                //利用反射,通过类对象获取对象属性
                Field field = clazz.getDeclaredField(fieldName);
                //取消属性的封装检查
                field.setAccessible(true);
                field.set(t,value);
            }
            list.add(t);
        }
        rs.close();
        preparedStatement.close();
        JDBCUtilV2.destory();
        return list;
    }

    /**
     * 通用查询,在上面查询的集合结果中获取一个结果,简化单行单列数据获取,单行多列数据获取
     */
    public <T> T executeQueryBean(Class<T> clazz,String sql,Object ... params) throws SQLException, IllegalAccessException, InstantiationException, NoSuchFieldException {
       List<T> list = this.executeQuery(clazz,sql,params);
       if (list == null || list.size() == 0) {
           return null;
       }
       return list.get(0);
    }
}

package com.lotus.senior.dao;

import com.lotus.senior.pojo.Employee;

import java.util.List;

/**
 * t_emp表的增删改查操作---接口定义规范
 */
public interface EmployeeDao {
    /**
     * 数据库中查询所有操作
     * @return 表中所有数据
     */
    List<Employee> selectAll();

    /**
     * 根据empId查询单个员工数据操作
     * @param empId 主键值
     * @return 一个员工对象(一行数据)
     */
    Employee selectByEmpId(Integer empId);

    /**
     * 新增一条数据
     * @param employee
     * @return 受影响行数
     */
    int insert(Employee employee);

    /**
     * 更新一条员工记录
     * @param employee
     * @return
     */
    int update(Employee employee);

    /**
     * 根据empId删除一条员工记录
     * @param empId
     * @return
     */
    int delete(Integer empId);
}

//实现类
package com.lotus.senior.dao.impl;

import com.lotus.senior.dao.BaseDAO;
import com.lotus.senior.dao.EmployeeDao;
import com.lotus.senior.pojo.Employee;

import java.sql.SQLException;
import java.util.List;

public class EmployeeDaoImpl extends BaseDAO implements EmployeeDao {
    @Override
    public List<Employee> selectAll() {
        String sql = "select emp_id empId,emp_name empName,emp_salary empSalary,emp_age empAge from t_emp";
        try {
            return executeQuery(Employee.class,sql,null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Employee selectByEmpId(Integer empId) {
        String sql = "select emp_id empId,emp_name empName,emp_salary empSalary,emp_age empAge from t_emp where emp_id = ?";
        try {
            Employee employee = executeQueryBean(Employee.class, sql, empId);
            return employee;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int insert(Employee employee) {
        try {
            String sql = "insert into t_emp(emp_name,emp_salary,emp_age)values(?,?,?)";
            return executeUpdate(sql,employee.getEmpName(),employee.getEmpSalary(),employee.getEmpAge());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(Employee employee) {
        try {
            String sql = "update t_emp set emp_salary = ? where emp_id = ?";
            return executeUpdate(sql,employee.getEmpSalary(),employee.getEmpId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int delete(Integer empId) {
        try {
            String sql = "delete from  t_emp where emp_id = ?";
            return executeUpdate(sql,empId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值