BasicDAO

韩顺平 零基础30天学会Java

一、基本说明

1、DAO:data access object 数据访问对象
2、这样的通用类,称为BasicDao,是专门和数据库交互的,及万恒对数据库(表)的crud操作
3、在BasicDao基础上实现一张表,对应一个Dao,更好的完成功能

BasicDAO应用示例

完成一个简单的设计

com.hspedu.dao_
1、com.hspedu.dao_.utils //工具类
2、com.hspedu.dao_.domain //javaBean
3、com.hspedu.dao_.dao 存放XXXDAO和BasicDAO
4、com.hspedu.dao_.test 写测试类
在这里插入图片描述

  • 最终的文件结构

在这里插入图片描述

操作步骤

  • 首先在数据库中创建一张表 actor

在这里插入图片描述

  • 在com.hspedu.dao_.utils 包下创建 Druid.java 用于连接数据库
package com.hspedu.dao_.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.support.spring.stat.annotation.Stat;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author 易
 * @version 1.0
 */
public class Druid {
    //首先是变量
    private static DataSource ds;

    //使用静态代码块初始化
    static {
        //使用Proerties得到配置文件
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src/druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    //创建连接
    public static Connection getConection() throws SQLException {
        return ds.getConnection();
    }

    //关闭连接--resultset,statement,connection
    public static void close(ResultSet resultSet, Statement statement, Connection connection) throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

  • 在 com.hspedu.dao_.domain 包下创建 Actro.java
package com.hspedu.dao_.domain;

/**
 * @author 易
 * @version 1.0
 */
public class Actor {
    //属性
    private Integer id;
    private String name;
    private String sex;
    private String borndate;
    private String phon;

    //给一个无参构造,反射需要
    public Actor() {
    }

    //给定构造器
    public Actor(Integer id, String name, String sex, String borndate, String phon) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.borndate = borndate;
        this.phon = phon;
    }


    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getBorndate() {
        return borndate;
    }

    public void setBorndate(String borndate) {
        this.borndate = borndate;
    }

    public String getPhon() {
        return phon;
    }

    public void setPhon(String phon) {
        this.phon = phon;
    }

    @Override
    public String toString() {
        return "Actor{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", borndate='" + borndate + '\'' +
                ", phon='" + phon + '\'' +
                '}';
    }
}

  • 在 com.hspedu.dao_.dao 包下创建 BasicDAO.java 开发 DAO 的通用操作是其他 DAO 的父类
package com.hspedu.dao_.dao;

import com.hspedu.chapter25.utils.Druid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

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

/**
 * @author 易
 * @version 1.0
 * 开发BasicDAO,是其他DAO的父类
 */
public class BasicDAO<T> {
    //泛型指定具体的类型
    //首先创建一个QueryRunner
    private QueryRunner queryRunner = new QueryRunner();
    /* 增*/
    /* 删*/
    /* 改*/

    /**
     * @param sql        sql 语句
     * @param parameters 给占位符赋值
     * @return 返回受到影响的行数
     */
    public int update(String sql, Object... parameters) {

        Connection connection = null;
        try {
            //得到连接
            connection = Druid.getConnection();
            //执行sql
            int rows = queryRunner.update(connection, sql, parameters);
            return rows;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //关闭连接
            Druid.close(null, null, connection);
        }
    }
    /* 查*/
    //查询到多行

    /**
     * @param sql        sql语句,可以有?
     * @param cls        传入一个类的 Class 对象,例如 Actor.class
     * @param parameters 可变形参,传入?具体的值,可以是多个
     * @return 根据 Actor.class 返回对应的 ArrayList 集合
     */
    public List<T> selectMul(String sql, Class cls, Object... parameters) {

        Connection connection = null;
        try {
            //创建连接
            connection = Druid.getConnection();
            //执行sql
            List<T> list = queryRunner.query(connection, sql, new BeanListHandler<T>(cls), parameters);
            //返回结果
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭连接
            Druid.close(null, null, connection);
        }
    }
    //查询单行的方法

    /**
     * @param sql        sql 语句
     * @param cls        传入一个类的Class对象,例如 Actor.class
     * @param parameters 传入多个形参,给占位符赋值
     * @return 根据 Actor.class 返回单行数据
     */
    public T selectSingle(String sql, Class cls, Object... parameters) {
        Connection connection = null;
        try {
            //获得连接
            connection = Druid.getConnection();
            //执行sql
            T t = queryRunner.query(connection, sql, new BeanHandler<T>(cls), parameters);
            //返回结果
            return t;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭连接
            Druid.close(null, null, connection);
        }
    }
    //查询单行单列的方法

    /**
     * @param sql        sql 语句
     * @param parameters 多个形参,
     * @return 返回单值
     */
    public Object selectSacal(String sql, Object... parameters) {
        Connection connection = null;
        try {
            connection = Druid.getConnection();
            Object query = queryRunner.query(connection, sql, new ScalarHandler(), parameters);
            return query;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            Druid.close(null, null, connection);
        }
    }
}

  • 在 com.hspedu.dao_.dao 包下创建 ActorDAO.java 继承 BasicDAO
package com.hspedu.dao_.dao;

import com.hspedu.dao_.domain.Actor;

/**
 * @author 易
 * @version 1.0
 */
public class ActorDAO extends BasicDAO<Actor> {
    //1、有BasicDAO 的方法
    //2、歌剧业务需求可以编写自己的方法
}

  • 在 com.hspedu.dao_.test 包下创建 TestDAO.java 用于测试刚才开发的功能
package com.hspedu.dao_.test;

import com.hspedu.dao_.dao.ActorDAO;
import com.hspedu.dao_.domain.Actor;
import org.junit.Test;

import java.util.List;

/**
 * @author 易
 * @version 1.0
 */
public class TestDAO {
    //测试ActorDAO对actor表的crud操作
    @Test
    public void testActorDAO() {
        ActorDAO actorDAO = new ActorDAO();
        //查询多条结果
        List<Actor> actors = actorDAO.selectMul("select * from actor", Actor.class);
        //输出结果
        System.out.println("输出结果");
        for (Actor actor : actors) {
            System.out.println(actor);
        }
//
        //测试一个插入语句
        int update = actorDAO.update("insert into actor values(null,?,?,?,?)", "jerry", "男", "1898-09-07", "1110");
        System.out.println(update > 0 ? "成功" : "失败");


    }

}

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值