java通过反射拿到mybatis中的sql语句并操作

Wesley13
• 阅读 500
private static final int MaxBatchLength = 100;

public void updateBatch(List<T>list, BaseMapper<T> mapper){
            
         if (!Proxy.isProxyClass(mapper.getClass())){
             throw new RuntimeException("mapper必须是代理对象");
         }
        InvocationHandler invocationHandler = Proxy.getInvocationHandler(mapper);
         if (null==invocationHandler){
             throw new RuntimeException("mapper必须是有处理器的代理对象");
         }
        Field fieldSession;
        try {
            fieldSession = invocationHandler.getClass().getDeclaredField("sqlSession");
        } catch (NoSuchFieldException e) {
            throw new RuntimeException("从mapper代理对象中获取不到sqlSession", e);
        }
        Field fieldMapper;
        try {
            fieldMapper = invocationHandler.getClass().getDeclaredField("mapperInterface");
        } catch (NoSuchFieldException | SecurityException e) {
            throw new RuntimeException("从mapper代理对象中获取不到mapperInterface", e);
        }
        fieldSession.setAccessible(true);
        SqlSession session;
        try {
            session = (SqlSession) fieldSession.get(invocationHandler);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new RuntimeException("从mapper代理对象中获取sqlSession失败,不应该出现此异常", e);
        }
        fieldMapper.setAccessible(true);
        Class<?> mapperInterface;
        try {
            mapperInterface = (Class<?>) fieldMapper.get(invocationHandler);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new RuntimeException("从mapper代理对象中获取mapperInterface失败,不应该出现此异常", e);
        }
        // 方法名(mybatis的对应xml中的sql语句的id)
        String methodName = mapperInterface.getName() + ".updateEntityBatch";
        System.out.println("获取方法的SQL:"+methodName);
        //传递参数保证,要更新的字段存在(若没有判空,则可以不用传递参数)
        BoundSql boundSql = session.getConfiguration().getMappedStatement(methodName).getBoundSql(list.get(0));

        //是否是独立的事务
        boolean atmo = true, succ = false;
        System.out.println("每次批量执行最大长度为:"+MaxBatchLength );

        //获取批量执行的sql
        String sql = boundSql.getSql();
        //获取连接
        Connection connection = null;
        PreparedStatement ps = null;
        List<Closeable> closeables = new LinkedList<>();
        try {
            connection = session.getConnection();
            if (atmo = null == connection || connection.isClosed()) {
                DataSource dataSource = session.getConfiguration().getEnvironment().getDataSource();
                connection = dataSource.getConnection();
                //事务不自动提交
                connection.setAutoCommit(false);
                System.out.println("session中的连接不可使用,使用独立的连接和事务");
            } else {
                System.out.println("使用session的连接,事务和session保持一致");
            }

            ps = connection.prepareStatement(sql);
           
            int index = 0;
            System.out.println("需要批量更新"+list.size()+"个对象");

            for (int i = 0, j = list.size(); i < j; i++, index++) {
                T t = list.get(i);
                //将实体类转换为map
                BeanMap map = BeanMap.create(t);
                System.out.println("绑定对象:"+ map);
                for (int ii = 1, jj = boundSql.getParameterMappings().size(); ii <= jj; ii++) {
                    ParameterMapping parameterMapping = boundSql.getParameterMappings().get(ii - 1);
                    String name = parameterMapping.getProperty();
                    Object value = map.get(name);
                    if (null == value) {
                        // 为空时候尝试取默认值
                        value = map.get(name + "Default");
                    }
                    if (null != value && value instanceof Date) {
                        Timestamp date = new Timestamp(((Date) value).getTime());
                        value = date;
                    }
                    // 单独处理clob类型
                    if (JdbcType.CLOB.equals(parameterMapping.getJdbcType())) {
                        StringReader sr = new StringReader(null == value ? "" : value.toString());
                        ps.setClob(ii, sr);
                        closeables.add(sr);
                    } else {
                        ps.setObject(ii, value, parameterMapping.getJdbcType().TYPE_CODE);
                    }
                }
                ps.addBatch();
                if (index > MaxBatchLength) {
                     ps.executeBatch();
                    ps.clearBatch();
                    index = 0;
                }
            }
            if (index > 0) {
                //执行剩下的
                ps.executeBatch();
            }
            succ = true;
        }catch (Exception e){
            throw new RuntimeException("批量更新失败",e);
        }finally {
            // 如果是独立的事务
            if (atmo && null != connection) {
               log.info("检测到独立事务,判断提交/回滚");
                if (succ) {
                    try {
                        connection.commit();
                        log.info("独立事务提交成功");
                    } catch (SQLException e) {
                        log.info("独立事务提交失败");
                        throw new RuntimeException(e);
                    }
                } else {
                    try {
                        connection.rollback();
                        log.info("独立事务回滚成功");
                    } catch (SQLException e) {
                        log.info("独立事务回滚失败");
                        throw new RuntimeException(e);
                    }
                }
            }
            if (null != ps) {
                try {
                    ps.close();
                } catch (SQLException e) {
                   e.printStackTrace();
                }
            }
            if (atmo && null != connection) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            for (Closeable closeable : closeables) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java日期时间API系列31
  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这