1.3 JDBC的dao模式,初步了解dao模式,使用dao模式完成jdbc的增删改查(重点)

Dao模式

Dao模式:就是避免项目的逻辑代码和sql代码在一块书写,一个方法的工作量过于庞大,冗余代码还比较多:
逻辑代码和sql代码分离:Service业务逻辑层+Dao持久层

使用DAO模式进行项目开发主要有以下两个好处:
隔离了业务逻辑代码和数据访问代码,分工明确,降低耦合性,提高可重用性。 采用面向接口编程,提高了项目的可扩展性和可维护性。
一个典型的DAO模式主要有以下几部分组成:
1、DAO接口: 把对数据库的所有操作定义成抽象方法,可以提供多种实现。
2、DAO 实现类: 针对不同数据库给出DAO接口定义方法的具体实现。一般情况下一个表对应一个Dao的实现类,有关本表的增删改查都在本类中
3、实体类:用于存放与传输对象数据。没有不影响 (回参:Map和List Student List)

项目代码:
1.3 JDBC的dao模式,初步了解dao模式,使用dao模式完成jdbc的增删改查(重点)_第1张图片
1.3 JDBC的dao模式,初步了解dao模式,使用dao模式完成jdbc的增删改查(重点)_第2张图片
IBookdao.java

package com.xh.jdbc.dao;


import com.xh.jdbc.entity.Book;

import java.util.List;
import java.util.Map;

public interface IBookdao {

    /**
     * @description: 增加
     *
     * @author  wangxihao
     * @email [email protected]
    **/
    int addbook(Book book);

    /**
     * @description: 删除
     * 
     * @author  wangxihao
     * @email [email protected]
    **/
    int delbook(int id);

    /**
     * @description: 更改
     * 
     * @author  wangxihao
     * @email [email protected]
    **/
    int updatebook(Book book);
    /**
     * @description: 查询
     * 
     * @author  wangxihao
     * @email [email protected]
    **/
    List<Map> selebook(int id);
    
}

IBookdaoimpl.java

package com.xh.jdbc.dao.impl;


import com.xh.jdbc.dao.IBookdao;
import com.xh.jdbc.entity.Book;
import com.xh.jdbc.util.JdbcUtil;

import java.util.List;
import java.util.Map;

public class IBookdaoimpl implements IBookdao {
    @Override
    public int addbook(Book book) {
        return JdbcUtil.Update("insert book(bookname,price) values(?,?)",book.getBookname(),book.getPrice());
    }

    @Override
    public int delbook(int id) {
        return JdbcUtil.Update("delete from book where id = ?",id);
    }

    @Override
    public int updatebook(Book book) {
        return JdbcUtil.Update("update book set bookname=?,price = ? where id = ?",book.getBookname(),book.getPrice(),book.getId());
    }

    @Override
    public List<Map> selebook(int id) {
        return JdbcUtil.select("select * from book");
    }
}

Book.java

package com.xh.jdbc.entity;


public class Book {
    private Integer id;
    private String bookname;
    private Integer price;

    public Book() {
    }

    public Book(Integer id, String bookname, Integer price) {
        this.id = id;
        this.bookname = bookname;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", bookname='" + bookname + '\'' +
                ", price=" + price +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getBookname() {
        return bookname;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }
}

Test01.java

package com.xh.jdbc.Test01;


import com.xh.jdbc.dao.impl.IBookdaoimpl;
import com.xh.jdbc.entity.Book;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Test01 {
    public void add(){
        //增加数据
        IBookdaoimpl iBookdaoimpl = new IBookdaoimpl();
        System.out.println("受影响行数"+iBookdaoimpl.addbook(new Book(1,"格林童话",20)));
    }

    public void del(){
        //删除数据
        IBookdaoimpl iBookdaoimpl = new IBookdaoimpl();
        int id = 2;
        System.out.println("受影响行数"+iBookdaoimpl.delbook(id));
    }

    public void upd(){
        //更改数据
        IBookdaoimpl iBookdaoimpl = new IBookdaoimpl();
        System.out.println(iBookdaoimpl.updatebook(new Book(2, "传奇", 60)));
    }
    public List<Book> sel(){
        //查询数据
        int id = 1;
        IBookdaoimpl iBookdaoimpl = new IBookdaoimpl();
        List<Map> selebook = iBookdaoimpl.selebook(id);
        List<Book> books = new ArrayList<>();
        for (Map map : selebook) {
            Book book = new Book();
            Integer id1 = (Integer) map.get("id");
            String bookname = (String) map.get("bookname");
            Integer price = (Integer) map.get("price");
            book.setId(id);
            book.setBookname(bookname);
            book.setPrice(price);
            books.add(book);
        }
        return books;
    }

    public static void main(String[] args){
        Test01 test01 = new Test01();
        System.out.println(test01.sel());


    }
}

JdbcUtil.java

package com.xh.jdbc.util;


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

public class JdbcUtil {

    /**
     * @description: 加载驱动
     *
     * @author  wangxihao
     * @email [email protected]
    **/
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("驱动加载异常");
        }
    }

    /**
     * @description: 获取连接
     *
     * @author  wangxihao
     * @email [email protected]
    **/
    public  static Connection conn(){
        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/casemanage?useUnicode=true&characterEncoding=utf-8&useSSL=false", "root", "1214521");
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接异常");
        }
        return null;
    }
    /**
     * @description: 设置参数
     *
     * @author  wangxihao
     * @email [email protected]
    **/
    public static void setParam(PreparedStatement preparedStatement,Object...ac){
        if(ac != null){
            for (int i = 0; i <ac.length ; i++) {
                try {
                    preparedStatement.setObject(i+1,ac[i]);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return;
    }
    /**
     * @description: 关闭连接
     *
     * @author  wangxihao
     * @email [email protected]
    **/
    public static void close(PreparedStatement preparedStatement1,Connection conn1, ResultSet resultSet1){

        try {
            if(preparedStatement1 != null){
                preparedStatement1.close();
            }
            if(conn1 != null){
                conn1.close();
            }
            if(resultSet1 != null){
                resultSet1.close();
            }

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



    public static int Update(String sql,Object... ac){
        Connection conn = null;
        PreparedStatement prepared = null;
        int j = 0;
        try {
            //获得连接
            conn = conn();
            prepared = conn.prepareStatement(sql);
            //参数赋值
            setParam(prepared,ac);
            j = prepared.executeUpdate();
        }catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(prepared,conn,null);
        }
        return j;
    }


    public static List<Map> select(String sql, Object...ac){
        List<Map> objects = new ArrayList<>();
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        try {
            conn = conn();
            preparedStatement = conn.prepareStatement(sql);
            setParam(preparedStatement,ac);
            ResultSet resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            while (resultSet.next()){
                TreeMap<String, Object> map = new TreeMap<>();

                for (int i = 1; i <= columnCount; i++) {
                    String columnLabel = metaData.getColumnLabel(i);
                    map.put(columnLabel,resultSet.getObject(i));
                }
                objects.add(map);
            }
            close(preparedStatement,conn,resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return objects;
    }

    public static void main(String[] args){

//        Object[] a = new Object[]{3};
//        FZjdbc01.update("insert sc value(2009,25,?)",a);
//        System.out.println("受影响的行数"+update);


        Object[] objects = {2001};
        System.out.println(JdbcUtil.select("select * from sc where s_no = ?", objects));


    }
}

简单说就是使用服务层代码去调底层数据库代码,实现了对代码的封装。

你可能感兴趣的:(java基础(前后端),java,开发语言,后端,数据库)