Java通过JDBC 进行Dao层的封装


前言

前面有一章节,我专门讲解了Java通过JDBC 进行MySQL数据库操作,这主要讲解了MySQL数据库的连接和简单的操作,但是在真正的Java项目中,我们要不断的和数据库打交道,为了提高数据库操作的执行效率和增加代码的复用性,将重新封装一个Dao层,也就是数据访问层 ,用来访问数据库实现数据的持久化。

Dao层设计

Dao层操作通用的步骤:

  • 1.写SQL语句
  • 2.获取连接
  • 3.创建stmt
  • 4.执行sql

a)更新 
String sql = “delete from admin where id=?””; 
String sql = “insert into admin (userName,pwd) values (?,?)” 
public void update(String sql, Object[] paramValues);

b)查询 
String sql = “select * from admin”; 
String sql = “select * from admin where id=? And pwd =?”; 
// 传入的什么类型的对象,就封装为什么类型 
// 要求: 列的名称,要与指定类型的对象的属性名称一样 
Public List query (String sql , Object[] paramValues , Class clazz); 
T t; // 对象赋值

  • 5.关闭/异常

编写BaseDao,自己写的所有的Dao都继承此类

其中JDBCUtil类在上篇博文Java通过JDBC 进行MySQL数据库操作中有详细介绍,这里就比说了。

/** * 通用的dao,自己写的所有的dao都继承此类; * 此类定义了2个通用的方法: * 1. 更新 * 2. 查询 * @author Charlie.chen * */ public class BaseDao { // 初始化参数 private Connection con; private PreparedStatement pstmt; private ResultSet rs; /** * 查询的通用方法 * @param sql * @param paramsValue */ public <T> List<T> query(String sql, Object[] paramsValue,Class<T> clazz){ try { // 返回的集合 List<T> list = new ArrayList<T>(); // 对象 T t = null; // 1. 获取连接 con = JdbcUtil.getConnection(); // 2. 创建stmt对象 pstmt = con.prepareStatement(sql); // 3. 获取占位符参数的个数, 并设置每个参数的值 int count = pstmt.getParameterMetaData().getParameterCount(); if (paramsValue != null && paramsValue.length > 0) { for (int i=0; i<paramsValue.length; i++) { pstmt.setObject(i+1, paramsValue[i]); } } // 4. 执行查询 rs = pstmt.executeQuery(); // 5. 获取结果集元数据 ResultSetMetaData rsmd = rs.getMetaData(); // ---> 获取列的个数 int columnCount = rsmd.getColumnCount(); // 6. 遍历rs while (rs.next()) { // 要封装的对象 t = clazz.newInstance(); // 7. 遍历每一行的每一列, 封装数据 for (int i=0; i<columnCount; i++) { // 获取每一列的列名称 String columnName = rsmd.getColumnName(i + 1); // 获取每一列的列名称, 对应的值 Object value = rs.getObject(columnName); // 封装: 设置到t对象的属性中 【BeanUtils组件】 BeanUtils.copyProperty(t, columnName, value); } // 把封装完毕的对象,添加到list集合中 list.add(t); } return list; } catch (Exception e) { throw new RuntimeException(e); } finally { JdbcUtil.closeAll(con, pstmt, rs); } } /** * 更新的通用方法 * @param sql 更新的sql语句(update/insert/delete) * @param paramsValue sql语句中占位符对应的值(如果没有占位符,传入null) */ public void update(String sql,Object[] paramsValue){ try { // 获取连接 con = JdbcUtil.getConnection(); // 创建执行命令的stmt对象 pstmt = con.prepareStatement(sql); // 参数元数据: 得到占位符参数的个数 int count = pstmt.getParameterMetaData().getParameterCount(); // 设置占位符参数的值 if (paramsValue != null && paramsValue.length > 0) { // 循环给参数赋值 for(int i=0;i<count;i++) { pstmt.setObject(i+1, paramsValue[i]); } } // 执行更新 pstmt.executeUpdate(); } catch (Exception e) { throw new RuntimeException(e); } finally { JdbcUtil.closeAll(con, pstmt, null); } }

 

编写实际操作的Dao类继承自BaseDao

public class AdminDao extends BaseDao { // 删除 public void delete(int id) { String sql = "delete from admin where id=?"; Object[] paramsValue = {id}; super.update(sql, paramsValue); } // 插入 public void insert(Admin admin) { String sql = "insert into admin (userName,pwd) values (?,?)"; Object[] paramsValue = {admin.getUserName(),admin.getPwd()}; super.update(sql, paramsValue); } // 查询全部 public List<Admin> getAll(){ String sql = "select * from admin"; List<Admin> list = super.query(sql, null, Admin.class); return list; } // 根据条件查询(主键) public Admin findById(int id){ String sql = "select * from admin where id=?"; List<Admin> list = super.query(sql, new Object[]{id}, Admin.class); return (list!=null&&list.size()>0) ? list.get(0) : null; } }

 

JavaBean类

/** * 1. bean类设计 * @author Charlie.chen * */ public class Admin { private int id; private String userName; private String pwd; private int age; private Date birth; public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Override public String toString() { return "Admin [age=" + age + ", birth=" + birth + ", id=" + id + ", pwd=" + pwd + ", userName=" + userName + "]"; } }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM