爆款云主机2核4G限时秒杀,88元/年起!
查看详情

活动

天翼云最新优惠活动,涵盖免费试用,产品折扣等,助您降本增效!
热门活动
  • 618智算钜惠季 爆款云主机2核4G限时秒杀,88元/年起!
  • 免费体验DeepSeek,上天翼云息壤 NEW 新老用户均可免费体验2500万Tokens,限时两周
  • 云上钜惠 HOT 爆款云主机全场特惠,更有万元锦鲤券等你来领!
  • 算力套餐 HOT 让算力触手可及
  • 天翼云脑AOne NEW 连接、保护、办公,All-in-One!
  • 中小企业应用上云专场 产品组合下单即享折上9折起,助力企业快速上云
  • 息壤高校钜惠活动 NEW 天翼云息壤杯高校AI大赛,数款产品享受线上订购超值特惠
  • 天翼云电脑专场 HOT 移动办公新选择,爆款4核8G畅享1年3.5折起,快来抢购!
  • 天翼云奖励推广计划 加入成为云推官,推荐新用户注册下单得现金奖励
免费活动
  • 免费试用中心 HOT 多款云产品免费试用,快来开启云上之旅
  • 天翼云用户体验官 NEW 您的洞察,重塑科技边界

智算服务

打造统一的产品能力,实现算网调度、训练推理、技术架构、资源管理一体化智算服务
智算云(DeepSeek专区)
科研助手
  • 算力商城
  • 应用商城
  • 开发机
  • 并行计算
算力互联调度平台
  • 应用市场
  • 算力市场
  • 算力调度推荐
一站式智算服务平台
  • 模型广场
  • 体验中心
  • 服务接入
智算一体机
  • 智算一体机
大模型
  • DeepSeek-R1-昇腾版(671B)
  • DeepSeek-R1-英伟达版(671B)
  • DeepSeek-V3-昇腾版(671B)
  • DeepSeek-R1-Distill-Llama-70B
  • DeepSeek-R1-Distill-Qwen-32B
  • Qwen2-72B-Instruct
  • StableDiffusion-V2.1
  • TeleChat-12B

应用商城

天翼云精选行业优秀合作伙伴及千余款商品,提供一站式云上应用服务
进入甄选商城进入云市场创新解决方案
办公协同
  • WPS云文档
  • 安全邮箱
  • EMM手机管家
  • 智能商业平台
财务管理
  • 工资条
  • 税务风控云
企业应用
  • 翼信息化运维服务
  • 翼视频云归档解决方案
工业能源
  • 智慧工厂_生产流程管理解决方案
  • 智慧工地
建站工具
  • SSL证书
  • 新域名服务
网络工具
  • 翼云加速
灾备迁移
  • 云管家2.0
  • 翼备份
资源管理
  • 全栈混合云敏捷版(软件)
  • 全栈混合云敏捷版(一体机)
行业应用
  • 翼电子教室
  • 翼智慧显示一体化解决方案

合作伙伴

天翼云携手合作伙伴,共创云上生态,合作共赢
天翼云生态合作中心
  • 天翼云生态合作中心
天翼云渠道合作伙伴
  • 天翼云代理渠道合作伙伴
天翼云服务合作伙伴
  • 天翼云集成商交付能力认证
天翼云应用合作伙伴
  • 天翼云云市场合作伙伴
  • 天翼云甄选商城合作伙伴
天翼云技术合作伙伴
  • 天翼云OpenAPI中心
  • 天翼云EasyCoding平台
天翼云培训认证
  • 天翼云学堂
  • 天翼云市场商学院
天翼云合作计划
  • 云汇计划
天翼云东升计划
  • 适配中心
  • 东升计划
  • 适配互认证

开发者

开发者相关功能入口汇聚
技术社区
  • 专栏文章
  • 互动问答
  • 技术视频
资源与工具
  • OpenAPI中心
开放能力
  • EasyCoding敏捷开发平台
培训与认证
  • 天翼云学堂
  • 天翼云认证
魔乐社区
  • 魔乐社区

支持与服务

为您提供全方位支持与服务,全流程技术保障,助您轻松上云,安全无忧
文档与工具
  • 文档中心
  • 新手上云
  • 自助服务
  • OpenAPI中心
定价
  • 价格计算器
  • 定价策略
基础服务
  • 售前咨询
  • 在线支持
  • 在线支持
  • 工单服务
  • 建议与反馈
  • 用户体验官
  • 服务保障
  • 客户公告
  • 会员中心
增值服务
  • 红心服务
  • 首保服务
  • 客户支持计划
  • 专家技术服务
  • 备案管家

了解天翼云

天翼云秉承央企使命,致力于成为数字经济主力军,投身科技强国伟大事业,为用户提供安全、普惠云服务
品牌介绍
  • 关于天翼云
  • 智算云
  • 天翼云4.0
  • 新闻资讯
  • 天翼云APP
基础设施
  • 全球基础设施
  • 信任中心
最佳实践
  • 精选案例
  • 超级探访
  • 云杂志
  • 分析师和白皮书
  • 天翼云·创新直播间
市场活动
  • 2025智能云生态大会
  • 2024智算云生态大会
  • 2023云生态大会
  • 2022云生态大会
  • 天翼云中国行
