温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

mybatis之BaseTypeHandler怎么使用

发布时间:2023-05-08 17:31:53 来源:亿速云 阅读:148 作者:iii 栏目:开发技术

本篇内容主要讲解“mybatis之BaseTypeHandler怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“mybatis之BaseTypeHandler怎么使用”吧!

    BaseTypeHandler用法

    BaseTypeHandler 是个抽象类,需要子类去实现其定义的 4 个抽象方法,而它本身实现了 typeHandler 接口的 4 个方法。

    可以对数据保存与查询时做出相应处理,类似操作数据库之间的一个拦截器

    举栗子:把集合类型当string存起来,读取的时候映射为list集合

    首先自定义handler 继承BaseTypeHandler重写他里边的四个方法

    public abstract void setNonNullParameter(PreparedStatement var1, int var2, T var3, JdbcType var4) throws SQLException;
     
    public abstract T getNullableResult(ResultSet var1, String var2) throws SQLException;
     
    public abstract T getNullableResult(ResultSet var1, int var2) throws SQLException;
     
    public abstract T getNullableResult(CallableStatement var1, int var2) throws SQLException;

    代码如下

    public class ListToStringHandler extends BaseTypeHandler<List> {
     
        @Override
        public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
            preparedStatement.setString(i, JSON.toJSONString(list));
        }
     
        @Override
        public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
            return JSONArray.parseArray(resultSet.getString(s));
        }
     
        @Override
        public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
            return JSONArray.parseArray(resultSet.getString(i));
        }
     
        @Override
        public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
            return JSONArray.parseArray(callableStatement.getString(i));
        }
    }

    映射操作

    mybaits-plus 方式

    bean上添加注解

    @TableName(autoResultMap = true)

    映射字段上添加如下注解,指定自定义的handler

    @TableField(jdbcType = JdbcType.VARCHAR, typeHandler = ListToStringHandler.class)

    mybaits的方式

    <resultMap> 标签内 映射字段的handler 指定自定义的handler即可,保存的时候也要指定。

    测试

    mybatis之BaseTypeHandler怎么使用

    mybatis之BaseTypeHandler怎么使用

    mybatis之BaseTypeHandler怎么使用

    这只是其一种简单的用法,其他的比如加密解密也适用。

    通过BaseTypeHandler从mysql数据库存取json字符串

    在mysql的使用过程中,我们经常会将一些json串存入mysql当中,如下json串

    {
        "params":[
            {
                "name":"zl",
                "age":18,
                "createTime":"2020-06-19 09:28:38",
                "modifyTime":"2020-06-19 09:29:07"
            }
        ],
        "paramsTypes":[
            "com.zl.platform.student"
        ]
    }

    对于这种数据在mybatis的存取过程需要一些特殊的处理,我们可以通过继承mybatis的org.apache.ibatis.type.BaseTypeHandler来实现。

    首先我们需要完成一个工具类

    import com.alibaba.fastjson.JSON;
    import org.apache.ibatis.type.BaseTypeHandler;
    import org.apache.ibatis.type.JdbcType;
    
    import java.sql.CallableStatement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    /**
     * @Author: zl
     */
    public class JsonTypeHandler<T> extends BaseTypeHandler<T> {
    
        private Class<T> type;
        public JsonTypeHandler(Class<T> type) {
            if (type == null) {
                throw new IllegalArgumentException("Type argument cannot be null");
            }
            this.type = type;
        }
    
        @Override
        public void setNonNullParameter(PreparedStatement ps, int i, Object parameter,
                                        JdbcType jdbcType) throws SQLException {
    
            ps.setString(i, JSON.toJSONString(parameter));
        }
    
        @Override
        public T getNullableResult(ResultSet rs, String columnName)
                throws SQLException {
    
            return JSON.parseObject(rs.getString(columnName), type);
        }
    
        @Override
        public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    
            return JSON.parseObject(rs.getString(columnIndex), type);
        }
    
        @Override
        public T getNullableResult(CallableStatement cs, int columnIndex)
                throws SQLException {
    
            return JSON.parseObject(cs.getString(columnIndex), type);
        }
    }

    然后在mybatis中对需要使用json格式的字段引用这个方法

        <resultMap id="BaseResultMap" type="com.zl.platform.entity.demo.DubboControllerInfo">
            <id column="id" property="id" />
            <result column="department" property="department" />
            <result column="case_name" property="caseName"/>
            <result column="author" property="author" />
            <result column="service_name" property="serviceName" />
            <result column="method_name" property="methodName" />
            <result column="dubbo_params" property="dubboParams" typeHandler="com.zl.platform.utils.JsonTypeHandler"/>
            <result column="create_time" property="createTime" />
            <result column="update_time" property="updateTime" />
        </resultMap>
        
        <insert id="insertDubboInfo"  parameterType="com.zl.platform.entity.demo.DubboControllerInfo">
          insert into dubbo_controller_info (department, author, service_name,
          method_name, dubbo_params,create_time, update_time)
          VALUES (#{department},#{author},#{serviceName},#{methodName},#{dubboParams,typeHandler=com.zl.platform.utils.JsonTypeHandler},
           #{createTime},#{updateTime})
        </insert>
    
        <select id="selectAll" resultMap="BaseResultMap">
            select * from dubbo_controller_info
        </select>

    到此,相信大家对“mybatis之BaseTypeHandler怎么使用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI