## 一、什么是DAO层 DAO层是数据管理层,用来进行与数据库的数据交互,实现数据持久存储,全称为Data Access Object。 DAO层的文件结构: ```plaintext 📁com.域名.项目名/ ├── 📁dao/ 数据管理层 │ ├── 📁impl/ 接口实现类包 │ │ └── ☕️表名DaoImpl.java 接口实现类 │ └── ☕️表名Dao.java 接口 ├── 📁po/ 持久化对象包 │ └── ☕️表对象实例化.java 持久化对象 └── 📁util/ 工具类包 ├── ☕️CommonUtil.java 通用工具类 └── ☕️DBUtil.java 数据库工具类 ``` ## 二、数据库工具类(util包) 该类主要作用为数据库连接、断开等,大多数为静态方法 ```java package com.doooog.test.util; import java.sql.*; public class DBUtil { private static final String URL = "jdbc:mysql://localhost:3306/mysqlDbName?characterEncoding=utf-8"; private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String USERNAME = "root"; private static final String PASSWORD = "password"; // 获取Connection数据库连接 public static Connection getConnection() { Connection con = null; try { Class.forName(DRIVER); con = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (ClassNotFoundException | SQLException e) { System.out.println(e.getMessage()); } return con; } // 关闭连接 public static void closeRes(Connection con, PreparedStatement pst,ResultSet rs ) { try { if (rs != null) rs.close(); if (pst != null) pst.close(); if (con != null) con.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } } ``` ## 三、通用工具类(util包) 该类主要作用为获取一些通用的数据,比如时间戳、设备信息等,大多为静态方法 ```java package com.doooog.test.util; import java.text.SimpleDateFormat; import java.util.Date; public class CommonUtil { // 获取系统日期 public static String getNewDate() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(new Date()); } } ``` ## 四、表对象实例化类(po包) 该类作用为将表项数据转换为对象数据存储到内存,以便于后续面向对象编程。 ```java package com.doooog.test.po; public class Emp { private Integer EMPno; private String ename; private String job; private Integer mgr; private String hiredate; private Double sal; private Double comm; private Integer DEPTno; public Emp() { } public Emp(Integer EMPno, String ename, String job, Integer mgr, String hiredate, Double sal, Double comm, Integer DEPTno) { this.EMPno = EMPno; this.ename = ename; this.job = job; this.mgr = mgr; this.hiredate = hiredate; this.sal = sal; this.comm = comm; this.DEPTno = DEPTno; } public Integer getDEPTno() { return DEPTno; } public void setDEPTno(Integer DEPTno) { this.DEPTno = DEPTno; } public Double getComm() { return comm; } public void setComm(Double comm) { this.comm = comm; } public Double getSal() { return sal; } public void setSal(Double sal) { this.sal = sal; } public String getHiredate() { return hiredate; } public void setHiredate(String hiredate) { this.hiredate = hiredate; } public Integer getMgr() { return mgr; } public void setMgr(Integer mgr) { this.mgr = mgr; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public Integer getEMPno() { return EMPno; } public void setEMPno(Integer EMPno) { this.EMPno = EMPno; } @Override public String toString() { return "Emp{" + "EMPno=" + EMPno + ", ename='" + ename + '\'' + ", job='" + job + '\'' + ", mgr='" + mgr + '\'' + ", hiredate='" + hiredate + '\'' + ", sal=" + sal + ", comm=" + comm + ", DEPTno=" + DEPTno + '}'; } } ``` ## 五、表数据操作接口(dao包) 该类接口主要定义需要实现操作的方法,比如查询、增删改等 ```java package com.doooog.test.dao; import com.doooog.test.po.Emp; import java.util.List; public interface EmpDao { List selectEmpAll(); Emp selectEmpById(Integer id); int insertEmp(Emp emp); int insertEmp(String ename, String job, Integer mgr, Double sal, Double comm, Integer DEPTno); int updateEname(int EMPno, String ename); int updateJob(int EMPno, String job); int updateMgr(int EMPno, Integer mgr); int updateHireDate(int EMPno, String hireDate); int updateSal(int EMPno, Double sal); int updateComm(int EMPno, Double comm); int updateDEPTno(int EMPno, Integer DEPTno); int deleteEmpById(int EMPno); } ``` ## 六、接口实现类(dao/impl包) 实现第五条所述的接口方法 ```java package com.doooog.test.dao.impl; import com.doooog.test.dao.EmpDao; import com.doooog.test.po.Emp; import com.doooog.test.util.CommonUtil; import com.doooog.test.util.DBUtil; import java.sql.*; import java.util.ArrayList; import java.util.List; public class EmpDaoImpl implements EmpDao { private Connection con = null; private PreparedStatement pst = null; private ResultSet rs = null; @Override public List selectEmpAll() { List list = new ArrayList<>(); String sql = "select * from emp order by empno"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); rs = pst.executeQuery(); while (rs.next()) { Emp tmp = new Emp(rs.getInt("EMPno"), rs.getString("ename"), rs.getString("job"), rs.getInt("mgr"), rs.getString("hiredate"), rs.getDouble("sal"), rs.getDouble("comm"), rs.getInt("DEPTno")); list.add(tmp); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, rs); } return list; } @Override public Emp selectEmpById(Integer id) { if (id == null) return null; Emp emp = null; String sql = "select * from emp where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); pst.setInt(1, id); rs = pst.executeQuery(); while (rs.next()) { emp = new Emp(rs.getInt("EMPno"), rs.getString("ename"), rs.getString("job"), rs.getInt("mgr"), rs.getString("hiredate"), rs.getDouble("sal"), rs.getDouble("comm"), rs.getInt("DEPTno")); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, rs); } return emp; } @Override public int insertEmp(Emp emp) { int result = 0; if (emp == null) return 0; String sql = "insert into emp values(null,?,?,?,?,?,?,?)"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); if (!(emp.getEname() == null)) pst.setString(1, emp.getEname()); else pst.setNull(1, Types.VARCHAR); if (!(emp.getJob() == null)) pst.setString(2, emp.getJob()); else pst.setNull(2, Types.VARCHAR); if (!(emp.getMgr() == null)) pst.setInt(3, emp.getMgr()); else pst.setNull(3, Types.INTEGER); pst.setString(4, CommonUtil.getNewDate()); if (!(emp.getSal() == null)) pst.setDouble(5, emp.getSal()); else pst.setNull(5, Types.DECIMAL); if (!(emp.getComm() == null)) pst.setDouble(6, emp.getComm()); else pst.setNull(6, Types.DECIMAL); if (!(emp.getDEPTno() == null)) pst.setInt(7, emp.getDEPTno()); else pst.setNull(7, Types.INTEGER); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int insertEmp(String ename, String job, Integer mgr, Double sal, Double comm, Integer DEPTno) { int result = 0; if (ename == null) return 0; String sql = "insert into emp values(null,?,?,?,?,?,?,?)"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); pst.setString(1, ename); if (!(job == null)) pst.setString(2, job); else pst.setNull(2, Types.VARCHAR); if (!(mgr == null)) pst.setInt(3, mgr); else pst.setNull(3, Types.INTEGER); pst.setString(4, CommonUtil.getNewDate()); if (!(sal == null)) pst.setDouble(5, sal); else pst.setNull(5, Types.DECIMAL); if (!(comm == null)) pst.setDouble(6, comm); else pst.setNull(6, Types.DECIMAL); if (!(DEPTno == null)) pst.setInt(7, DEPTno); else pst.setNull(7, Types.INTEGER); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateEname(int EMPno, String ename) { if (ename == null) return 0; int result = 0; String sql = "update emp set ename=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); pst.setString(1, ename); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateJob(int EMPno, String job) { if (job == null) return 0; int result = 0; String sql = "update emp set job=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); pst.setString(1, job); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateMgr(int EMPno, Integer mgr) { int result = 0; String sql = "update emp set mgr=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); if (!(mgr == null)) pst.setInt(1, mgr); else pst.setNull(1, Types.INTEGER); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateHireDate(int EMPno, String hireDate) { int result = 0; String sql = "update emp set hiredate=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); if (!(hireDate == null)) pst.setString(1, hireDate); else pst.setNull(1, Types.DATE); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateSal(int EMPno, Double sal) { int result = 0; String sql = "update emp set sal=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); if (!(sal == null)) pst.setDouble(1, sal); else pst.setNull(1, Types.DECIMAL); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateComm(int EMPno, Double comm) { int result = 0; String sql = "update emp set comm=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); if (!(comm == null)) pst.setDouble(1, comm); else pst.setNull(1, Types.DECIMAL); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateDEPTno(int EMPno, Integer DEPTno) { int result = 0; String sql = "update emp set DEPTno=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); if (!(DEPTno == null)) pst.setInt(1, DEPTno); else pst.setNull(1, Types.INTEGER); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int deleteEmpById(int EMPno) { int result = 0; String sql = "delete from emp where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); pst.setInt(1, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } } ``` ## 七、事务回滚 在MySQL中一个事务包含许多小步骤,要么全部成功,要么全部失败,以保证数据的同步和正确性,在Java中若要提交事务,须设置不自动提交,以转账事务为例: ```java public int transfer(int transferorId, int transferredId, double money) { int result = 1; String sql1 = "update emp set sal=sal-? where EMPno=?"; String sql2 = "update emp set sal=sal+? where EMPno=?"; try { con = DBUtil.getConnection(); // 1、设置为手动提交(新建一个事务) con.setAutoCommit(false); // 步骤一 pst = con.prepareStatement(sql1); pst.setDouble(1, money); pst.setInt(2, transferorId); pst.executeUpdate(); // 步骤二 pst = con.prepareStatement(sql2); pst.setDouble(1, money); pst.setInt(2, transferredId); pst.executeUpdate(); // 2、提交事务 con.commit(); } catch (Exception e) { // 3、回滚事务 result = 0; try { con.rollback(); } catch (SQLException ex) { throw new RuntimeException(ex); } System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } ``` ## 八、DAO层在现代开发中的演进 虽然DAO的概念依然重要,但其实现方式随着技术的发展而演变: 1、**ORM框架的普及**:现在很少直接使用原生JDBC来实现DAO。像 **MyBatis**、**Hibernate**(JPA规范)这样的ORM框架极大地简化了DAO层的开发。 * **JPA (Hibernate)**: 你可以直接创建一个接口继承 `JpaRepository`,框架会自动为你实现基本的CRUD方法,连实现类都不用写。 ```java // Spring Data JPA 风格的DAO,甚至不需要实现类 public interface UserRepository extends JpaRepository { // 根据方法名自动生成查询,如根据用户名查找 User findByUsername(String username); } ``` * **MyBatis**: 你只需要编写接口和对应的SQL映射文件(XML),MyBatis会通过动态代理自动创建接口的实现。 2、**名称的演变**:虽然职责相同,但在Spring Data等框架中,DAO层通常被称为 **Repository**(仓库)层。这两个术语在大多数上下文中可以视为同义词,但Repository的概念可能更广泛一些。 Loading... ## 一、什么是DAO层 DAO层是数据管理层,用来进行与数据库的数据交互,实现数据持久存储,全称为Data Access Object。 DAO层的文件结构: ```plaintext 📁com.域名.项目名/ ├── 📁dao/ 数据管理层 │ ├── 📁impl/ 接口实现类包 │ │ └── ☕️表名DaoImpl.java 接口实现类 │ └── ☕️表名Dao.java 接口 ├── 📁po/ 持久化对象包 │ └── ☕️表对象实例化.java 持久化对象 └── 📁util/ 工具类包 ├── ☕️CommonUtil.java 通用工具类 └── ☕️DBUtil.java 数据库工具类 ``` ## 二、数据库工具类(util包) 该类主要作用为数据库连接、断开等,大多数为静态方法 ```java package com.doooog.test.util; import java.sql.*; public class DBUtil { private static final String URL = "jdbc:mysql://localhost:3306/mysqlDbName?characterEncoding=utf-8"; private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String USERNAME = "root"; private static final String PASSWORD = "password"; // 获取Connection数据库连接 public static Connection getConnection() { Connection con = null; try { Class.forName(DRIVER); con = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (ClassNotFoundException | SQLException e) { System.out.println(e.getMessage()); } return con; } // 关闭连接 public static void closeRes(Connection con, PreparedStatement pst,ResultSet rs ) { try { if (rs != null) rs.close(); if (pst != null) pst.close(); if (con != null) con.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } } ``` ## 三、通用工具类(util包) 该类主要作用为获取一些通用的数据,比如时间戳、设备信息等,大多为静态方法 ```java package com.doooog.test.util; import java.text.SimpleDateFormat; import java.util.Date; public class CommonUtil { // 获取系统日期 public static String getNewDate() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(new Date()); } } ``` ## 四、表对象实例化类(po包) 该类作用为将表项数据转换为对象数据存储到内存,以便于后续面向对象编程。 ```java package com.doooog.test.po; public class Emp { private Integer EMPno; private String ename; private String job; private Integer mgr; private String hiredate; private Double sal; private Double comm; private Integer DEPTno; public Emp() { } public Emp(Integer EMPno, String ename, String job, Integer mgr, String hiredate, Double sal, Double comm, Integer DEPTno) { this.EMPno = EMPno; this.ename = ename; this.job = job; this.mgr = mgr; this.hiredate = hiredate; this.sal = sal; this.comm = comm; this.DEPTno = DEPTno; } public Integer getDEPTno() { return DEPTno; } public void setDEPTno(Integer DEPTno) { this.DEPTno = DEPTno; } public Double getComm() { return comm; } public void setComm(Double comm) { this.comm = comm; } public Double getSal() { return sal; } public void setSal(Double sal) { this.sal = sal; } public String getHiredate() { return hiredate; } public void setHiredate(String hiredate) { this.hiredate = hiredate; } public Integer getMgr() { return mgr; } public void setMgr(Integer mgr) { this.mgr = mgr; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public Integer getEMPno() { return EMPno; } public void setEMPno(Integer EMPno) { this.EMPno = EMPno; } @Override public String toString() { return "Emp{" + "EMPno=" + EMPno + ", ename='" + ename + '\'' + ", job='" + job + '\'' + ", mgr='" + mgr + '\'' + ", hiredate='" + hiredate + '\'' + ", sal=" + sal + ", comm=" + comm + ", DEPTno=" + DEPTno + '}'; } } ``` ## 五、表数据操作接口(dao包) 该类接口主要定义需要实现操作的方法,比如查询、增删改等 ```java package com.doooog.test.dao; import com.doooog.test.po.Emp; import java.util.List; public interface EmpDao { List<Emp> selectEmpAll(); Emp selectEmpById(Integer id); int insertEmp(Emp emp); int insertEmp(String ename, String job, Integer mgr, Double sal, Double comm, Integer DEPTno); int updateEname(int EMPno, String ename); int updateJob(int EMPno, String job); int updateMgr(int EMPno, Integer mgr); int updateHireDate(int EMPno, String hireDate); int updateSal(int EMPno, Double sal); int updateComm(int EMPno, Double comm); int updateDEPTno(int EMPno, Integer DEPTno); int deleteEmpById(int EMPno); } ``` ## 六、接口实现类(dao/impl包) 实现第五条所述的接口方法 ```java package com.doooog.test.dao.impl; import com.doooog.test.dao.EmpDao; import com.doooog.test.po.Emp; import com.doooog.test.util.CommonUtil; import com.doooog.test.util.DBUtil; import java.sql.*; import java.util.ArrayList; import java.util.List; public class EmpDaoImpl implements EmpDao { private Connection con = null; private PreparedStatement pst = null; private ResultSet rs = null; @Override public List<Emp> selectEmpAll() { List<Emp> list = new ArrayList<>(); String sql = "select * from emp order by empno"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); rs = pst.executeQuery(); while (rs.next()) { Emp tmp = new Emp(rs.getInt("EMPno"), rs.getString("ename"), rs.getString("job"), rs.getInt("mgr"), rs.getString("hiredate"), rs.getDouble("sal"), rs.getDouble("comm"), rs.getInt("DEPTno")); list.add(tmp); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, rs); } return list; } @Override public Emp selectEmpById(Integer id) { if (id == null) return null; Emp emp = null; String sql = "select * from emp where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); pst.setInt(1, id); rs = pst.executeQuery(); while (rs.next()) { emp = new Emp(rs.getInt("EMPno"), rs.getString("ename"), rs.getString("job"), rs.getInt("mgr"), rs.getString("hiredate"), rs.getDouble("sal"), rs.getDouble("comm"), rs.getInt("DEPTno")); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, rs); } return emp; } @Override public int insertEmp(Emp emp) { int result = 0; if (emp == null) return 0; String sql = "insert into emp values(null,?,?,?,?,?,?,?)"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); if (!(emp.getEname() == null)) pst.setString(1, emp.getEname()); else pst.setNull(1, Types.VARCHAR); if (!(emp.getJob() == null)) pst.setString(2, emp.getJob()); else pst.setNull(2, Types.VARCHAR); if (!(emp.getMgr() == null)) pst.setInt(3, emp.getMgr()); else pst.setNull(3, Types.INTEGER); pst.setString(4, CommonUtil.getNewDate()); if (!(emp.getSal() == null)) pst.setDouble(5, emp.getSal()); else pst.setNull(5, Types.DECIMAL); if (!(emp.getComm() == null)) pst.setDouble(6, emp.getComm()); else pst.setNull(6, Types.DECIMAL); if (!(emp.getDEPTno() == null)) pst.setInt(7, emp.getDEPTno()); else pst.setNull(7, Types.INTEGER); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int insertEmp(String ename, String job, Integer mgr, Double sal, Double comm, Integer DEPTno) { int result = 0; if (ename == null) return 0; String sql = "insert into emp values(null,?,?,?,?,?,?,?)"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); pst.setString(1, ename); if (!(job == null)) pst.setString(2, job); else pst.setNull(2, Types.VARCHAR); if (!(mgr == null)) pst.setInt(3, mgr); else pst.setNull(3, Types.INTEGER); pst.setString(4, CommonUtil.getNewDate()); if (!(sal == null)) pst.setDouble(5, sal); else pst.setNull(5, Types.DECIMAL); if (!(comm == null)) pst.setDouble(6, comm); else pst.setNull(6, Types.DECIMAL); if (!(DEPTno == null)) pst.setInt(7, DEPTno); else pst.setNull(7, Types.INTEGER); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateEname(int EMPno, String ename) { if (ename == null) return 0; int result = 0; String sql = "update emp set ename=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); pst.setString(1, ename); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateJob(int EMPno, String job) { if (job == null) return 0; int result = 0; String sql = "update emp set job=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); pst.setString(1, job); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateMgr(int EMPno, Integer mgr) { int result = 0; String sql = "update emp set mgr=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); if (!(mgr == null)) pst.setInt(1, mgr); else pst.setNull(1, Types.INTEGER); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateHireDate(int EMPno, String hireDate) { int result = 0; String sql = "update emp set hiredate=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); if (!(hireDate == null)) pst.setString(1, hireDate); else pst.setNull(1, Types.DATE); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateSal(int EMPno, Double sal) { int result = 0; String sql = "update emp set sal=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); if (!(sal == null)) pst.setDouble(1, sal); else pst.setNull(1, Types.DECIMAL); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateComm(int EMPno, Double comm) { int result = 0; String sql = "update emp set comm=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); if (!(comm == null)) pst.setDouble(1, comm); else pst.setNull(1, Types.DECIMAL); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int updateDEPTno(int EMPno, Integer DEPTno) { int result = 0; String sql = "update emp set DEPTno=? where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); if (!(DEPTno == null)) pst.setInt(1, DEPTno); else pst.setNull(1, Types.INTEGER); pst.setInt(2, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } @Override public int deleteEmpById(int EMPno) { int result = 0; String sql = "delete from emp where EMPno=?"; try { con = DBUtil.getConnection(); pst = con.prepareStatement(sql); pst.setInt(1, EMPno); result = pst.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } } ``` ## 七、事务回滚 在MySQL中一个事务包含许多小步骤,要么全部成功,要么全部失败,以保证数据的同步和正确性,在Java中若要提交事务,须设置不自动提交,以转账事务为例: ```java public int transfer(int transferorId, int transferredId, double money) { int result = 1; String sql1 = "update emp set sal=sal-? where EMPno=?"; String sql2 = "update emp set sal=sal+? where EMPno=?"; try { con = DBUtil.getConnection(); // 1、设置为手动提交(新建一个事务) con.setAutoCommit(false); // 步骤一 pst = con.prepareStatement(sql1); pst.setDouble(1, money); pst.setInt(2, transferorId); pst.executeUpdate(); // 步骤二 pst = con.prepareStatement(sql2); pst.setDouble(1, money); pst.setInt(2, transferredId); pst.executeUpdate(); // 2、提交事务 con.commit(); } catch (Exception e) { // 3、回滚事务 result = 0; try { con.rollback(); } catch (SQLException ex) { throw new RuntimeException(ex); } System.out.println(e.getMessage()); } finally { DBUtil.closeRes(con, pst, null); } return result; } ``` ## 八、DAO层在现代开发中的演进 虽然DAO的概念依然重要,但其实现方式随着技术的发展而演变: 1、**ORM框架的普及**:现在很少直接使用原生JDBC来实现DAO。像 **MyBatis**、**Hibernate**(JPA规范)这样的ORM框架极大地简化了DAO层的开发。 * **JPA (Hibernate)**: 你可以直接创建一个接口继承 `JpaRepository`,框架会自动为你实现基本的CRUD方法,连实现类都不用写。 ```java // Spring Data JPA 风格的DAO,甚至不需要实现类 public interface UserRepository extends JpaRepository<User, Long> { // 根据方法名自动生成查询,如根据用户名查找 User findByUsername(String username); } ``` * **MyBatis**: 你只需要编写接口和对应的SQL映射文件(XML),MyBatis会通过动态代理自动创建接口的实现。 2、**名称的演变**:虽然职责相同,但在Spring Data等框架中,DAO层通常被称为 **Repository**(仓库)层。这两个术语在大多数上下文中可以视为同义词,但Repository的概念可能更广泛一些。 最后修改:2025 年 10 月 22 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 👆请简单粗暴地爱我。