MyBatis中TypeHandler的使用教程详解

 更新时间:2024年12月01日 11:40:56   作者:不想做咸鱼的王富贵  
在我们平常开发操作数据库时,查询、插入数据等操作行为,有时会报数据类型不匹配异常,就可以得知数据的类型是不唯一的必然是多种不同的数据类型,本文给大家介绍了MyBatis中TypeHandler的使用教程,需要的朋友可以参考下

一.TypeHandler作用及其使用场景

在我们平常开发操作数据库时,查询、插入数据等操作行为,有时会报数据类型不匹配异常,就可以得知数据的类型是不唯一的必然是多种不同的数据类型。并且我们必须要明确的一点就是java作为一门编程语言有自己的数据类型,数据库也是有自己的数据类型的。

jdbc数据类型:org.apache.ibatis.type.JdbcType 此枚举就是所有的数据库支持类型

java数据类型:int、long、string、…

一定要分清,例如java重的date数据插入到数据库中,应该是已经转换成了数据库的某种类型,必然跟java已经没有关系了。中间有一些我们看不见的操作做了数据处理。

假设此时的java类型与数据库数据类型是一样的,哪么其他语言中的日期数据插入数据库时又该怎么解释,例如C#操作数据库存入时间类型,C#与java肯定没有关系吧。所以每种语言与数据库之间有种数据类型关系对应。

思考:

因为java与数据库各自有数据类型,所以在将java数据存入数据库前中间是否有其他操作,是我们看不见的,不然java数据怎么知道自己与哪个jdbc数据类型匹配?

答:mybatis框架为每种数据类型做了默认的关系对应,BaseTypeHandler的所有实现类,就是来做这些处理的。

例如:java中的date插入数据库时是jdbc哪种类型,怎么就是这种类型? 中间具体有什么操作?

答:DateTypeHandler就是来解决date数据类型的处理。

二.TypeHandler使用

我们想要自定义去处理Java和JDBC的数据类型转换时,需要实现TypeHandler接口,该接口源码如下:

//此接口作用是用于指定jdbc与java的数据类型间对应关系处理。
public interface TypeHandler<T> {
  // 保存操作,数据入库之前时数据处理
  void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
  //下面三个则是,从数据库加载数据后,vo对象封装前的数据处理
  T getResult(ResultSet rs, String columnName) throws SQLException;
  T getResult(ResultSet rs, int columnIndex) throws SQLException;
  T getResult(CallableStatement cs, int columnIndex) throws SQLException;
}

JsonIntegerTypeHandler 实现Integer和字符串互转

