Mybatis对于类转换器TypeHandler的简单使用

  • 目录

    TypeHandler概念

    MyBatis 内置的 TypeHandler

    如何自定义typehandler 

    自定义demo(亲测有效) 


    TypeHandler概念

  • MyBatis 中的 TypeHandler 类型处理器用于 JavaType 与 JdbcType 之间的转换,用于 PreparedStatement 设置参数值和从 ResultSet 或 CallableStatement 中取出一个值。MyBatis 内置了大部分基本类型的类型处理器,所以对于基本类型可以直接处理,当我们需要处理其他类型的时候就需要自定义类型处理器

  • MyBatis 内置的 TypeHandler

  • 在 MyBatis 的 TypeHandlerRegistry 类型中,可以看到内置的类型处理器。内置处理器比较多,这里整理常见的一些。

    BooleanTypeHandler:用于 java 类型 boolean,jdbc 类型 bit、boolean

    ByteTypeHandler:用于 java 类型 byte,jdbc 类型 TINYINT

    ShortTypeHandler:用于 java 类型 short,jdbc 类型 SMALLINT

    IntegerTypeHandler:用于 INTEGER 类型

    LongTypeHandler:用于 long 类型 

    FloatTypeHandler:用于 FLOAT 类型

    DoubleTypeHandler:用于 double 类型

    StringTypeHandler:用于 java 类型 string,jdbc 类型 CHAR、VARCHAR

    ArrayTypeHandler:用于 jdbc 类型 ARRAY

    BigDecimalTypeHandler:用于 java 类型 BigDecimal,jdbc 类型 REAL、DECIMAL、NUMERIC

    DateTypeHandler:用于 java 类型 Date,jdbc 类型 TIMESTAMP

    DateOnlyTypeHandler:用于 java 类型 Date,jdbc 类型 DATE

    TimeOnlyTypeHandler:用于 java 类型 Date,jdbc 类型 TIME

    对于常见的 Enum 类型,内置了 EnumTypeHandler 进行 Enum 名称的转换和 EnumOrdinalTypeHandler 进行 Enum 序数的转换。这两个类型处理器没有在 TypeHandlerRegistry 中注册,如果需要使用必须手动配置。

  • 作者:程序之心
    链接:https://www.jianshu.com/p/251cb44e2b82
    來源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

  • 如何自定义typehandler 

  1. 两种方式 

            1.1 :可以实现TypeHandler<T>接口

public class MyTypeHandler2 implements TypeHandler<List<String>> {
    public void setParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        StringBuffer sb = new StringBuffer();
        for(String s : strings){
            sb.append(s).append(",");
        }
        preparedStatement.setString(i,sb.toString().substring(0,sb.toString().length() - 1));
    }
 
    public List<String> getResult(ResultSet resultSet, String s) throws SQLException {
        String[] arr = resultSet.getString(s).split(",");
        return Arrays.asList(arr);
    }
 
    public List<String> getResult(ResultSet resultSet, int i) throws SQLException {
        String[] arr = resultSet.getString(i).split(",");
        return Arrays.asList(arr);
    }
 
    public List<String> getResult(CallableStatement callableStatement, int i) throws SQLException {
        String[] arr = callableStatement.getString(i).split(",");
        return Arrays.asList(arr);
    }
}

     1.2:可以继承 BaseTypeHandler<T>

public class MyTypeHandler extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> list, JdbcType jdbcType) throws SQLException {
        StringBuffer sb = new StringBuffer();
        for(String s : list){
            sb.append(s).append(",");
        }
        preparedStatement.setString(i,sb.toString().substring(0,sb.toString().length() - 1));
    }
 
    @Override
    public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String[] arr = resultSet.getString(s).split(",");
        return Arrays.asList(arr);
    }
 
    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String[] arr = resultSet.getString(i).split(",");
        return Arrays.asList(arr);
    }
 
    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String[] arr = callableStatement.getString(i).split(",");
        return Arrays.asList(arr);
    }
}
  • 自定义demo(亲测有效) 

  • 需求:使用mysql5.7新特性,字段属性为json。可存储json格式数据和数组,前端传值使用String,而接收的时候是json或数组,减少对于数据的转换。json----->String[]
  •  数据库

  • 自定义转换类 
package com.timothy.mybatis;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
   <columnOverride column="urls" javaType="java.lang.String[]" typeHandler="JsonStringArrayTypeHandler"/>
 */
@MappedJdbcTypes({JdbcType.VARCHAR})
public class JsonStringArrayTypeHandler extends BaseTypeHandler<String[]> {
    private static final ObjectMapper mapper = new ObjectMapper();

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

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

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

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

    private String toJson(String[] params) {
        try {
            return mapper.writeValueAsString(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "[]";
    }

    private String[] toObject(String content) {
        if (content != null && !content.isEmpty()) {
            try {
                return (String[]) mapper.readValue(content, String[].class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }
}

 

  •  实体类
package com.timothy.generator.pojo;

public class User {
   
    private Integer id;


    private String name;

    private String[] like;

    private String address;

   
    public Integer getId() {
        return id;
    }

  
    public void setId(Integer id) {
        this.id = id;
    }

  
    public String getName() {
        return name;
    }

   
    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

  
    public String[] getLike() {
        return like;
    }

   
    public void setLike(String[] like) {
        this.like = like;
    }

   
    public String getAddress() {
        return address;
    }

   
    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }
}
  • 最重要的是mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.timothy.generator.mapper.UserMapper" >
  <resultMap id="BaseResultMap" type="com.timothy.generator.pojo.User" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="like" property="like" jdbcType="CHAR" typeHandler="com.timothy.mybatis.JsonStringArrayTypeHandler" />
    <result column="address" property="address" jdbcType="CHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    id, name, like, address
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    delete from user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.timothy.generator.pojo.User" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <selectKey resultType="java.lang.Integer" keyProperty="id" order="BEFORE" >
      select uuid_short()
    </selectKey>
    insert into user (id, name, like,
      address)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{like,jdbcType=CHAR,typeHandler=com.timothy.mybatis.JsonStringArrayTypeHandler},
      #{address,jdbcType=CHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.timothy.generator.pojo.User" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <selectKey resultType="java.lang.Integer" keyProperty="id" order="BEFORE" >
      select uuid_short()
    </selectKey>
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      id,
      <if test="name != null" >
        name,
      </if>
      <if test="like != null" >
        like,
      </if>
      <if test="address != null" >
        address,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      #{id,jdbcType=INTEGER},
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="like != null" >
        #{like,jdbcType=CHAR,typeHandler=com.timothy.mybatis.JsonStringArrayTypeHandler},
      </if>
      <if test="address != null" >
        #{address,jdbcType=CHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.timothy.generator.pojo.User" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update user
    <set >
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="like != null" >
        like = #{like,jdbcType=CHAR,typeHandler=com.timothy.mybatis.JsonStringArrayTypeHandler},
      </if>
      <if test="address != null" >
        address = #{address,jdbcType=CHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.timothy.generator.pojo.User" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update user
    set name = #{name,jdbcType=VARCHAR},
      like = #{like,jdbcType=CHAR,typeHandler=com.timothy.mybatis.JsonStringArrayTypeHandler},
      address = #{address,jdbcType=CHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>

  <select id="findById" resultMap="BaseResultMap" parameterType="Integer">
    SELECT * FROM user WHERE  id = 1
  </select>

</mapper>
  •  调用findById
  • 返回结果

 

<think>我们正在讨论MyBatis-Plus中配置TypeHandler使用别名的问题。根据用户的问题,我们需要指导如何在MyBatis-Plus中为TypeHandler配置别名。在MyBatis中,TypeHandler用于处理Java型和JDBC型之间的转换。有时,我们可能希望为自定义的TypeHandler设置一个别名,以便在映射文件中方便地引用。在MyBatis-Plus中,我们可以通过多种方式配置TypeHandler,其中使用别名的方式与Mybatis似。步骤:1.自定义TypeHandler:首先需要编写自己的TypeHandler,实现MybatisTypeHandler接口或继承BaseTypeHandler。2.为TypeHandler设置别名:在Mybatis的配置中,我们可以通过型别名(typeAliases)来为TypeHandler设置别名。3.在映射文件中使用别名:在定义ResultMap或参数映射时,使用别名来引用TypeHandler。但是,在MyBatis-Plus中,我们通常使用注解配置,也可以使用XML配置。参考引用[1]中提到了配置mybatis-config.xml,因此我们可以考虑在mybatis-config.xml中配置别名。示例:步骤1:自定义TypeHandler例如,我们有一个自定义的TypeHandler用于处理List型:```javapublic classListTypeHandler extendsBaseTypeHandler<List<String>>{//实现方法}```步骤2:在mybatis-config.xml中配置别名在<typeAliases>标签下,为TypeHandler设置别名: ```xml<typeAliases><!--其他别名配置--><typeAliastype="com.example.handler.ListTypeHandler"alias="ListTypeHandler"/></typeAliases> ```步骤3:在映射文件中使用在ResultMap中指定某个列使用这个TypeHandler:```xml<result column="tags" property="tags" typeHandler="ListTypeHandler"/>```另外,MyBatis-Plus也支持通过注解来配置TypeHandler。在实体的字段上使用@TableField注解指定typeHandler: ```java@TableField(typeHandler =ListTypeHandler.class) privateList<String> tags; ```但是,这里直接使用名,并没有使用别名。那么,如果我们想用别名怎么办?实际上,在注解中不能直接使用别名,而是必须使用Class对象。因此,在注解方式下,我们无法使用别名。所以,使用别名主要是在XML映射文件中使用。另外,我们还可以在MyBatis-Plus的全局配置中通过配置typeHandler来注册,但这并不是别名的方式。注意:在MyBatis中,我们还可以通过扫描包的方式来注册TypeHandler,这样就不需要为每个TypeHandler单独配置别名。但是,如果我们需要在XML中引用,那么别名可以简化配置。总结:1.在XML配置中使用别名:在mybatis-config.xml中配置别名,然后在XML映射文件中使用别名引用TypeHandler。2.在注解方式下,无法使用别名,只能直接指定TypeHandler。因此,如果用户需要在XML映射文件中使用简短的别名来引用TypeHandler,可以按照上述步骤配置。参考引用[4]中提到了数据库连接的配置,虽然不直接相关,但提醒我们在配置数据库连接时要注意细节。生成相关问题:1.如何在MyBatis-Plus中自定义TypeHandler?2. MyBatis-Plus中如何配置全局的TypeHandler?3.在MyBatis-Plus中,如何通过注解方式指定TypeHandler?4.使用TypeHandler时,如何解决数据库时区问题(如引用[4]中提到的时区问题)?注意:用户的问题集中在“别名”的使用上,因此我们主要解答别名配置的方法。</think>### MyBatis-Plus 中配置 TypeHandler 使用别名的方法 在 MyBatis-Plus 中,通过别名配置 TypeHandler 需要以下步骤: #### 1. **自定义 TypeHandler** 首先创建自定义 TypeHandler (以处理 List<String> 型为例): ```java public class ListTypeHandler extends BaseTypeHandler<List<String>> { @Override public void setNonNullParameter(...) { // 实现JDBC参数设置逻辑 } @Override public List<String> getNullableResult(...) { // 实现结果集转换逻辑 } } ``` #### 2. **配置别名(关键步骤)** 在 `mybatis-config.xml` 中注册别名: ```xml <typeAliases> <!-- 为TypeHandler设置别名 --> <typeAlias type="com.example.handler.ListTypeHandler" alias="ListHandler"/> </typeAliases> ``` #### 3. **在映射中使用别名** ##### 方式1:XML 映射文件 ```xml <resultMap id="userMap" type="User"> <result column="tags" property="tags" typeHandler="ListHandler"/> </resultMap> ``` ##### 方式2:注解方式(需结合 XML 别名) ```java public class User { @TableField(typeHandler = ListHandler.class) // 使用别名 private List<String> tags; } ``` #### 4. **全局配置(可选)** 在 MyBatis-Plus 配置中全局注册: ```java @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 添加其他拦截器... return interceptor; } // 注册TypeHandler @Bean public ConfigurationCustomizer configurationCustomizer() { return configuration -> { configuration.getTypeHandlerRegistry().register(ListHandler.class); // 使用别名 }; } } ``` #### 注意事项: 1. **别名作用域** 别名仅在 MyBatis 配置文件作用域内有效,需确保别名在 `mybatis-config.xml` 中正确定义[^1]。 2. **依赖冲突** 如遇 `ClassNotFoundException`,检查是否缺少 `mybatis-typehandlers-jsr310` 等依赖(似引用[3]中的依赖问题)。 3. **JDBC 参数** 数据库连接需正确配置参数,如 MySQL 时区设置(参考引用[4]): ```properties spring.datasource.url=jdbc:mysql:///db?serverTimezone=Asia/Shanghai ``` 4. **优先级规则** - 字段注解 > XML 映射 > 全局注册 - 自定义 TypeHandler 优先于内置处理器 > **最佳实践**:对于复杂型处理,建议结合 `@MappedTypes` 和 `@MappedJdbcTypes` 注解声明处理器作用范围,减少显式配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值