mybatis JdbcTypeInterceptor - 运行时自动添加 jdbcType 属性-程序员宅基地

技术标签: java  

上代码:

package tk.mybatis.plugin;


import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.util.*;

/**
 * JdbcTypeInterceptor - 运行时自动添加 jdbcType 属性
 */
@Intercepts({
        @Signature(type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class})
})
public class JdbcTypeInterceptor implements Interceptor {

    private static Set<String> methodSet = new HashSet<>();
    private static Map<Class<?>, JdbcType> typeMap = new HashMap<>();
    private static final Field mappedStatementField;
    private static final Field boundSqlField;

    static {
        try {
            mappedStatementField = DefaultParameterHandler.class.getDeclaredField("mappedStatement");
            mappedStatementField.setAccessible(true);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException("获取 DefaultParameterHandler 字段 mappedStatement 时出错", e);
        }
        try {
            boundSqlField = DefaultParameterHandler.class.getDeclaredField("boundSql");
            boundSqlField.setAccessible(true);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException("获取 DefaultParameterHandler 字段 boundSql 时出错", e);
        }
        //设置默认的方法,是用 Mapper 所有方法
        Method[] methods = tk.mybatis.mapper.common.Mapper.class.getMethods();
        for (Method method : methods) {
            methodSet.add(method.getName());
        }
        //设置默认的类型转换,参考 TypeHandlerRegistry
        register(Boolean.class, JdbcType.BOOLEAN);
        register(boolean.class, JdbcType.BOOLEAN);

        register(Byte.class, JdbcType.TINYINT);
        register(byte.class, JdbcType.TINYINT);

        register(Short.class, JdbcType.SMALLINT);
        register(short.class, JdbcType.SMALLINT);

        register(Integer.class, JdbcType.INTEGER);
        register(int.class, JdbcType.INTEGER);

        register(Long.class, JdbcType.BIGINT);
        register(long.class, JdbcType.BIGINT);

        register(Float.class, JdbcType.FLOAT);
        register(float.class, JdbcType.FLOAT);

        register(Double.class, JdbcType.DOUBLE);
        register(double.class, JdbcType.DOUBLE);

        register(String.class, JdbcType.VARCHAR);

        register(BigDecimal.class, JdbcType.DECIMAL);
        register(BigInteger.class, JdbcType.DECIMAL);

        register(Byte[].class, JdbcType.BLOB);
        register(byte[].class, JdbcType.BLOB);

        register(Date.class, JdbcType.DATE);
        register(java.sql.Date.class, JdbcType.DATE);
        register(java.sql.Time.class, JdbcType.TIME);
        register(java.sql.Timestamp.class, JdbcType.TIMESTAMP);

        register(Character.class, JdbcType.CHAR);
        register(char.class, JdbcType.CHAR);
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //这里不考虑有多个基于该方法插件时的情况
        Object handler = invocation.getTarget();
        MappedStatement mappedStatement = (MappedStatement) mappedStatementField.get(handler);
        //一旦配置了 methods,就只对配置的方法进行处理
        if (handler instanceof DefaultParameterHandler) {
            if (methodSet.size() > 0) {
                String msId = mappedStatement.getId();
                String methodName = msId.substring(msId.lastIndexOf(".") + 1);
                if (!methodSet.contains(methodName)) {
                    return invocation.proceed();
                }
            }
            //获取基本变量信息
            BoundSql boundSql = (BoundSql) boundSqlField.get(handler);
            Object parameterObject = ((DefaultParameterHandler) handler).getParameterObject();
            Configuration configuration = mappedStatement.getConfiguration();
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            PreparedStatement ps = (PreparedStatement) invocation.getArgs()[0];
            //原 DefaultParameterHandler 逻辑
            ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
            List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
            if (parameterMappings != null) {
                for (int i = 0; i < parameterMappings.size(); i++) {
                    ParameterMapping parameterMapping = parameterMappings.get(i);
                    if (parameterMapping.getMode() != ParameterMode.OUT) {
                        Object value;
                        String propertyName = parameterMapping.getProperty();
                        if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
                            value = boundSql.getAdditionalParameter(propertyName);
                        } else if (parameterObject == null) {
                            value = null;
                        } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                            value = parameterObject;
                        } else {
                            MetaObject metaObject = configuration.newMetaObject(parameterObject);
                            value = metaObject.getValue(propertyName);
                        }
                        TypeHandler typeHandler = parameterMapping.getTypeHandler();
                        JdbcType jdbcType = parameterMapping.getJdbcType();
                        if (value == null && jdbcType == null) {
                            if (parameterMapping.getJavaType() != null && typeMap.containsKey(parameterMapping.getJavaType())) {
                                jdbcType = typeMap.get(parameterMapping.getJavaType());
                            } else {
                                jdbcType = configuration.getJdbcTypeForNull();
                            }
                        }
                        typeHandler.setParameter(ps, i + 1, value, jdbcType);
                    }
                }
            }
            return null;
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    private boolean isNotEmpty(String str) {
        return str != null && str.length() > 0;
    }

