DAO设计模式

时间:2020-05-22
本文章向大家介绍DAO设计模式,主要包括DAO设计模式使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

DAO设计模式

  • DAO是数据访问对象(Data Access Object)的简写。
  • 建立在数据库与业务层之间,封装所有对数据库的访问操作,我们也可称之为持久层。
  • 目的: 将数据访问逻辑和业务逻辑分开。
  1. 主要就是封装与数据库交互的所有的方法和类型
    2. 目的是降低耦合性,将数据业务逻辑和访问逻辑分开。

    设计内容包含以下部分:

    • 一个实体类(通过ORM关系来设计的)
      • 表结构与类结构对应
      • 表字段与类属性对应
      • 表记录和类的实例对应
    • 一个接口:提供所有的与数据库交互的抽象方法,如增删改查等
    • 一个接口的实现类

    案例:为访问emp和dept表设计一个DAO模式
    1. 提供实体类Employee、Dept类型
    2. 提供一个接口:EmployeeDAO、DeptDAO
    3. 提供一个接口的实现类:EmployeeDAOImpl、DeptDAOImpl
    目录结构

Dept和Employee

package DAO.entity;

import java.util.Objects;

/**
 * @Author 昊
 * @Create 2020/5/21 23:37
 * @Description
 */
public class Dept {
    private int deptno;
    private String dname;
    private String loc;
    public Dept(){}
    public Dept(int deptno, String dname, String loc) {
        this.deptno = deptno;
        this.dname = dname;
        this.loc = loc;
    }

    public int getDeptno() {
        return deptno;
    }

    public void setDeptno(int deptno) {
        this.deptno = deptno;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Dept dept = (Dept) o;
        return deptno == dept.deptno &&
                Objects.equals(dname, dept.dname) &&
                Objects.equals(loc, dept.loc);
    }

    @Override
    public int hashCode() {
        return Objects.hash(deptno, dname, loc);
    }

    @Override
    public String toString() {
        return "Dept{" +
                "deptno=" + deptno +
                ", dname='" + dname + '\'' +
                ", loc='" + loc + '\'' +
                '}';
    }
}

package DAO.entity;

import java.sql.Date;
import java.util.Objects;

/**
 * @Author 昊
 * @Create 2020/5/21 21:44
 * @Description
 */
public class Employee {
    private int empno;
    private String ename;
    private String job;
    private int mgr;
    private Date hiredate;
    private double sal;
    private double comm;
    private int deptno;

    public Employee(){}

    public Employee(int empno, String ename, String job, int mgr, Date hiredate, double sal, double comm, int 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 int getEmpno() {
        return empno;
    }

    public void setEmpno(int empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public int getMgr() {
        return mgr;
    }

    public void setMgr(int mgr) {
        this.mgr = mgr;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }

    public double getComm() {
        return comm;
    }

    public void setComm(double comm) {
        this.comm = comm;
    }

    public int getDeptno() {
        return deptno;
    }

    public void setDeptno(int deptno) {
        this.deptno = deptno;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return empno == employee.empno &&
                mgr == employee.mgr &&
                Double.compare(employee.sal, sal) == 0 &&
                Double.compare(employee.comm, comm) == 0 &&
                deptno == employee.deptno &&
                Objects.equals(ename, employee.ename) &&
                Objects.equals(job, employee.job) &&
                Objects.equals(hiredate, employee.hiredate);
    }

    @Override
    public int hashCode() {
        return Objects.hash(empno, ename, job, mgr, hiredate, sal, comm, deptno);
    }

    @Override
    public String toString() {
        return "Employee{" +
                "empno=" + empno +
                ", ename='" + ename + '\'' +
                ", job='" + job + '\'' +
                ", mgr=" + mgr +
                ", hiredate=" + hiredate +
                ", sal=" + sal +
                ", comm=" + comm +
                ", deptno=" + deptno +
                '}';
    }
}

DeptDAO、EmployeeDAO、DeptDAOImpl、EmployeeDAOImpl

package DAO.impl;

import DAO.entity.Dept;
import DAO.entity.Employee;

import java.util.List;

/**
 * @Author 昊
 * @Create 2020/5/21 23:38
 * @Description
 */
public interface DeptDAO {
    public void addDept(Dept d);

    public void delDept(int id);

    public void modDept(Dept d);

    public Dept findById(int id);

    public List<Dept> findALl();

    public List<Dept> findByPage(int page,int pageSize);
}

package DAO.impl;

import DAO.entity.Dept;
import DAO.entity.Employee;
import DAO.util.DBUtil_c3p0;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 昊
 * @Create 2020/5/21 23:38
 * @Description
 */
public class DeptDAOImpl implements DeptDAO{
    final static String sqlAdd="insert into dept values(?,?,?)";
    final static String del="delete from dept where deptno=?";
    final static String findById="select * from dept where deptno=?";
    final static String mod="update dept set dname=?,loc=? where deptno=?";
    final static String findAll="select * from dept";
    final static String findByPage="select * from dept limit ?,?";


    @Override
    public void addDept(Dept d) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        try{
            connection= DBUtil_c3p0.getConnection();
            preparedStatement=connection.prepareStatement(sqlAdd);
            preparedStatement.setInt(1,d.getDeptno());
            preparedStatement.setString(2,d.getDname());
            preparedStatement.setString(3,d.getLoc());
            preparedStatement.executeUpdate();

        }catch (Exception exception){
            exception.printStackTrace();
        }finally {
            DBUtil_c3p0.closeConnection(connection,preparedStatement,null);
        }
    }

    @Override
    public void delDept(int id) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try{
            connection=DBUtil_c3p0.getConnection();
            preparedStatement=connection.prepareStatement(del);
            preparedStatement.setInt(1,id);
            int i = preparedStatement.executeUpdate();
            System.out.println(i+"条受到影响");
        }catch (Exception exception){
            exception.printStackTrace();
        }finally {
            DBUtil_c3p0.closeConnection(connection,preparedStatement,resultSet);
        }
    }

