利用元数据对Dao操作进行抽取

Dao操作通用的步骤:

1.写SQL语句

2.获取连接

3.创建stmt

4.执行sql

a)更新executeUpdate

b)查询executeQuery

5.关闭/异常

BaseDao抽取:

其中利用BeanUtils将属性拷贝到对象中,需要用到2个包commons-beanutils-1.8.3.jar点击打开链接 和 commons-logging-1.1.3.jar点击打开链接

父类BaseDao.java

  1. package com.cn.dao;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.ResultSetMetaData;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import org.apache.commons.beanutils.BeanUtils;
  9. import com.cn.util.JdbcUtil;
  10. /**
  11. * 通用的dao,自己写的所有的dao都继承此类
  12. * 此类定义2个通用 方法
  13. * 1.更新
  14. * 2.查询
  15. * @author liuzhiyong
  16. *
  17. */
  18. public class BaseDao {
  19. /**
  20. * 更新的通用的方法
  21. * @param sql 更新的SQL语句(update/insert/delete)
  22. * @param params SQL语句中占位符对应的值(如果没有占位符,则传入null)
  23. */
  24. public void update(String sql, Object[] params){
  25. Connection conn = null;
  26. PreparedStatement pstmt = null;
  27. try {
  28. //获取连接
  29. conn = JdbcUtil.getConnection();
  30. //创建执行命令的stmt对象
  31. pstmt = conn.prepareStatement(sql);
  32. //通过参数元数据,得到占位参数的个数
  33. int count = pstmt.getParameterMetaData().getParameterCount();
  34. //设置占位符参数的值
  35. if(params != null && params.length>0){
  36. //循环给参数赋值
  37. for(int i=0; i<count; i++){
  38. pstmt.setObject(i+1, params[i]);
  39. }
  40. }
  41. //执行更新
  42. pstmt.executeUpdate();
  43. } catch (Exception e) {
  44. throw new RuntimeException(e);
  45. }finally{
  46. JdbcUtil.close(conn, pstmt, null);
  47. }
  48. }
  49. public <T>List<T> query(String sql, Object[] params, Class<T> clazz){
  50. Connection conn = null;
  51. PreparedStatement pstmt = null;
  52. ResultSet rs = null;
  53. try {
  54. //创建List集合,存放数据库查询出来的数据
  55. List<T> list = new ArrayList<T>();
  56. //要封装的对象
  57. T t = null;
  58. //获取连接
  59. conn = JdbcUtil.getConnection();
  60. //创建执行命令的stmt对象
  61. pstmt = conn.prepareStatement(sql);
  62. //通过参数元数据,得到占位参数的个数
  63. int paramsCount = pstmt.getParameterMetaData().getParameterCount();
  64. //设置占位符参数的值
  65. if(params!=null && params.length>0){
  66. //循环给参数赋值
  67. for(int i=0; i<paramsCount; i++){
  68. pstmt.setObject(i+1, params[i]);
  69. }
  70. }
  71. //执行查询
  72. rs = pstmt.executeQuery();
  73. //获取结果集元数据
  74. ResultSetMetaData rsMeta = rs.getMetaData();
  75. //获取列的个数
  76. int columnCount = rsMeta.getColumnCount();
  77. //遍历结果集,迭代每一行
  78. while(rs.next()){
  79. //创建要封装的T对象
  80. t = clazz.newInstance();
  81. //遍历每一行的每一列
  82. for(int i=0; i<columnCount; i++){
  83. //获取每一列的名称
  84. String columnName = rsMeta.getColumnName(i+1);
  85. //获取该行对应列名称的值
  86. Object objectValue = rs.getObject(columnName);
  87. //利用BeanUtils将属性拷贝到对象中
  88. BeanUtils.copyProperty(t, columnName, objectValue);//注意日期类型的数据保存,需要注册日期类型注册前
  89. }
  90. //将封装完毕的t对象存入list集合中
  91. list.add(t);
  92. }
  93. return list;
  94. } catch (Exception e) {
  95. throw new RuntimeException(e);
  96. }finally{
  97. JdbcUtil.close(conn, pstmt, rs);
  98. }
  99. }
  100. }

子类继承BaseDao.java

  1. package com.cn.dao.impl;
  2. import java.util.List;
  3. import com.cn.dao.BaseDao;
  4. import com.cn.entity.User;
  5. public class UserDao extends BaseDao{
  6. /**
  7. * 删除
  8. * @param id
  9. */
  10. public void delete(int id){
  11. String sql = "delete from users where id = ?";
  12. Object[] params = {id};
  13. super.update(sql, params);//调用父类BaseDao中的方法
  14. }
  15. /**
  16. * 插入
  17. * @param user
  18. */
  19. public void save(User user){
  20. String sql = "insert into users(name, password) values(?, ?)";
  21. Object[] params = {user.getName(), user.getPassword()};
  22. super.update(sql, params);//调用父类BaseDao中的方法
  23. }
  24. /**
  25. *
  26. * @param user
  27. */
  28. public void update(User user){
  29. String sql = "update users set name=?, password=? where id=?";
  30. Object[] params = {user.getName(), user.getPassword(), user.getId()};
  31. super.update(sql, params);//调用父类BaseDao中的方法
  32. }
  33. /**
  34. * 查询所有
  35. * @param params
  36. * @return
  37. */
  38. public List<User> query(){
  39. String sql = "select * from users";
  40. List<User> list = super.query(sql, null, User.class);
  41. return list;
  42. }
  43. /**
  44. * 根据主键查询
  45. * @param id
  46. * @return
  47. */
  48. public User findById(int id){
  49. String sql = "select * from users where id = ?";
  50. List<User> list = super.query(sql, new Object[]{id}, User.class);
  51. return (list!=null&&list.size()>0)?list.get(0):null;
  52. }
  53. }

