当前位置: 代码网 > it编程>编程语言>Java > MyBatis中TypeHandler的使用教程详解

MyBatis中TypeHandler的使用教程详解

2024年12月02日 Java 我要评论
一.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使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com