    @Override
    public void modDept(Dept d) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        int deptno=d.getDeptno();
        Dept byId = findById(deptno);
        if(byId!=null){
            try{
                connection=DBUtil_c3p0.getConnection();
                preparedStatement=connection.prepareStatement(mod);
                preparedStatement.setInt(3,d.getDeptno());
                preparedStatement.setString(1,d.getDname());
                preparedStatement.setString(2,d.getLoc());

                int i = preparedStatement.executeUpdate();
                System.out.println(i+"受到影响");
            }catch (Exception exception){
                exception.printStackTrace();
            }finally {
                DBUtil_c3p0.closeConnection(connection,preparedStatement,resultSet);
            }
        }
    }

    @Override
    public Dept findById(int id) {
        Dept dept=null;
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try{
            connection= DBUtil_c3p0.getConnection();
            preparedStatement=connection.prepareStatement(findById);
            preparedStatement.setInt(1,id);
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                int deptno=resultSet.getInt(1);
                String dname=resultSet.getString(2);
                String loc=resultSet.getString(3);
                dept=new Dept(deptno,dname,loc);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil_c3p0.closeConnection(connection,preparedStatement,resultSet);
        }
        return dept;
    }

    @Override
    public List<Dept> findALl() {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        List<Dept> emps=new ArrayList<>();
        try{
            connection=DBUtil_c3p0.getConnection();
            preparedStatement=connection.prepareStatement(findAll);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                int empno = resultSet.getInt(1);
                Dept byId = findById(empno);
                emps.add(byId);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil_c3p0.closeConnection(connection,preparedStatement,resultSet);
        }
        return emps;
    }

    @Override
    public List<Dept> findByPage(int page, int pageSize) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        List<Dept>emps=new ArrayList<>();
        try{
            connection=DBUtil_c3p0.getConnection();
            preparedStatement=connection.prepareStatement(findByPage);
            preparedStatement.setInt(1,page-1);
            preparedStatement.setInt(2,pageSize);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                int empno=resultSet.getInt("deptno");
                Dept byId = findById(empno);
                emps.add(byId);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil_c3p0.closeConnection(connection,preparedStatement,resultSet);
        }
        return emps;
    }
}
package DAO.impl;

import com.sun.java.accessibility.util.EventQueueMonitor;
import DAO.entity.Employee;

import java.awt.desktop.ScreenSleepListener;
import java.util.List;

/**
 * @Author 昊
 * @Create 2020/5/21 21:47
 * @Description
 */
public interface EmployeeDAO {
    public void addEmp(Employee e);

    public void delEmp(int id);

    public void modEmp(Employee e);

    public Employee findById(int id);

    public List<Employee> findALl();

    public List<Employee> findByPage(int page,int pageSize);
}

package DAO.impl;


import DAO.entity.Employee;
import DAO.util.DBUtil_c3p0;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 昊
 * @Create 2020/5/21 21:46
 * @Description
 */