User.java

  1. package com.cn.entity;
  2. public class User {
  3. private int id;
  4. private String name;
  5. private String password;
  6. public int getId() {
  7. return id;
  8. }
  9. public void setId(int id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public String getPassword() {
  19. return password;
  20. }
  21. public void setPassword(String password) {
  22. this.password = password;
  23. }
  24. public User() {
  25. }
  26. @Override
  27. public String toString() {
  28. return "User [id=" + id + ", name=" + name + ", password=" + password
  29. + "]";
  30. }
  31. }

测试

  1. package com.cn.test;
  2. import java.util.List;
  3. import org.junit.Test;
  4. import com.cn.dao.impl.UserDao;
  5. import com.cn.entity.User;
  6. public class UserTest {
  7. UserDao dao = new UserDao();
  8. /**
  9. * 测试更新
  10. * @throws Exception
  11. */
  12. @Test
  13. public void testUpdate() throws Exception {
  14. /**
  15. * 删除
  16. */
  17. // dao.delete(4);
  18. /**
  19. * 保存
  20. */
  21. // dao.save(new User());
  22. // User user = new User();
  23. // user.setName("刘先森");
  24. // user.setPassword("666666");
  25. // dao.save(user);
  26. /**
  27. * 更新
  28. */
  29. User user2 = new User();
  30. user2.setId(8);
  31. user2.setName("mary");
  32. user2.setPassword("mary");
  33. dao.update(user2);
  34. }
  35. /**
  36. * 查询所有
  37. * @throws Exception
  38. */
  39. @Test
  40. public void testQuery() throws Exception {
  41. List<User> list = dao.query();
  42. for(User user : list){
  43. System.out.println(user.toString());
  44. }
  45. }
  46. /**
  47. * 根据id主键查询
  48. * @throws Exception
  49. */
  50. @Test
  51. public void testFindById() throws Exception {
  52. User user = dao.findById(3);
  53. System.out.println(user.toString());
  54. }
  55. }

BaseDao工具类相关推荐

  1. JDBC初学者的basedao工具类

    package com.obtk.util;import java.sql.Connection; import java.sql.DriverManager; import java.sql.Pre ...

  2. JAVA高效率 (秒级) 将千万条数据导入数据库 (已封装工具类)【详解】【一看就懂】

    该gif做了加速处理,便于观看~  今天在将一个500w+条数据的文件导入至数据库时,遇到一个异常,相信做大数据应该都有遇到.500w条数据说多不多,说少也不少.既然问题出现了,那么就一定要解决. 异 ...

  3. java druid jdbc例子_JDBC【使用Druid连接数据库,DBUtils工具类的使用】

    Druid连接数据库,DBUtils工具类的使用 1.在maven中添加Druid依赖 com.alibaba druid 1.2.0 2.封装Druid连接方法 import com.alibaba ...

  4. jdbc dao 工具类mysql_Java基于JDBC实现事务,银行转账及货物进出库功能示例

    本文实例讲述了Java基于JDBC实现事务,银行转账及货物进出库功能.分享给大家供大家参考,具体如下: 1. 转账业务 转账必须执行2个sql语句(update更新)都成功的情况下,提交事务,如果有一 ...

  5. dbutils java_Dbutils工具类的使用

    一.什么是Dbutils? Commons DbUtils是Apache组织提供的一个对JDBC进行简单封装的开源工具类库,使用它能够简化JDBC应用程序的开发,同时也不会影响程序的性能.来源百度百科 ...

  6. java list resultset_Java工具类 通过ResultSet对象返回对应的实体List集合

    自从学了JDBC用多了像一下这种代码: ResultSet rs = this.executeQuery(sql, objs); List list = new Array(); if(rs.next ...

  7. java中常用的工具类

    1. 常用零散工具类 1.1[DateUtil.java]日期处理的工具类 /*** 时间日期处理工具* String -> Date* Date -> String* 以及生成含有日期的 ...

  8. NC6 用户账号密码加密工具类

    RBAC用户密码工具类: package nc.vo.uap.rbac.util;import java.util.Collection; import java.util.regex.Matcher ...

  9. java日期转化工具类

    package com.rest.ful.utils;import java.text.DateFormat; import java.text.ParseException; import java ...

最新文章

  1. 计算机网络——IP地址与MAC地址
  2. 如何在ASP.NET Core中自定义Azure Storage File Provider
  3. POJ 1852 Ants 分析
  4. idea关闭当前项目
  5. 微信小程序轮播中的current_开源 | 微信接龙小程序 wechatsolita 开源
  6. mybatis--常见的错误
  7. ArcPad 10 的安装部署
  8. UnionID与OpenID的区别【转自微信官方文档】
  9. Gif 录制工具:Screen2Gif
  10. 企业研发人员配备比例_高新企业科技人员占比是什么要求
  11. andriod studio git
  12. 服务器修复oxc0000098,修复oxc0000098的方法
  13. 「数据结构 | 链表」单链表、双向链表节点操作演示动画
  14. 轻型货车悬架系统的设计(设计说明书+CAD图纸+开题报告+任务书+答辩相关材料)
  15. vue项目模拟后台数据
  16. linux中获取几天前或者几天后的日期
  17. 御坂坂的C++学习之路(3)-----函数-----stdarg.h
  18. Linux内核源码介绍
  19. 【C语言程序设计】从键盘上输入某年某月(包括闰年),编程输出该年的该月拥有的天数。
  20. 计算机工程本科旧金山找工,2020年旧金山大学本科热门专业

热门文章

  1. MySQL笔记(黑马一)
  2. 考试 mysql 数据库设计_基于MySQL的在线考试系统数据库设计
  3. 7N60-ASEMI高压MOS管7N60
  4. bbs jsp mysql_BBS 一个比较简单的用jsp+servlet+mysql做的bbs论坛 Jsp/ 265万源代码下载- www.pudn.com...
  5. 如何用OBS直播?关键的步骤能不能简化一下
  6. 前端自动化测试——百度搜索功能实战演示
  7. ------什么是作用域
  8. 手机射频电路中常见的射频电路
  9. 認識系統服務 daemons
  10. 临沂计算机公司排名2015,临沂有哪些大企业 临沂百强企业排名2015