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 ? "成功" : "失败");

      }

    }

相关推荐
Java探秘者12 分钟前
Maven下载、安装与环境配置详解:从零开始搭建高效Java开发环境
java·开发语言·数据库·spring boot·spring cloud·maven·idea
2301_7869643618 分钟前
3、练习常用的HBase Shell命令+HBase 常用的Java API 及应用实例
java·大数据·数据库·分布式·hbase
苹果醋322 分钟前
大模型实战--FastChat一行代码实现部署和各个组件详解
java·运维·spring boot·mysql·nginx
阿维的博客日记1 小时前
图文并茂解释水平分表,垂直分表,水平分库,垂直分库
数据库·分库分表
wrx繁星点点2 小时前
事务的四大特性(ACID)
java·开发语言·数据库
小小娥子3 小时前
Redis的基础认识与在ubuntu上的安装教程
java·数据库·redis·缓存
DieSnowK3 小时前
[Redis][集群][下]详细讲解
数据库·redis·分布式·缓存·集群·高可用·新手向
计算机学姐3 小时前
基于SpringBoot+Vue的高校运动会管理系统
java·vue.js·spring boot·后端·mysql·intellij-idea·mybatis
-XWB-3 小时前
【MySQL】数据目录迁移
数据库·mysql
老华带你飞3 小时前
公寓管理系统|SprinBoot+vue夕阳红公寓管理系统(源码+数据库+文档)
java·前端·javascript·数据库·vue.js·spring boot·课程设计