public class JsonIntegerTypeHandler extends BaseTypeHandler<Integer> {
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Integer parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, toJson(parameter));
    }

    @Override
    public Integer getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.toObject(rs.getString(columnName));
    }

    @Override
    public Integer getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.toObject(rs.getString(columnIndex));
    }

    @Override
    public Integer getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.toObject(cs.getString(columnIndex));
    }

    private String toJson(Integer params) {
        try {
            String copyObject = IotDbUtils.copyObject(params);
            return copyObject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private Integer toObject(String content) {
        if (content != null && !content.isEmpty()) {
            try {
                System.out.println("1111111111111"+content);
                return (Integer) mapper.readValue(content, Integer.class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }
}

Mapper.xml

查询

查询的时候 你转的那个字段就配置哪个字段

    <resultMap id="DmpDeviceReportResult" type="com.chinaunicom.iotdb.domain.DmpDeviceReportInformation" >
        <result column="Time" property="timestamp" />

        <result column="type" jdbcType="INTEGER"
                property="type" typeHandler="com.chinaunicom.iotdb.handler.JsonIntegerTypeHandler"/>
        

    </resultMap>

  <select id="listDeviceReportInformation" resultMap="DmpDeviceReportResult">
        select trace_id, imei, topic, information, interaction_time,type
        from dmp_device_report_information
        where imei = #{serialNumber}
        <if test="beginTime != null and endTime != null">
            and interaction_time between #{beginTime} and #{endTime}
        </if>
        <if test="traceId != null and traceId != ''">
            and trace_id = #{traceId}
        </if>
        limit #{pageSize}  offset #{pageNum}
    </select>

新增

<insert id="add" parameterType="com.chinaunicom.iotdb.domain.DmpDeviceReportInformation">
        INSERT INTO root.device.dmp_device_report_information
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="null != type ">
                type,
            </if>
            <if test="null != traceId and '' != traceId">
                trace_id,
            </if>
            <if test="null != imei and '' != imei">
                imei,
            </if>
            <if test="null != topic and '' != topic">
                topic,
            </if>
            <if test="null != information and '' != information">
                information,
            </if>
            <if test="null != interactionTime  and '' != interactionTime ">
                interaction_time,
            </if>
            <if test="null != organizationId ">
                organization_id
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="null != type ">
                #{type,typeHandler=com.chinaunicom.iotdb.handler.JsonIntegerTypeHandler },
            </if>
            <if test="null != traceId and '' != traceId">
                #{traceId,typeHandler=com.chinaunicom.iotdb.handler.JsonIntegerTypeHandler },
            </if>
            <if test="null != imei and '' != imei">
                #{imei,typeHandler=com.chinaunicom.iotdb.handler.JsonIntegerTypeHandler },
            </if>
            <if test="null != topic and '' != topic">
                #{topic,typeHandler=com.chinaunicom.iotdb.handler.JsonIntegerTypeHandler },
            </if>
            <if test="null != information and '' != information">
                #{information,typeHandler=com.chinaunicom.iotdb.handler.JsonIntegerTypeHandler },
            </if>
            <if test="null != interactionTime and '' != interactionTime ">
                #{interactionTime,typeHandler=com.chinaunicom.iotdb.handler.JsonIntegerTypeHandler },
            </if>
            <if test="null != organizationId ">
                #{organizationId,typeHandler=com.chinaunicom.iotdb.handler.JsonIntegerTypeHandler },
            </if>
        </trim>
    </insert>

mybatisPlus中使用

类注解 @TableName(autoResultMap = true)
参数注解 @TableField(typeHandler = JsonIntegerTypeHandler.class)

@Data
@TableName(autoResultMap = true)
public class DmpDeviceReportInformation implements Serializable
{
    private static final long serialVersionUID = 1L;

    private Long id;

    /**
     * 消息类型1:消息上报 2:消息下发
     */
 @TableField(typeHandler = JsonIntegerTypeHandler.class)
    private Integer type;
    }

注意: 如果使用自己的mapper查询 要选择mybaits的形式

要想全局生效的话

mybatis-plus:
   type-handlers-package: com.chinaunicom.iotdb.handler

到此这篇关于MyBatis中TypeHandler的使用教程详解的文章就介绍到这了,更多相关MyBatis TypeHandler使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java中的RMI使用方法详解

    Java中的RMI使用方法详解

    这篇文章主要介绍了Java中的RMI使用方法,RMI是Java提供的一个完善的简单易用的远程方法调用框架,采用客户服务器通信方式,在服务器上部署了提供各种服务的远程对象,下面我们来详细讲解
    2023-10-10
  • 详解Spring-Boot中如何使用多线程处理任务

    详解Spring-Boot中如何使用多线程处理任务

    本篇文章主要介绍了详解Spring-Boot中如何使用多线程处理任务,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
    2017-03-03
  • Spring整合Mybatis框架方法剖析

    Spring整合Mybatis框架方法剖析

    这篇文章主要为大家介绍了Spring整合Mybatis框架方法剖析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • Java消息队列JMS实现原理解析

    Java消息队列JMS实现原理解析

    这篇文章主要介绍了Java消息队列JMS实现原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03
  • maven安装、使用、配置本地仓库、idea配置maven以及解决plugins报错问题

    maven安装、使用、配置本地仓库、idea配置maven以及解决plugins报错问题

    本地仓库是远程仓库的一个缓冲和子集,当你构建Maven项目时首先会从本地仓库查找资源,如果没有那么Maven会从远程仓库下载到你本地仓库,这篇文章主要给大家介绍了关于maven安装、使用、配置本地仓库、idea配置maven以及解决plugins报错问题的相关资料,需要的朋友可以参考下
    2024-01-01
  • 手写Java LockSupport的示例代码

    手写Java LockSupport的示例代码

    LockSupport给我们提供了一个非常强大的功能,它是线程阻塞最基本的元语,他可以将一个线程阻塞也可以将一个线程唤醒,因此经常在并发的场景下进行使用。本文将用60行代码实现手写LockSupport,需要的可以参考一下
    2022-08-08
  • MyBatis 核心组件Configuration实例详解

    MyBatis 核心组件Configuration实例详解

    Configuration用于描述 MyBatis 的主配置信息,其他组件需要获取配置信息时,直接通过 Configuration 对象获取,这篇文章主要介绍了MyBatis核心组件Configuration,需要的朋友可以参考下
    2023-08-08
  • 详解Java中的敏感信息处理

    详解Java中的敏感信息处理

    平时开发中常常会遇到像用户的手机号、姓名、身份证等敏感信息需要处理,这篇文章主要为大家整理了一些常用的方法,希望对大家有所帮助
    2025-01-01
  • java二叉树面试题详解

    java二叉树面试题详解

    下面小编就为大家带来一篇java二叉树的几道面试题详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2021-07-07
  • Spring Cloud Hystrix原理与注意事项小结

    Spring Cloud Hystrix原理与注意事项小结

    本文介绍了Hystrix的基本概念、工作原理以及其在实际开发中的应用方式,通过对Hystrix的深入学习,开发者可以在分布式系统中实现精细的错误处理机制,并能够及时响应系统中的异常,避免服务的连锁崩溃,感兴趣的朋友一起看看吧
    2025-03-03

最新评论