    @Override
    public void setProperties(Properties properties) {
        String methodStr = properties.getProperty("methods");
        if (isNotEmpty(methodStr)) {
            //处理所有方法
            if (methodStr.equalsIgnoreCase("ALL")) {
                methodSet.clear();
            } else {
                String[] methods = methodStr.split(",");
                for (String method : methods) {
                    methodSet.add(method);
                }
            }
        }
        //手动配置
        String typeMapStr = properties.getProperty("typeMaps");
        if (isNotEmpty(typeMapStr)) {
            String[] typeMaps = typeMapStr.split(",");
            for (String typeMap : typeMaps) {
                String[] kvs = typeMap.split(":");
                if (kvs.length == 2) {
                    register(kvs[0], kvs[1]);
                }
            }
        }
    }

    public static void register(String type, String jdbcType) {
        try {
            typeMap.put(Class.forName(type), JdbcType.valueOf(jdbcType));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("配置 typeMaps 时出错!", e);
        }
    }

    public static void register(Class<?> type, JdbcType jdbcType) {
        typeMap.put(type, jdbcType);
    }
}

 

在springboot中使用:

    @Bean
    public Interceptor getInterceptor(){
        return new JdbcTypeInterceptor();
    }

 

它的好处,就是在运行mybatis动态sql的时候给属性添加jdbcType

 

mybatis jdbctype参考:https://www.cnblogs.com/pianai-shu/p/6349183.html

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_34267123/article/details/85992082

智能推荐

CAN总线在自动驾驶中的应用_自动驾驶开发 can版本-程序员宅基地

文章浏览阅读964次,点赞14次,收藏17次。随着技术的不断发展和社会对自动驾驶技术的接受度提高,自动驾驶技术有望在未来成为现实,为我们的生活带来更多便利和安全。它连接了车辆的各个部件和系统,实现了数据的实时传输和通讯,为自动驾驶车辆的正常运行和安全性提供了基础支持。此外,CAN总线还可以用于车辆的诊断和故障排除,以确保车辆的安全和可靠性。通过CAN总线,不同的模块和系统可以共享数据并协同工作,实现了车辆的智能化和自动化。此外,CAN总线还可以用于车辆的诊断和故障排除,以确保车辆的安全和可靠性。_自动驾驶开发 can版本

Debian安装和使用Elasticsearch教程-程序员宅基地

文章浏览阅读354次,点赞9次,收藏9次。请注意,以上是一个简要的安装和使用教程,实际操作中可能会涉及到更多的配置和细节。确保按照Elasticsearch官方文档进行操作,以获得最准确的安装和配置指导。打开终端,运行以下命令来添加Elasticsearch的APT仓库。运行以下命令来验证Elasticsearch是否在运行。运行以下命令来启动Elasticsearch服务。运行以下命令来安装Elasticsearch。

在Vue里面使用wangeditor编译器,如何获取到内容?_@wangeditor/editor-for-vue 读取data-src 定义的内容-程序员宅基地

文章浏览阅读1.2w次,点赞6次,收藏3次。1:使用npm下载://(注意 wangeditor 全部是小写字母)npm install wangeditor 122: 直接在项目模板中引用import E from 'wangeditor'13:HTML &lt;div id="editorElem" style="text-align:left"&gt;&lt;/div&gt; &lt;button v-on:click="..._@wangeditor/editor-for-vue 读取data-src 定义的内容

【PCL】的五大依赖库及作用_pcl依赖库-程序员宅基地