天翼云
  • 活动
  • 智算服务
  • 产品
  • 解决方案
  • 应用商城
  • 合作伙伴
  • 开发者
  • 支持与服务
  • 了解天翼云
      • 文档
      • 控制中心
      • 备案
      • 管理中心

      反射实例之封装对数据库的增删改查操作

      首页 知识中心 数据库 文章详情页

      反射实例之封装对数据库的增删改查操作

      2024-09-24 06:30:33 阅读次数:100

      MySQL,数据库

      需求

      使用反射来封装对MySQL数据库的增删改查操作,封装更通用的方法。

      代码实现

      第一步,创建数据库连接。

      设置数据库连接参数,获取Connection。注意,改成自己数据库的连接参数。

      /**
       * 获取数据库连接的工具类,注意在该类设置数据库连接参数
       */
      class JDBCUtil {
          /**
           * 获取数据库连接
           *
           * @return 数据库连接对象
           */
          public static Connection getConnection() {
              Connection connection = null;
              try {
                  Class.forName("com.mysql.jdbc.Driver");
                  String url = "jdbc:mysql://localhost/test";
                  String user = "root";
                  String password = "root";
                  connection = DriverManager.getConnection(url, user, password);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return connection;
          }
      }

      第二步,创建BaseMapper接口。

      该接口中定义了众多增删改查的默认方法。

      public interface BaseMapper<T> {
      
          // --------------------------------------插入操作------------------------------------------
      
          /**
           * 向数据库内插入一条记录。
           * 插入SQL语句如例:insert into user(id,username,password,phone,email,memo,insert_time) values(20,'刘三刀','123456','1008611','1008611@','我是一名用户','2021-08-10 21:28:35')
           *
           * @param t 带插入的实体类对象
           * @return 返回受影响行数
           * @throws IllegalAccessException
           * @throws SQLException
           */
          default int insert(T t) throws IllegalAccessException, SQLException {
              // 使用泛型参数,是因为不清楚会传什么实体类,所以使用泛型
              // 获取输入参数t的Class类对象
              Class<?> tClass = t.getClass();
              // 使用StringBuilder来存放SQL语句
              StringBuilder sb = new StringBuilder();
              // 插入SQL语句的头部"insert into "
              sb.append("insert into ");
              // 获取类名,但需要将类名转换成小写,虽然在MySQL中不区分大小写
              sb.append(tClass.getSimpleName().toLowerCase());
              sb.append("(");
              // 获取属性数组,即获取t所表示的实体类中的所有属性,而不是该类中的所有方法
              Field[] fields = tClass.getDeclaredFields();
              int i = 0;
              for (Field field : fields) {
                  sb.append(field.getName());// 添加属性名
                  sb.append(",");
                  i++;
              }
              // 除去最后一个逗号,添加一个右括号
              String s = sb.substring(0, sb.length() - 1) + ")";
              StringBuilder result = new StringBuilder(s);
              result.append(" values(");
              for (int j = 0; j < i; j++) {
                  result.append("?,");
              }
              // 到这一步,一个完整的SQL语句完成了,只是没有传入参数
              // 例如:insert into user(phone,username,insert_time,email,memo,id,password) values(?,?,?,?,?,?,?)
              String sql = result.substring(0, result.length() - 1) + ")";
      
              // 接下来就是进行插入操作
              // 获取数据库连接
              Connection connection = JDBCUtil.getConnection();
              // 根据Connection创建PreparedStatement对象
              PreparedStatement ps = connection.prepareStatement(sql);
              // 该参数表示是第几个待传入的参数,在PreparedStatement类中设置参数对应值的方法的序号是从1开始的
              int j = 1;
              for (Field field : fields) {
                  field.setAccessible(true);
                  ps.setObject(j, field.get(t));
                  j++;
              }
              // 可以打印完整的SQL语句
              System.out.println(ps);
              // 执行SQL插入操作
              return ps.executeUpdate();
          }
      
          // --------------------------------------更新操作------------------------------------------
      
          /**
           * 通过id字段更新记录
           * SQL语句如:update user set username='王五' where id=6;
           *
           * @param t 待更新的信息,都是封装在实体类中的,包括id信息
           * @return 返回受影响行数
           */
          default int updateById(T t) throws SQLException, IllegalAccessException {
              // 1.获取字段
              // 获取t所表示类的Class对象
              Class<?> tClass = t.getClass();
              // 获取该类的所有属性
              Field[] fields = tClass.getDeclaredFields();
              // 过滤掉空值的字段
              // 将Field数组转换成Field流
              Stream<Field> stream = Arrays.stream(fields);
              // 过滤掉空属性,因为待更新的字段必须是有值的属性
              Stream<Field> fieldStream = stream.filter((field) -> {
                  field.setAccessible(true);
                  try {
                      // 只保留不为空的字段
                      return field.get(t) != null;
                  } catch (IllegalAccessException e) {
                      e.printStackTrace();
                  }
                  return false;
              });
      
              // 2.组装SQL语句
              StringBuilder sb = new StringBuilder();
              sb.append("update ");
              sb.append(tClass.getSimpleName().toLowerCase());// 表名
              sb.append(" set ");
              // 循环遍历要更新的字段
              List<Field> fieldList = new ArrayList<>();
              fieldStream.forEach((field -> {
                  // 将字段添加到List集合中
                  fieldList.add(field);
                  if (!"id".equals(field.getName())) {
                      sb.append(field.getName().toLowerCase());
                      sb.append("=");
                      sb.append("?");
                      sb.append(",");
                  }
              }));
              // 去除最后一个逗号","
              String where = sb.substring(0, sb.length() - 1);
              // 设置where后面的条件子句,即"where id=?;"
              StringBuilder sql = new StringBuilder(where);
              sql.append(" where ");
              sql.append("id=?;");
              String updateSql = sql.toString();
      
              // 3.执行SQL语句返回结果
              Connection connection = JDBCUtil.getConnection();
              PreparedStatement ps = connection.prepareStatement(updateSql);
              // 调用PreparedStatement类的setObject()方法的参数序号,从1开始
              int parameterIndex = 1;
              // id字段对应的值
              Object id = -1;
              for (Field field : fieldList) {
                  if (!"id".equals(field.getName())) {
                      field.setAccessible(true);
                      ps.setObject(parameterIndex, field.get(t));
                      parameterIndex++;
                  } else {
                      // 将id字段的值保存到局部变量中
                      id = field.get(t);
                  }
              }
              // 设置id字段的值,即最后一个问号的值
              ps.setObject(parameterIndex, id);
              System.out.println(ps);
              // 执行更新操作,返回受影响行数
              return ps.executeUpdate();
          }
      
          /**
           * 通过条件查询更新记录。
           * SQL语句如:update user set username='李四',password='abcd' where id=23 and username='王五' and email='10086@';
           *
           * @param t          待更新的信息
           * @param conditions where子句后面的条件
           * @return 返回受影响的行数
           * @throws SQLException
           * @throws IllegalAccessException
           */
          default int update(T t, Map<String, Object> conditions) throws SQLException, IllegalAccessException {
              // 1.获取字段
              // 获取t所表示类的Class对象
              Class<?> tClass = t.getClass();
              // 获取该类的所有属性
              Field[] fields = tClass.getDeclaredFields();
              // 过滤掉空值的字段
              // 将Field数组转换成Field流
              Stream<Field> stream = Arrays.stream(fields);
              // 过滤掉空属性,因为待更新的字段必须是有值的属性
              Stream<Field> fieldStream = stream.filter((field) -> {
                  field.setAccessible(true);
                  try {
                      // 只保留不为空的字段
                      // 注意:如果是基本数据类型如int,那么会有一个默认值,会通过!=null判断,导致出现问题
                      // 所以在实体类中尽量使用引用数据类型,而不是基本数据类型
                      return field.get(t) != null;
                  } catch (IllegalAccessException e) {
                      e.printStackTrace();
                  }
                  return false;
              });
      
              // 2.组装SQL语句
              StringBuilder sb = new StringBuilder();
              sb.append("update ");
              sb.append(tClass.getSimpleName().toLowerCase());// 表名
              sb.append(" set ");
              // 循环遍历要更新的字段
              List<Field> fieldList = new ArrayList<>();
              fieldStream.forEach((field -> {
                  // 将字段添加到List集合中
                  fieldList.add(field);
                  sb.append(field.getName().toLowerCase());
                  sb.append("=");
                  sb.append("?");
                  sb.append(",");
              }));
              // 去除最后一个逗号","
              String where = sb.substring(0, sb.length() - 1);
              // 设置where后面的条件子句,即"where username='xxx' and password='xxx';"
              StringBuilder sql = new StringBuilder(where);
              sql.append(" where ");
              for (String key : conditions.keySet()) {
                  sql.append(key);
                  sql.append("=?");
                  sql.append(" and ");
              }
              String updateSql = sql.substring(0, sql.lastIndexOf("and"));
      
              // 3.执行SQL语句返回结果
              Connection connection = JDBCUtil.getConnection();
              PreparedStatement ps = connection.prepareStatement(updateSql);
              // 调用PreparedStatement类的setObject()方法的参数序号,从1开始
              int parameterIndex = 1;
              // 设置set子句后面的参数
              for (Field field : fieldList) {
                  field.setAccessible(true);
                  ps.setObject(parameterIndex, field.get(t));
                  parameterIndex++;
              }
              // 设置where子句后面的参数
              for (String key : conditions.keySet()) {
                  ps.setObject(parameterIndex, conditions.get(key));
                  parameterIndex++;
              }
              System.out.println(ps);
              // 执行更新操作,返回受影响行数
              return ps.executeUpdate();
          }
      
          // --------------------------------------删除操作------------------------------------------
      
          /**
           * 通过id字段删除某条记录。
           * SQL语句如:delete from user where id=2;
           *
           * @param clazz 实体类,如User.class
           * @param id    待删除的id字段值
           * @return 返回受影响行数
           * @throws SQLException
           */
          default int deleteById(Class<?> clazz, Serializable id) throws SQLException {
              // 1.拼接SQL语句
              StringBuilder sql = new StringBuilder();
              sql.append("delete from ");
              sql.append(clazz.getSimpleName().toLowerCase());
              sql.append(" where ");
              sql.append("id=?;");
              String deleteSql = sql.toString();
      
              // 2.执行SQL语句
              Connection connection = JDBCUtil.getConnection();
              PreparedStatement ps = connection.prepareStatement(deleteSql);
              ps.setObject(1, id);
              return ps.executeUpdate();
          }
      
          /**
           * 多条件删除。
           * SQL语句如:delete from user where username='zhangsan' and password='123456';
           *
           * @param clazz      实体类,如User.class
           * @param conditions where子句后面跟着的条件
           * @return 返回受影响行数
           * @throws SQLException
           */
          default int deleteByMap(Class<?> clazz, Map<String, Object> conditions) throws SQLException {
              // 1.拼接SQL语句
              StringBuilder sql = new StringBuilder();
              sql.append("delete from ");
              sql.append(clazz.getSimpleName().toLowerCase());
              sql.append(" where ");
              // 从conditions集合中读取条件参数
              for (String key : conditions.keySet()) {
                  sql.append(key);
                  sql.append("=");
                  sql.append("?");
                  sql.append(" and ");
              }
              String deleteSql = sql.substring(0, sql.lastIndexOf("and"));
      
              // 2.执行SQL语句
              Connection connection = JDBCUtil.getConnection();
              PreparedStatement ps = connection.prepareStatement(deleteSql);
              int parameterIndex = 1;
              for (String key : conditions.keySet()) {
                  ps.setObject(parameterIndex, conditions.get(key));
                  parameterIndex++;
              }
              return ps.executeUpdate();
          }
      
          /**
           * 根据实体类中的字段进行条件删除。
           * SQL语句如:delete from user where username='zhangsan' and password='123456';
           *
           * @param t 实体类对象
           * @return 返回受影响行数
           * @throws SQLException
           * @throws IllegalAccessException
           */
          default int delete(T t) throws SQLException, IllegalAccessException {
              // 1.获取条件字段,过滤掉空字段
              Field[] fields = t.getClass().getDeclaredFields();
              // 使用Stream流进行初步过滤
              Stream<Field> stream = Arrays.stream(fields);
              Stream<Field> fieldStream = stream.filter((field -> {
                  field.setAccessible(true);
                  try {
                      // 只保留设置了值的字段
                      return field.get(t) != null;
                  } catch (IllegalAccessException e) {
                      e.printStackTrace();
                  }
                  return false;
              }));
      
              // 2.组装SQL语句
              StringBuilder sql = new StringBuilder();
              sql.append("delete from ");
              sql.append(t.getClass().getSimpleName().toLowerCase());
              sql.append(" where ");
              List<Field> fieldList = new ArrayList<>();
              fieldStream.forEach((field -> {
                  fieldList.add(field);
                  field.setAccessible(true);
                  sql.append(field.getName().toLowerCase());
                  sql.append("=");
                  sql.append("?");
                  sql.append(" and ");
              }));
              String deleteSql = sql.substring(0, sql.lastIndexOf("and"));
      
              // 3.执行SQL语句,返回删除结果
              Connection connection = JDBCUtil.getConnection();
              PreparedStatement ps = connection.prepareStatement(deleteSql);
              int parameterIndex = 1;
              for (Field field : fieldList) {
                  ps.setObject(parameterIndex, field.get(t));
                  parameterIndex++;
              }
              return ps.executeUpdate();
          }
      
          // --------------------------------------查询操作------------------------------------------
      
          /**
           * 通过id查询某条记录。
           * SQL语句如:select * from user where id=2;
           *
           * @param clazz 实体类,如User.class
           * @param id    主键id
           * @return 返回查询结果
           * @throws SQLException
           * @throws InstantiationException
           * @throws IllegalAccessException
           * @throws InvocationTargetException
           */
          default T selectById(Class<?> clazz, Serializable id) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
              // 1.组装SQL语句
              StringBuilder sql = new StringBuilder();
              sql.append("select * from ");
              sql.append(clazz.getSimpleName().toLowerCase());
              sql.append(" where id=?");
              String selectSql = sql.toString();
      
              // 2.执行SQL语句获取查询结果集
              Connection connection = JDBCUtil.getConnection();
              PreparedStatement ps = connection.prepareStatement(selectSql);
              ps.setObject(1, id);
              ResultSet rs = ps.executeQuery();
      
              // 3.封装查询结果集到实体类对象中并返回
              // 利用反射创建实例对象
              Object t = clazz.newInstance();
              Method[] methods = t.getClass().getDeclaredMethods();
              if (rs.next()) {
                  // 循环遍历方法数组,将数据封装到实体类对象中
                  for (Method method : methods) {
                      // 过滤setXXX方法,设置属性的值
                      if (method.getName().startsWith("set")) {
                          // 设置属性的值,通过rs.getObject(String columnLabel)方法获取指定列的值
                          method.invoke(t, rs.getObject(method.getName().substring(3)));
                      }
                  }
              }
              // 如果还有下一条记录,表示查询结果有多个,那么不应该
              if (rs.next()) {
                  throw new IllegalArgumentException("查询结果有多个,请输入合法参数:" + id);
              }
              return (T) t;
          }
      
          /**
           * 通过批量id查询多条记录。
           * SQL语句如:select * from user where id in (1,2,3,4,5);
           *
           * @param clazz  实体类,如User.class
           * @param idList 主键id列表
           * @return 返回查询结果集
           * @throws SQLException
           * @throws InstantiationException
           * @throws IllegalAccessException
           * @throws InvocationTargetException
           */
          default List<T> selectBatchIds(Class<?> clazz, List<? extends Serializable> idList) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
              // 1.组装SQL语句
              StringBuilder sql = new StringBuilder();
              sql.append("select * from ");
              sql.append(clazz.getSimpleName().toLowerCase());
              sql.append(" where id in(");
              for (int i = 0; i < idList.size(); i++) {
                  sql.append("?");
                  if (i != idList.size() - 1) {
                      sql.append(",");
                  }
              }
              sql.append(")");
              String selectSql = sql.toString();
      
              // 2.执行SQL语句获取查询结果集
              Connection connection = JDBCUtil.getConnection();
              PreparedStatement ps = connection.prepareStatement(selectSql);
              int parameterIndex = 1;
              for (Serializable id : idList) {
                  ps.setObject(parameterIndex, id);
                  parameterIndex++;
              }
              ResultSet rs = ps.executeQuery();
      
              // 3.封装查询结果集到实体类对象中并返回
              List<T> tList = new ArrayList<>();
              while (rs.next()) {
                  // 利用反射创建实例对象
                  Object t = clazz.newInstance();
                  // 获取该类的所有声明的方法
                  Method[] methods = t.getClass().getDeclaredMethods();
                  // 循环遍历方法数组,将数据封装到实体类对象中
                  for (Method method : methods) {
                      // 过滤setXXX方法,设置属性的值
                      if (method.getName().startsWith("set")) {
                          // 设置属性的值,通过rs.getObject(String columnLabel)方法获取指定列的值
                          method.invoke(t, rs.getObject(method.getName().substring(3)));
                      }
                  }
                  tList.add((T) t);
              }
              return tList;
          }
      
          /**
           * 多条件查询唯一一条记录。
           * SQL语句如:select * from user where username='zhangsan' and password='123456';
           *
           * @param clazz      实体类,如User.class
           * @param conditions where子句后面的条件集合
           * @return 返回查询结果
           * @throws SQLException
           * @throws InstantiationException
           * @throws IllegalAccessException
           * @throws InvocationTargetException
           */
          default T selectOne(Class<?> clazz, Map<String, Object> conditions) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
              // 1.组装SQL语句
              StringBuilder sql = new StringBuilder();
              sql.append("select * from ");
              sql.append(clazz.getSimpleName().toLowerCase());
              // where子句后面的条件
              sql.append(" where ");
              for (String key : conditions.keySet()) {
                  sql.append(key);
                  sql.append("=");
                  sql.append("?");
                  sql.append(" and ");
              }
              String selectSql = sql.substring(0, sql.lastIndexOf("and"));
      
              // 2.执行SQL语句获取查询结果集
              Connection connection = JDBCUtil.getConnection();
              PreparedStatement ps = connection.prepareStatement(selectSql);
              int parameterIndex = 1;
              for (String key : conditions.keySet()) {
                  ps.setObject(parameterIndex, conditions.get(key));
                  parameterIndex++;
              }
              ResultSet rs = ps.executeQuery();
      
              // 3.封装查询结果集到实体类对象中并返回
              // 利用反射创建实例对象
              Object t = clazz.newInstance();
              Method[] methods = t.getClass().getDeclaredMethods();
              if (rs.next()) {
                  // 循环遍历方法数组,将数据封装到实体类对象中
                  for (Method method : methods) {
                      // 过滤setXXX方法,设置属性的值
                      if (method.getName().startsWith("set")) {
                          // 设置属性的值,通过rs.getObject(String columnLabel)方法获取指定列的值
                          method.invoke(t, rs.getObject(method.getName().substring(3)));
                      }
                  }
              }
              // 如果还有下一条记录,表示查询结果有多个,那么不应该
              if (rs.next()) {
                  throw new IllegalArgumentException("查询结果有多个,请输入合法参数。");
              }
              return (T) t;
          }
      
          /**
           * 指定条件下的记录总条数。
           * SQL语句如:select count(*) from user where password='123456';
           *
           * @param clazz      实体类,如User.class
           * @param conditions where子句后面的条件集合
           * @return 返回记录总条数
           * @throws SQLException
           * @throws InstantiationException
           * @throws IllegalAccessException
           * @throws InvocationTargetException
           */
          default Integer selectCount(Class<?> clazz, Map<String, Object> conditions) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
              // 1.组装SQL语句
              StringBuilder sql = new StringBuilder();
              sql.append("select count(*) from ");
              sql.append(clazz.getSimpleName().toLowerCase());
              // where子句后面的条件
              sql.append(" where ");
              for (String key : conditions.keySet()) {
                  sql.append(key);
                  sql.append("=");
                  sql.append("?");
                  sql.append(" and ");
              }
              String selectSql = sql.substring(0, sql.lastIndexOf("and"));
      
              // 2.执行SQL语句获取查询结果集
              Connection connection = JDBCUtil.getConnection();
              PreparedStatement ps = connection.prepareStatement(selectSql);
              int parameterIndex = 1;
              for (String key : conditions.keySet()) {
                  ps.setObject(parameterIndex, conditions.get(key));
                  parameterIndex++;
              }
              ResultSet rs = ps.executeQuery();
      
              // 3.封装查询结果集到实体类对象中并返回
              // 记录的总条数
              int count = 0;
              if (rs.next()) {
                  count = rs.getInt(1);
              }
              return count;
          }
      
          /**
           * 多条件下查询多条记录。
           * SQL语句如下:select * from user where username='zhangsan' and password='123456';
           *
           * @param clazz      实体类,如User.class
           * @param conditions where子句后面的条件集合
           * @return 返回查询结果集
           * @throws SQLException
           * @throws InstantiationException
           * @throws IllegalAccessException
           * @throws InvocationTargetException
           */
          default List<T> selectList(Class<?> clazz, Map<String, Object> conditions) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
              // 1.组装SQL语句
              StringBuilder sql = new StringBuilder();
              sql.append("select * from ");
              sql.append(clazz.getSimpleName().toLowerCase());
              // where子句后面的条件
              sql.append(" where ");
              for (String key : conditions.keySet()) {
                  sql.append(key);
                  sql.append("=");
                  sql.append("?");
                  sql.append(" and ");
              }
              String selectSql = sql.substring(0, sql.lastIndexOf("and"));
      
              // 2.执行SQL语句获取查询结果集
              Connection connection = JDBCUtil.getConnection();
              PreparedStatement ps = connection.prepareStatement(selectSql);
              int parameterIndex = 1;
              for (String key : conditions.keySet()) {
                  ps.setObject(parameterIndex, conditions.get(key));
                  parameterIndex++;
              }
              ResultSet rs = ps.executeQuery();
      
              // 3.封装查询结果集到实体类对象中并返回
              List<T> tList = new ArrayList<>();
              while (rs.next()) {
                  // 利用反射创建实例对象
                  Object t = clazz.newInstance();
                  Method[] methods = t.getClass().getDeclaredMethods();
                  // 循环遍历方法数组,将数据封装到实体类对象中
                  for (Method method : methods) {
                      // 过滤setXXX方法,设置属性的值
                      if (method.getName().startsWith("set")) {
                          // 设置属性的值,通过rs.getObject(String columnLabel)方法获取指定列的值
                          method.invoke(t, rs.getObject(method.getName().substring(3)));
                      }
                  }
                  tList.add((T) t);
              }
              return tList;
          }
      
          /**
           * 多条件下分页查询多条记录。
           * SQL语句如下:select * from user where username='zhangsan' limit 0,5;
           *
           * @param clazz      实体类,如User.class
           * @param limit      分页查询中的起始索引,从0开始
           * @param size       该页条数
           * @param conditions where子句后面的条件集合
           * @return 返回查询结果集
           * @throws SQLException
           * @throws InstantiationException
           * @throws IllegalAccessException
           * @throws InvocationTargetException
           */
          default List<T> selectPage(Class<?> clazz, int limit, int size, Map<String, Object> conditions) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
              // 1.组装SQL语句
              StringBuilder sql = new StringBuilder();
              sql.append("select * from ");
              sql.append(clazz.getSimpleName().toLowerCase());
              // where子句后面的条件,注意处理空条件的问题
              sql.append(" where ");
              for (String key : conditions.keySet()) {
                  sql.append(key);
                  sql.append("=");
                  sql.append("?");
                  sql.append(" and ");
              }
              String selectSql = sql.substring(0, sql.lastIndexOf("and"));
              selectSql = selectSql + " limit " + limit + "," + size;
      
              // 2.执行SQL语句获取查询结果集
              Connection connection = JDBCUtil.getConnection();
              PreparedStatement ps = connection.prepareStatement(selectSql);
              int parameterIndex = 1;
              for (String key : conditions.keySet()) {
                  ps.setObject(parameterIndex, conditions.get(key));
                  parameterIndex++;
              }
              ResultSet rs = ps.executeQuery();
      
              // 3.封装查询结果集到实体类对象中并返回
              List<T> tList = new ArrayList<>();
              while (rs.next()) {
                  // 利用反射创建实例对象
                  Object t = clazz.newInstance();
                  Method[] methods = t.getClass().getDeclaredMethods();
                  // 循环遍历方法数组,将数据封装到实体类对象中
                  for (Method method : methods) {
                      // 过滤setXXX方法,设置属性的值
                      if (method.getName().startsWith("set")) {
                          // 设置属性的值,通过rs.getObject(String columnLabel)方法获取指定列的值
                          method.invoke(t, rs.getObject(method.getName().substring(3)));
                      }
                  }
                  tList.add((T) t);
              }
              return tList;
          }
      
          /**
           * 查询该表的所有记录。
           * SQL语句如下:select * from user;
           *
           * @param tClass 实体类,如User.class
           * @return 返回查询结果集
           * @throws SQLException
           * @throws InstantiationException
           * @throws IllegalAccessException
           * @throws InvocationTargetException
           */
          default List<T> selectAll(Class<T> tClass) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
              // 设置查询所有记录的SQL语句
              String sql = "select * from " + tClass.getSimpleName().toLowerCase();
              // 创建存放结果的集合
              List<T> lists = new ArrayList<>();
              // 获取数据库连接并创建PreparedStatement对象,执行查询操作获取结果集
              Connection connection = JDBCUtil.getConnection();
              PreparedStatement ps = connection.prepareStatement(sql);
              ResultSet rs = ps.executeQuery();
              while (rs.next()) {
                  // 根据实体类创建实例对象
                  T t = tClass.newInstance();
                  // 获取t所表示的实体类的所有方法,其实主要是获取setXXX方法,设置属性的值
                  Method[] methods = t.getClass().getDeclaredMethods();
                  // 循环遍历方法数组
                  for (Method method : methods) {
                      // 过滤setXXX方法,设置属性的值
                      if (method.getName().startsWith("set")) {
                          // 设置属性的值,通过rs.getObject(String columnLabel)方法获取指定列的值
                          method.invoke(t, rs.getObject(method.getName().substring(3)));
                      }
                  }
                  // 将设置成功的实例对象添加到集合中
                  lists.add(t);
              }
              return lists;
          }
      
      }

      第三步,创建对应实体类。

      创建对应的实体类,该类中的属性名和对应表中的字段名一一对应,注意属性名和字段名必须完全对应,不能将下划线转换成驼峰命名。

      class User {
          private Long id;
          private String username;
          private String password;
          private String phone;
          private String email;
          private String memo;
          private java.util.Date insert_time;
      
          public User() {
          }
      
          public User(String username, String password, String phone, String email, String memo, java.util.Date insert_time) {
              this.username = username;
              this.password = password;
              this.phone = phone;
               = email;
              this.memo = memo;
              this.insert_time = insert_time;
          }
      
          public User(Long id, String username, String password, String phone, String email, String memo, java.util.Date insert_time) {
              this.id = id;
              this.username = username;
              this.password = password;
              this.phone = phone;
               = email;
              this.memo = memo;
              this.insert_time = insert_time;
          }
      
          public Long getId() {
              return id;
          }
      
          public void setId(Long id) {
              this.id = id;
          }
      
          public String getUsername() {
              return username;
          }
      
          public void setUsername(String username) {
              this.username = username;
          }
      
          public String getPassword() {
              return password;
          }
      
          public void setPassword(String password) {
              this.password = password;
          }
      
          public String getPhone() {
              return phone;
          }
      
          public void setPhone(String phone) {
              this.phone = phone;
          }
      
          public String getEmail() {
              return email;
          }
      
          public void setEmail(String email) {
               = email;
          }
      
          public String getMemo() {
              return memo;
          }
      
          public void setMemo(String memo) {
              this.memo = memo;
          }
      
          public java.util.Date getInsert_time() {
              return insert_time;
          }
      
          public void setInsert_time(Date insert_time) {
              this.insert_time = insert_time;
          }
      
          @Override
          public String toString() {
              return "User{" +
                      "id=" + id +
                      ", username='" + username + '\'' +
                      ", password='" + password + '\'' +
                      ", phone='" + phone + '\'' +
                      ", email='" + email + '\'' +
                      ", memo='" + memo + '\'' +
                      ", insert_time=" + insert_time +
                      '}';
          }
      }

      第四步,创建UserMapper类实现BaseMapper<User>接口。

      由于定义了默认方法,所以只需要实现BaseMapper接口,不需要自定义任何方法。

      class UserMapper implements BaseMapper<User> {
      
      }

      第五步,测试方法。

      class Test {
          public static void main(String[] args) throws SQLException, IllegalAccessException, InvocationTargetException, InstantiationException {
              UserMapper userMapper = new UserMapper();
              Map<String, Object> map = new HashMap<>();
              map.put("username", "张三");
              map.put("password", "123456");
              System.out.println(userMapper.selectPage(User.class, 2, 4, map));
          }
      }

      存在的问题

      上面封装的BaseMapper<T>接口实际上是存在很多问题的,很难在实际中使用。下面列举些常见的问题:

      • 1.属性名和字段名必须一模一样。
      • 2.主键id字段的插入字段存在问题。
      • 3.conditions条件必须匹配,即至少存在一个条件。
      • 4.只能处理相等的条件,不能处理更复杂的条件查询如大于条件等。
      • 5.实体类中的属性名必须是使用引用数据类型,否则可能会引发异常。
      版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.csdn.net/cnds123321/article/details/119617626,作者:二木成林,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。

      上一篇:队列练习之Example001-用两个栈 s1 和 s2 来模拟一个队列,实现队列的出队、入队、队是否为空的运算

      下一篇:【Android入门到项目实战--4.7】—— 怎么使用LitePal来操作数据库?

      相关文章

      2025-05-19 09:05:01

      项目更新到公网服务器的操作步骤

      项目更新到公网服务器的操作步骤

      2025-05-19 09:05:01
      公网 , 数据库 , 文件 , 更新 , 服务器
      2025-05-19 09:05:01

      Navicat 连接MySQL 8.0.11 出现2059错误 解决

      Navicat 连接MySQL 8.0.11 出现2059错误 解决

      2025-05-19 09:05:01
      MySQL , Navicat , 解决 , 连接
      2025-05-19 09:04:53

      Django rest froamwork-ModelSerializer

      Django rest froamwork-ModelSerializer

      2025-05-19 09:04:53
      django , sqlite , 数据库
      2025-05-19 09:04:38

      mysql只有在任务处于完成状态才能运行

      mysql只有在任务处于完成状态才能运行

      2025-05-19 09:04:38
      MySQL , 任务 , 数据库 , 查询 , 状态
      2025-05-19 09:04:30

      设置28401事件后启动数据库时报错ORA-49100

      设置28401事件后启动数据库时报错ORA-49100

      2025-05-19 09:04:30
      ORA , 数据库 , 时报
      2025-05-16 09:15:24

      MySQL 表的内外连接

      MySQL 表的内外连接

      2025-05-16 09:15:24
      MySQL , 显示 , 连接
      2025-05-14 10:03:13

      MySQL 索引优化以及慢查询优化

      MySQL 是一种广泛使用的关系型数据库管理系统,因其性能优异和使用便捷而备受欢迎。然而,随着数据量的增长和查询复杂度的增加,性能瓶颈也变得越来越明显。

      2025-05-14 10:03:13
      MySQL , 优化 , 使用 , 性能 , 数据库 , 查询 , 索引
      2025-05-14 10:03:05

      Oracle数据库用户权限分析

      Oracle数据库用户权限分析

      2025-05-14 10:03:05
      Oracle , 分析 , 数据库 , 权限 , 用户
      2025-05-14 10:02:48

      SQL Server 事务日志体系结构1--基本术语

      事务包括对数据库的一次更改或一系列更改。它有一个明确开始和明确结束。开始时使用BEGIN TRANSACTION语句,或者SQL Server会自动为您开始一个事务。

      2025-05-14 10:02:48
      Server , SQL , 事务 , 数据库 , 日志 , 磁盘
      2025-05-14 10:02:48

      SQL Server 账号管理1

      SQL Server 账号管理主要包含登录名、用户、架构、角色等管理。通过对账号的管理可以有效的提高数据库系统的安全性,规范运维及使用。

      2025-05-14 10:02:48
      Server , SQL , 对象 , 数据库 , 权限 , 用户
      查看更多
      推荐标签

      作者介绍

      天翼云小翼
      天翼云用户

      文章

      33561

      阅读量

      5238665

      查看更多

      最新文章

      Navicat 连接MySQL 8.0.11 出现2059错误 解决

      2025-05-19 09:05:01

      Django rest froamwork-ModelSerializer

      2025-05-19 09:04:53

      mysql只有在任务处于完成状态才能运行

      2025-05-19 09:04:38

      设置28401事件后启动数据库时报错ORA-49100

      2025-05-19 09:04:30

      MySQL 表的内外连接

      2025-05-16 09:15:24

      MySQL 索引优化以及慢查询优化

      2025-05-14 10:03:13

      查看更多

      热门文章

      Nacos数据持久化到MySQL

      2023-05-12 07:20:56

      Confluence 6 MySQL 输入你的数据库细节

      2023-04-27 08:03:27

      MySQL的间隙锁

      2023-05-12 07:20:56

      MySQL timestamp(3)问题

      2023-04-27 08:00:12

      ​云原生微服务K8s容器编排第七章之ETCD的使用及备份

      2023-03-16 07:45:55

      MySQL安全小技巧

      2023-05-06 10:22:49

      查看更多

      热门标签

      数据库 mysql 字符串 数据结构 MySQL 算法 redis oracle java sql python 数据 索引 SQL 查询
      查看更多

      相关产品

      弹性云主机

      随时自助获取、弹性伸缩的云服务器资源

      天翼云电脑(公众版)

      便捷、安全、高效的云电脑服务

      对象存储

      高品质、低成本的云上存储服务

      云硬盘

      为云上计算资源提供持久性块存储

      查看更多

      随机文章

      【mysql】ENUM类型

      redis优化系列五Sentinel 实现原理常见问题

      MySQL索引结构

      mysql/stonedb-IN句子使用HASH优化后-查询多个字符串结果不符合预期记录

      MySQL学习记录===待续

      数据库索引(1)-基础

      • 7*24小时售后
      • 无忧退款
      • 免费备案
      • 专家服务
      售前咨询热线
      400-810-9889转1
      关注天翼云
      • 旗舰店
      • 天翼云APP
      • 天翼云微信公众号
      服务与支持
      • 备案中心
      • 售前咨询
      • 智能客服
      • 自助服务
      • 工单管理
      • 客户公告
      • 涉诈举报
      账户管理
      • 管理中心
      • 订单管理
      • 余额管理
      • 发票管理
      • 充值汇款
      • 续费管理
      快速入口
      • 天翼云旗舰店
      • 文档中心
      • 最新活动
      • 免费试用
      • 信任中心
      • 天翼云学堂
      云网生态
      • 甄选商城
      • 渠道合作
      • 云市场合作
      了解天翼云
      • 关于天翼云
      • 天翼云APP
      • 服务案例
      • 新闻资讯
      • 联系我们
      热门产品
      • 云电脑
      • 弹性云主机
      • 云电脑政企版
      • 天翼云手机
      • 云数据库
      • 对象存储
      • 云硬盘
      • Web应用防火墙
      • 服务器安全卫士
      • CDN加速
      热门推荐
      • 云服务备份
      • 边缘安全加速平台
      • 全站加速
      • 安全加速
      • 云服务器
      • 云主机
      • 智能边缘云
      • 应用编排服务
      • 微服务引擎
      • 共享流量包
      更多推荐
      • web应用防火墙
      • 密钥管理
      • 等保咨询
      • 安全专区
      • 应用运维管理
      • 云日志服务
      • 文档数据库服务
      • 云搜索服务
      • 数据湖探索
      • 数据仓库服务
      友情链接
      • 中国电信集团
      • 189邮箱
      • 天翼企业云盘
      • 天翼云盘
      ©2025 天翼云科技有限公司版权所有 增值电信业务经营许可证A2.B1.B2-20090001
      公司地址:北京市东城区青龙胡同甲1号、3号2幢2层205-32室
      • 用户协议
      • 隐私政策
      • 个人信息保护
      • 法律声明
      备案 京公网安备11010802043424号 京ICP备 2021034386号