public class EmployeeDAOImpl implements EmployeeDAO {
    final static String sqlAdd="insert into emp values(?,?,?,?,?,?,?,?)";
    final static String del="delete from emp where empno=?";
    final static String findById="select * from emp where empno=?";
    final static String mod="update emp set ename=?,job=?,mgr=?,hiredate=?,sal=?,comm=?,deptno=? where empno=?";
    final static String findAll="select * from emp";
    final static String findByPage="select * from emp limit ?,?";
    @Override
    public void addEmp(Employee e) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        try{
            connection= DBUtil_c3p0.getConnection();
            preparedStatement=connection.prepareStatement(sqlAdd);
            preparedStatement.setInt(1,e.getEmpno());
            preparedStatement.setString(2,e.getEname());
            preparedStatement.setString(3,e.getJob());
            preparedStatement.setInt(4,e.getMgr());
            preparedStatement.setDate(5,e.getHiredate());
            preparedStatement.setDouble(6,e.getSal());
            preparedStatement.setDouble(7,e.getComm());
            preparedStatement.setInt(8,e.getDeptno());
            preparedStatement.executeUpdate();

        }catch (Exception exception){
            exception.printStackTrace();
        }finally {
            DBUtil_c3p0.closeConnection(connection,preparedStatement,null);
        }
    }

    @Override
    public void delEmp(int id) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try{
            connection=DBUtil_c3p0.getConnection();
            preparedStatement=connection.prepareStatement(del);
            preparedStatement.setInt(1,id);
            int i = preparedStatement.executeUpdate();
            System.out.println(i+"条受到影响");
        }catch (Exception exception){
            exception.printStackTrace();
        }finally {
            DBUtil_c3p0.closeConnection(connection,preparedStatement,resultSet);
        }
    }

    @Override
    public void modEmp(Employee e) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        int empno=e.getEmpno();
        Employee byId = findById(empno);
        if(byId!=null){
            try{
                connection=DBUtil_c3p0.getConnection();
                preparedStatement=connection.prepareStatement(mod);
                preparedStatement.setInt(8,e.getEmpno());
                preparedStatement.setString(1,e.getEname());
                preparedStatement.setString(2,e.getJob());
                preparedStatement.setInt(3,e.getMgr());
                preparedStatement.setDate(4,e.getHiredate());
                preparedStatement.setDouble(5,e.getSal());
                preparedStatement.setDouble(6,e.getComm());
                preparedStatement.setInt(7,e.getDeptno());
                int i = preparedStatement.executeUpdate();
                System.out.println(i+"受到影响");
            }catch (Exception exception){
                exception.printStackTrace();
            }finally {
                DBUtil_c3p0.closeConnection(connection,preparedStatement,resultSet);
            }
        }
    }

    @Override
    public Employee findById(int id) {
//        int empno = 0,deptno=0,mgr=0;
//        String ename=null;
//        String job=null;
//        Date hiredate=null;
//        double sal=0,comm=0;
        Employee emp=null;
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try{
            connection= DBUtil_c3p0.getConnection();
            preparedStatement=connection.prepareStatement(findById);
            preparedStatement.setInt(1,id);
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                int empno=resultSet.getInt(1);
                String ename=resultSet.getString(2);
                String job=resultSet.getString(3);
                int mgr=resultSet.getInt(4);
                Date hiredate=resultSet.getDate(5);
                double sal=resultSet.getDouble(6);
                double comm=resultSet.getDouble(7);
                int deptno=resultSet.getInt(8);
                emp=new Employee(empno,ename,job,mgr,hiredate,sal,comm,deptno);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil_c3p0.closeConnection(connection,preparedStatement,resultSet);
        }
        return emp;
    }

    @Override
    public List<Employee> findALl() {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        List<Employee> emps=new ArrayList<>();
        try{
            connection=DBUtil_c3p0.getConnection();
            preparedStatement=connection.prepareStatement(findAll);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                int empno = resultSet.getInt(1);
                Employee byId = findById(empno);
                emps.add(byId);
            }
            
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil_c3p0.closeConnection(connection,preparedStatement,resultSet);
        }
        return emps;
    }

    @Override
    public List<Employee> findByPage(int page, int pageSize) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        List<Employee>emps=new ArrayList<>();
        try{
            connection=DBUtil_c3p0.getConnection();
            preparedStatement=connection.prepareStatement(findByPage);
            preparedStatement.setInt(1,page-1);
            preparedStatement.setInt(2,pageSize);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                int empno=resultSet.getInt("empno");
                Employee byId = findById(empno);
                emps.add(byId);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil_c3p0.closeConnection(connection,preparedStatement,resultSet);
        }
        return emps;
    }
}

EmployeeService和DeptService

package DAO.service;

import DAO.entity.Dept;
import DAO.entity.Employee;
import DAO.impl.DeptDAO;
import DAO.impl.DeptDAOImpl;
import DAO.impl.EmployeeDAO;
import DAO.impl.EmployeeDAOImpl;
import org.junit.Test;

import java.sql.Date;
import java.util.List;

/**
 * @Author 昊
 * @Create 2020/5/21 23:39
 * @Description
 */
public class DeptService {
    @Test
    public void addEmp(){
        Dept e = new Dept(50,"昊思敏捷有限责任公司","北京");
        DeptDAO employeeDAO=new DeptDAOImpl();
        employeeDAO.addDept(e);

    }

