DAO 相关

概念

DAO:Data Access Object 访问数据信息的类和接口,包括了对数据的 CRUD(Create、Retrival、Update、Delete),而不包含任何业务相关的信息。有时也称作 BaseDAO。

作用:为了实现功能的模块化,更有利于代码的维护和升级。

使用

表结构

DAO使用


  1. package cn.parzulpan.jdbc.ch07.util;
  2. import com.alibaba.druid.pool.DruidDataSourceFactory;
  3. import org.apache.commons.dbutils.DbUtils;
  4. import javax.sql.DataSource;
  5. import java.io.InputStream;
  6. import java.sql.*;
  7. import java.text.ParseException;
  8. import java.text.SimpleDateFormat;
  9. import java.util.Properties;
  10. /**
  11. * @Author : parzulpan
  12. * @Time : 2020-12-02
  13. * @Desc : 操作数据库的工具类,最终版
  14. */
  15. public class JDBCUtils {
  16. private static DataSource dataSource = null;
  17. static {
  18. try {
  19. Properties properties = new Properties();
  20. InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
  21. properties.load(is);
  22. dataSource = DruidDataSourceFactory.createDataSource(properties);
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. /**
  28. * 获取数据库连接,使用 Druid 数据库连接池
  29. * @return 数据库连接
  30. */
  31. public static Connection getDruidConnection() throws SQLException {
  32. return dataSource.getConnection();
  33. }
  34. /**
  35. * 使用DbUtils,静默关闭数据库资源
  36. * @param connection 数据库连接
  37. * @param statement 声明
  38. * @param resultSet 结果集
  39. */
  40. public static void closeResourceQuietly(Connection connection, Statement statement, ResultSet resultSet) {
  41. DbUtils.closeQuietly(connection);
  42. DbUtils.closeQuietly(statement);
  43. DbUtils.closeQuietly(resultSet);
  44. }
  45. public static Date getSqlDate(String dateStr) {
  46. java.sql.Date date = null;
  47. try {
  48. java.util.Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
  49. date = new java.sql.Date(parse.getTime());
  50. } catch (ParseException e) {
  51. e.printStackTrace();
  52. }
  53. return date;
  54. }
  55. }

  1. package cn.parzulpan.jdbc.ch07.dao;
  2. import org.apache.commons.dbutils.QueryRunner;
  3. import org.apache.commons.dbutils.handlers.BeanHandler;
  4. import org.apache.commons.dbutils.handlers.BeanListHandler;
  5. import org.apache.commons.dbutils.handlers.ScalarHandler;
  6. import java.lang.reflect.ParameterizedType;
  7. import java.lang.reflect.Type;
  8. import java.sql.Connection;
  9. import java.sql.SQLException;
  10. import java.util.List;
  11. /**
  12. * @Author : parzulpan
  13. * @Time : 2020-12-01
  14. * @Desc : 对数据表的通用操作
  15. */
  16. public abstract class BaseDAO<T> {
  17. // 泛型的类型
  18. private Class<T> type;
  19. private QueryRunner queryRunner = new QueryRunner();
  20. // 获取 T 类对象,获取泛型的类型,泛型是在被子类继承时才确定的
  21. public BaseDAO() {
  22. // 获取子类的类型
  23. Class<? extends BaseDAO> clazz = this.getClass();
  24. // 获取父类的类型
  25. ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
  26. // 获取具体的泛型
  27. Type[] types = parameterizedType.getActualTypeArguments();
  28. this.type = (Class<T>)types[0];
  29. }
  30. /**
  31. * 通用的增删改操作
  32. * @param connection 数据库连接
  33. * @param sql sql 语句
  34. * @param args 参数
  35. * @return 更新的条数
  36. */
  37. public int update(Connection connection, String sql, Object ... args) {
  38. int update = 0;
  39. try {
  40. update = queryRunner.update(connection, sql, args);
  41. } catch (SQLException e) {
  42. e.printStackTrace();
  43. }
  44. return update;
  45. }
  46. /**
  47. * 通用的查询操作
  48. * @param connection 数据库连接
  49. * @param sql sql 语句
  50. * @param args 参数
  51. * @return 返回一个对象
  52. */
  53. public T getBean(Connection connection, String sql, Object ... args) {
  54. T t = null;
  55. BeanHandler<T> beanHandler = new BeanHandler<>(type);
  56. try {
  57. t = queryRunner.query(connection, sql, beanHandler, args);
  58. } catch (SQLException e) {
  59. e.printStackTrace();
  60. }
  61. return t;
  62. }
  63. /**
  64. * 通用的查询操作
  65. * @param connection 数据库连接
  66. * @param sql sql 语句
  67. * @param args 参数
  68. * @return 返回一个对象列表
  69. */
  70. public List<T> getBeanList(Connection connection, String sql, Object ... args) {
  71. List<T> list = null;
  72. BeanListHandler<T> beanListHandler = new BeanListHandler<>(type);
  73. try {
  74. list = queryRunner.query(connection, sql, beanListHandler, args);
  75. } catch (SQLException e) {
  76. e.printStackTrace();
  77. }
  78. return list;
  79. }
  80. /**
  81. * 查询特殊值,类似于最大的,最小的,平均的,总和,个数相关的操作
  82. * @param connection 数据库连接
  83. * @param sql sql 语句
  84. * @param args 参数
  85. * @return 特殊值
  86. */
  87. public Object getValue(Connection connection, String sql, Object ... args) {
  88. Object obj = null;
  89. ScalarHandler scalarHandler = new ScalarHandler();
  90. try {
  91. obj = queryRunner.query(connection, sql, scalarHandler, args);
  92. } catch (SQLException e) {
  93. e.printStackTrace();
  94. }
  95. return obj;
  96. }
  97. }

  1. package cn.parzulpan.jdbc.ch07.dao;
  2. import cn.parzulpan.jdbc.ch07.bean.Customer;
  3. import java.sql.Connection;
  4. import java.sql.Date;
  5. import java.util.List;
  6. /**
  7. * @Author : parzulpan
  8. * @Time : 2020-12-01
  9. * @Desc : 此接口用于规范 customers 表的常用操作
  10. */
  11. public interface CustomerDAO {
  12. /**
  13. * 将 customer 对象添加到数据库中
  14. * @param connection 数据库连接
  15. * @param customer customer 对象
  16. */
  17. void insert(Connection connection, Customer customer);
  18. /**
  19. * 用 customer 对象修改数据库对应的数据中
  20. * @param connection 数据库连接
  21. * @param customer customer 对象
  22. */
  23. void update(Connection connection, Customer customer);
  24. /**
  25. * 根据 Id 删除一条记录
  26. * @param connection 数据库连接
  27. * @param id
  28. */
  29. void deleteById(Connection connection, int id);
  30. /**
  31. * 根据 Id 查询一条记录
  32. * @param connection 数据库连接
  33. * @param id
  34. * @return
  35. */
  36. Customer getCustomerById(Connection connection, int id);
  37. /**
  38. * 查询多条记录
  39. * @param connection 数据库连接
  40. * @return
  41. */
  42. List<Customer> getCustomerList(Connection connection);
  43. /**
  44. * 查询记录条数
  45. * @param connection 数据库连接
  46. * @return
  47. */
  48. Long getCount(Connection connection);
  49. /**
  50. * 查询最大的生日记录
  51. * @param connection 数据库连接
  52. * @return
  53. */
  54. Date getMaxBirth(Connection connection);
  55. }

  1. package cn.parzulpan.jdbc.ch07.impl;
  2. import cn.parzulpan.jdbc.ch07.bean.Customer;
  3. import cn.parzulpan.jdbc.ch07.dao.BaseDAO;
  4. import cn.parzulpan.jdbc.ch07.dao.CustomerDAO;
  5. import java.sql.Connection;
  6. import java.sql.Date;
  7. import java.util.List;
  8. /**
  9. * @Author : parzulpan
  10. * @Time : 2020-12-01
  11. * @Desc :
  12. */
  13. public class CustomerDAOImpl extends BaseDAO<Customer> implements CustomerDAO {
  14. /**
  15. * 将 customer 对象添加到数据库中
  16. *
  17. * @param connection 数据库连接
  18. * @param customer customer 对象
  19. */
  20. @Override
  21. public void insert(Connection connection, Customer customer) {
  22. String sql = "insert into customers(name, email, birth)values(?,?,?)";
  23. update(connection, sql, customer.getName(), customer.getEmail(), customer.getBirth());
  24. }
  25. /**
  26. * 用 customer 对象修改数据库对应的数据中
  27. *
  28. * @param connection 数据库连接
  29. * @param customer customer 对象
  30. */
  31. @Override
  32. public void update(Connection connection, Customer customer) {
  33. String sql = "update customers set name = ?, email = ?, birth = ? where id = ?";
  34. update(connection, sql, customer.getName(), customer.getEmail(), customer.getBirth(), customer.getId());
  35. }
  36. /**
  37. * 根据 Id 删除一条记录
  38. *
  39. * @param connection 数据库连接
  40. * @param id
  41. */
  42. @Override
  43. public void deleteById(Connection connection, int id) {
  44. String sql = "delete from customers where id = ?";
  45. update(connection, sql, id);
  46. }
  47. /**
  48. * 根据 Id 查询一条记录
  49. *
  50. * @param connection 数据库连接
  51. * @param id
  52. * @return
  53. */
  54. public Customer getCustomerById(Connection connection, int id) {
  55. String sql = "select id, name, email, birth from customers where id = ?";
  56. return getBean(connection, sql, id);
  57. }
  58. /**
  59. * 查询多条记录
  60. *
  61. * @param connection 数据库连接
  62. * @return
  63. */
  64. @Override
  65. public List<Customer> getCustomerList(Connection connection) {
  66. String sql = "select id, name, email, birth from customers";
  67. return getBeanList(connection, sql);
  68. }
  69. /**
  70. * 查询记录条数
  71. *
  72. * @param connection 数据库连接
  73. * @return
  74. */
  75. @Override
  76. public Long getCount(Connection connection) {
  77. String sql = "select count(*) from customers";
  78. return (Long) getValue(connection, sql);
  79. }
  80. /**
  81. * 查询最大的生日记录
  82. *
  83. * @param connection 数据库连接
  84. * @return
  85. */
  86. @Override
  87. public Date getMaxBirth(Connection connection) {
  88. String sql = "select max(birth) from customers";
  89. return (Date) getValue(connection, sql);
  90. }
  91. }

  1. package cn.parzulpan.jdbc.ch07.junit;
  2. import cn.parzulpan.jdbc.ch07.bean.Customer;
  3. import cn.parzulpan.jdbc.ch07.impl.CustomerDAOImpl;
  4. import cn.parzulpan.jdbc.ch07.util.JDBCUtils;
  5. import org.junit.After;
  6. import org.junit.Before;
  7. import org.junit.Test;
  8. import java.sql.Connection;
  9. import java.sql.Date;
  10. import java.sql.SQLException;
  11. import java.util.List;
  12. import static org.junit.Assert.*;
  13. /**
  14. * @Author : parzulpan
  15. * @Time : 2020-12-02
  16. * @Desc :
  17. */
  18. public class CustomerDAOImplTest {
  19. @Before
  20. public void setUp() throws Exception {
  21. System.out.println("CustomerDAOImplTest Before");
  22. }
  23. @After
  24. public void tearDown() throws Exception {
  25. System.out.println("CustomerDAOImplTest Down");
  26. }
  27. private CustomerDAOImpl customerDAO = new CustomerDAOImpl();
  28. @Test
  29. public void insert() {
  30. Connection connection = null;
  31. try {
  32. connection = JDBCUtils.getDruidConnection();
  33. Customer customer = new Customer(30, "DAO", "dao@163.com", JDBCUtils.getSqlDate("1995-1-1"));
  34. customerDAO.insert(connection, customer);
  35. } catch (SQLException e) {
  36. e.printStackTrace();
  37. } finally {
  38. JDBCUtils.closeResourceQuietly(connection, null, null);
  39. }
  40. }
  41. @Test
  42. public void update() {
  43. Connection connection = null;
  44. try {
  45. connection = JDBCUtils.getDruidConnection();
  46. Customer customer = new Customer(24, "DAOUpdate", "dao@163.com", JDBCUtils.getSqlDate("1995-1-1"));
  47. customerDAO.update(connection, customer);
  48. } catch (SQLException e) {
  49. e.printStackTrace();
  50. } finally {
  51. JDBCUtils.closeResourceQuietly(connection, null, null);
  52. }
  53. }
  54. @Test
  55. public void deleteById() {
  56. Connection connection = null;
  57. try {
  58. connection = JDBCUtils.getDruidConnection();
  59. customerDAO.deleteById(connection, 23);
  60. } catch (SQLException e) {
  61. e.printStackTrace();
  62. } finally {
  63. JDBCUtils.closeResourceQuietly(connection, null, null);
  64. }
  65. }
  66. @Test
  67. public void getCustomerById() {
  68. Connection connection = null;
  69. try {
  70. connection = JDBCUtils.getDruidConnection();
  71. Customer customer = customerDAO.getCustomerById(connection, 10);
  72. System.out.println(customer);
  73. } catch (SQLException e) {
  74. e.printStackTrace();
  75. } finally {
  76. JDBCUtils.closeResourceQuietly(connection, null, null);
  77. }
  78. }
  79. @Test
  80. public void getCustomerList() {
  81. Connection connection = null;
  82. try {
  83. connection = JDBCUtils.getDruidConnection();
  84. List<Customer> customers = customerDAO.getCustomerList(connection);
  85. customers.forEach(System.out::println);
  86. } catch (SQLException e) {
  87. e.printStackTrace();
  88. } finally {
  89. JDBCUtils.closeResourceQuietly(connection, null, null);
  90. }
  91. }
  92. @Test
  93. public void getCount() {
  94. Connection connection = null;
  95. try {
  96. connection = JDBCUtils.getDruidConnection();
  97. Long count = customerDAO.getCount(connection);
  98. System.out.println(count);
  99. } catch (SQLException e) {
  100. e.printStackTrace();
  101. } finally {
  102. JDBCUtils.closeResourceQuietly(connection, null, null);
  103. }
  104. }
  105. @Test
  106. public void getMaxBirth() {
  107. Connection connection = null;
  108. try {
  109. connection = JDBCUtils.getDruidConnection();
  110. Date maxBirth = customerDAO.getMaxBirth(connection);
  111. System.out.println(maxBirth);
  112. } catch (SQLException e) {
  113. e.printStackTrace();
  114. } finally {
  115. JDBCUtils.closeResourceQuietly(connection, null, null);
  116. }
  117. }
  118. }

练习和总结

【JDBC核心】DAO 相关的更多相关文章

  1. Unit02: JDBC核心API

    Unit02: JDBC核心API db.properties 注意:如果使用连接池,可以在这个文件中增加对连接池的相关设置: 连接池参数,常用参数有: 初始连接数 最大连接数 最小连接数 每次增加的 ...

  2. 关于案例中核心dao的解释

    很多小伙伴不太理解核心dao,说这是干什么的,接下来我将一一为大家解答: 1.说到核心dao不得不说到单表操作,单表操作顾名思义是对单张数据库表的CRUD操作,实际情况中我们追求将表与表的关系映射到对 ...

  3. JDBC核心API

    JDBC核心API在java.sql.*和javax.sql.* 1.Driver接口:表示Java驱动程序接口,具体的数据库厂商要实现其此接口 connect(url.propertis):连接数据 ...

  4. [课本]JDBC课程6--使用JDBC的DAO模块化--完成数据库的增删查改_工具类JDBCTools四个(Preparedstatement)功能模块的敲定版

    (课本P273-任务九) /**DAO: Data Access Object * 为什么用: 实现功能的模块化,更有利于代码的维护和升级 * 是什么: 访问数据信息的类,包含对数据的CRUD(cre ...

  5. 关于mysql,需要掌握的基础(二):JDBC和DAO层

    ​ 目录 关于mysql,需要掌握的基础(二):JDBC和DAO层 1.了解jdbc是什么? 2.加载注册驱动:为什么Class.forName("com.mysql.jdbc.Driver ...

  6. Java 核心内容相关面试题【3】

    目录 面向对象编程(OOP) 常见的Java问题 Java线程 Java集合类 垃圾收集器 异常处理 Java小应用程序(Applet) Swing JDBC 远程方法调用(RMI) Servlet ...

  7. Jdbc与Dao和Javabean的区别

    JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口 ...

  8. JDBC、DAO

    JDBC是Java数据库连接技术的简称,提供连接各种常用数据库的能力 JDBC的工作原理 JDBC 驱动器由数据库厂商提供 1.在个人开发与测试中,可以使用JDBC-ODBC桥连方式 2.在生产型开发 ...

  9. JDBC中DAO事务函数模版

    DAO事物函数模版1: public void OrderFinsByPage(){ Connection conn = null; PreparedStatement pstmt = null; R ...

随机推荐

  1. Object.prototype.toString.call()和typeof()区别

    js中判断数据类型都知道用tyoeof(),但是他只能判断object,boolean,function,string,number,undefined还有symbol(es6新增)这几种初步类型,比 ...

  2. webstorm2020最新安装破解教程方法永久激活码

    现在webstorm的版本已经更新到2020.3了,还没有升级的小伙伴们赶紧升级啦,本文教大家如何安装webstorm2020.3版本并且破解,此方法亲测百分百可以永久激活webstorm2020.3 ...

  3. Codeforces Edu Round 64 A-D

    A. Inscribed Figures 分类讨论打表即可. PS:这道题翻译有歧义. 这样稍微翻转一下,就可以是\(7\)个交点呀...(大概是我没看英文题干导致的惨案) #include < ...

  4. basic english

    color/visual see look color dark light beautiful shade black blue brown clear gray green orange red ...

  5. git学习——git下载安装

    原文来至 一.集中式vs分布式 Linus一直痛恨的CVS及SVN都是集中式的版本控制系统,而Git是分布式版本控制系统,集中式和分布式版本控制系统有什么区别呢? 先说集中式版本控制系统,版本库是集中 ...

  6. js日期格式化-----总结

    1. // 对Date的扩展,将 Date 转化为指定格式的String // 月(M).日(d).小时(h).分(m).秒(s).季度(q) 可以用 1-2 个占位符, // 年(y)可以用 1-4 ...

  7. Git:git常用命令

    1.版本控制工具     一个可以管理和追踪软件代码的工具.     分类:       集中式版本控制工具:SVN       分布式版本控制工具:Git 2.Git 的概念:     工作区:就是 ...

  8. idea的下载与安装

    1.下载idea.到idea的官网选择你需要下载的,你最喜欢的版本https://www.jetbrains.com/idea/download/ 2.下载jdk.进入Oracle官网,鼠标指在Dow ...

  9. 想用selenium ,先了解html 基础知识(5)

    二.HTML语法---了解!1.HTML超文本标记语言,是网页设计使用的语言.2.从<html>开始,到</html>结束,里面包括head和body两个部分,我们测试人员关心 ...

  10. Flink问题1

    flink问题1 报错: More buffers requested available than totally available 查看源码: /** * This method makes s ...