文章浏览阅读1.6k次,点赞3次,收藏4次。安装点云PCL库时,需要额外安装5个依赖库;它们有什么作用呢?如下:Boost: 用于共享指针和多线程。Eigen: 一个标准的C++模板库用于线性代数,矩阵,向量等计算。FLANN:(Fast Approximate Nearest Neighbor Search Library), 快速最近邻逼近搜索函数库,可实现快速高效匹配。OpenNI:一个开源的框架,用于3D传感器中间件的应用开发。VTK:三维点云的可视化和渲染。计算机图形学,图像处理,可视化方面的库。..._pcl依赖库

React+Antd实现省、市区级联下拉多选组件(支持只选省不选市)_antd 封装省份组件-程序员宅基地

文章浏览阅读1.4k次,点赞9次,收藏3次。react+antd+实现省、市区级联下拉多选组件_antd 封装省份组件

Microsoft visio 2010 Premium 的激活_visio premium 2010 激活-程序员宅基地

文章浏览阅读1.2w次。1、百度下载Microsoft office ToolKit2.3.2或其他版本,点击office button。2、进去后点击Product keys选项,选择Microsoft office 2010、Retail、visio Premium。3、进Activation选项,tool选择AutoKMS,点击EZ-Activator。4、激活成功。..._visio premium 2010 激活

随便推点

python中def _init_是什么意思_详细解读Python中的__init__()方法-程序员宅基地

文章浏览阅读3.5k次。__init__()方法意义重大的原因有两个。第一个原因是在对象生命周期中初始化是最重要的一步;每个对象必须正确初始化后才能正常工作。第二个原因是__init__()参数值可以有多种形式。因为有很多种方式为__init__()提供参数值,对于对象创建有大量的用例,我们可以看看其中的几个。我们想尽可能的弄清楚,因此我们需要定义一个初始化来正确的描述问题区域。在我们接触__init__()方法之前,无..._def __init__

delphi读取xml中的内容property name传递参数_SpringBoot系列-整合Mybatis(XML配置方式)...-程序员宅基地

文章浏览阅读68次。本文介绍下SpringBoot整合Mybatis(XML配置方式)的过程。本文目录 一、什么是 MyBatis?二、整合方式三、实战四、测试一、什么是 MyBatis? MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型..._"怎么用传递参数"

计算机组成原理学习-实验一 运算器实验(详细、系统)_采用一个74ls181作为alu核心,采用74ls373作为4位操作数a和4位操作数b的锁存器。-程序员宅基地

文章浏览阅读2.1w次,点赞34次,收藏154次。计算机内部关于运算器的实验!(带你了解运算器是如何工作的)在线博主,及时解答~_采用一个74ls181作为alu核心,采用74ls373作为4位操作数a和4位操作数b的锁存器。

linux系统ps命令的参数a与-a表示的讨论-程序员宅基地

文章浏览阅读1.6w次,点赞7次,收藏15次。前言 在刘遄老师所著的《linux就该这么学》中ps 命令用于查看系统中的进程状态,格式为“ps [参数]”。书中对于ps命令有一定的介绍,为了加强自己的理解,所以我在自己的虚拟机上进行了实验,发现输出的和书上讲的不一样,可能是我理解的错了?以下就展开对此的讨论。 在讨论之前,我们先了解以下ps命令的用法。一、ps命令 ps 命令用于查看...

JAVA的Calendar类set月份的时候,月份会比输入的加1_(calendar.month)总是大1-程序员宅基地

文章浏览阅读4.7k次。今天产品跟我反馈后台管理系统上传数据的时候,命名输入的是 2018/11/16,但是上传之后显示的时间是 2018/12/16我用的是Calendar.set(Calendar.MONTH, )我就觉得很奇怪啊,我的代码没问题啊,然后去看数据库的时间戳,发现真的是 2018/12/16那么我们可以将问题锁定到下图的红框框中那么好,现在很显然我们可以改为month-1来修改我们..._(calendar.month)总是大1

crontab 定时执行php脚本文件_crontable 执行php-程序员宅基地

文章浏览阅读919次。什么是Cron和CrontabUnix和Linux系统的各个发行版本基本都支持Cron,Cron /Crontab允许我们在设定的时间自动执行或定时执行某个任务,如应用程序或脚本。更详细的概念和使用方法介绍请点击Cron和Crontab是什么?现在我们要讨论的是,许多的php程序员都可以很快完成Web应用的开发,PHP代码的调试也比PERL或C语言容易很多,不过经常会碰到有php_crontable 执行php

推荐文章

热门文章

相关标签