    @Test
    public void findAll(){
        //模拟客户端点击一个查询所有员工的按钮,来到此处,调用DAO层的findAll方法
        DeptDAO dao = new DeptDAOImpl();
        List<Dept> all = dao.findALl();
        //打印所有员工的信息,假装是传输到客户端页面上
        for (Dept employee : all) {
            System.out.println(employee);
        }
    }
    @Test
    public void modEmp(){
        DeptDAO dao = new DeptDAOImpl();
        Dept e = new Dept(50,"昊思敏捷有限责任公司","北京");
        dao.modDept(e);
    }
    @Test
    public void delet(){
        DeptDAO dao = new DeptDAOImpl();
        dao.delDept(60);
    }

    @Test
    public void findByPage(){
        DeptDAO dao = new DeptDAOImpl();
        List<Dept> all = dao.findByPage(1,5);
        //打印所有员工的信息,假装是传输到客户端页面上
        for (Dept employee : all) {
            System.out.println(employee);
        }
    }

    @Test
    public void findById(){
        DeptDAO dao = new DeptDAOImpl();
        Dept byId = dao.findById(50);
        System.out.println(byId);
    }
}

package DAO.service;

import DAO.entity.Employee;
import DAO.impl.EmployeeDAO;
import DAO.impl.EmployeeDAOImpl;
import org.junit.Test;

import java.sql.Date;
import java.util.List;

/**
 * @Author 昊
 * @Create 2020/5/21 21:47
 * @Description
 */
public class EmployeeService {
    @Test
    public void addEmp(){
       //Employee e = new Employee(9000,"ironMan","science",7369, Date.valueOf("2020-5-21"),100000000.0,1000000.0,10);
       //Employee employee=new Employee(9100,"clark","reporter",7369,Date.valueOf("2020-10-10"),100000,100000,10);
        Employee e = new Employee(9001,"spiderMan","student",7369, Date.valueOf("2020-5-22"),1000000.0,500000.0,10);

        EmployeeDAO employeeDAO=new EmployeeDAOImpl();
        employeeDAO.addEmp(e);
       // employeeDAO.addEmp(employee);
    }

    @Test
    public void findAll(){
        //模拟客户端点击一个查询所有员工的按钮,来到此处,调用DAO层的findAll方法
        EmployeeDAO dao = new EmployeeDAOImpl();
        List<Employee> all = dao.findALl();
        //打印所有员工的信息,假装是传输到客户端页面上
        for (Employee employee : all) {
            System.out.println(employee);
        }
    }
    @Test
    public void modEmp(){
        EmployeeDAO dao = new EmployeeDAOImpl();
        Employee employee=new Employee(9100,"clark","reporter",7369,Date.valueOf("2020-10-10"),900000,900000,10);
        dao.modEmp(employee);
    }
    @Test
    public void delet(){
        EmployeeDAO dao = new EmployeeDAOImpl();
        dao.delEmp(9100);
    }

    @Test
    public void findByPage(){
        EmployeeDAO dao = new EmployeeDAOImpl();
        List<Employee> all = dao.findByPage(1,5);
        //打印所有员工的信息,假装是传输到客户端页面上
        for (Employee employee : all) {
            System.out.println(employee);
        }
    }

    @Test
    public void findById(){
        EmployeeDAO dao = new EmployeeDAOImpl();
        Employee byId = dao.findById(9100);
        System.out.println(byId);
    }
}

DBUtile_c3p0

package DAO.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @Author 昊
 * @Create 2020/5/21 20:37
 * @Description
 *
 * 相关jar包
 * c3p0-0.9.5-pre8.jar
 * mchange-commons-java-0.2.7.jar
 */
public class DBUtil_c3p0 {
    //传图一个src下的xml配置文件,
    //底层会涉及到io流的读取和相关属性的赋值
    private  static ComboPooledDataSource comboPooledDataSource=new ComboPooledDataSource("c3p0-config");

    //获取连接对
    public static Connection getConnection(){
        try{
        return comboPooledDataSource.getConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }

    public static void closeConnection(Connection conn, Statement stat, ResultSet rs){
        try{
            if(rs!=null){
                rs.close();
            }
            if(stat!=null){
                stat.close();
            }
            if(conn!=null){
                conn.close();//实际上是调用的子类对象的重写好的close方法,close方法的逻辑一定是把连接对象放到连接池对象的能存多个连接对象的属性中
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }



    //测试
    public static void main(String[] args) {
        Connection connection= DBUtil_c3p0.getConnection();
        System.out.println(connection);
        closeConnection(connection,null,null);
        System.out.println(comboPooledDataSource.getAcquireIncrement());
        System.out.println(comboPooledDataSource.getInitialPoolSize());
        System.out.println(comboPooledDataSource.getMaxPoolSize());
    }
}

原文地址:https://www.cnblogs.com/dch-21/p/12935197.html