当前位置:   article > 正文

Mybatis--TypeHandler使用手册_wrapper 查询中的 typehandler 使用

wrapper 查询中的 typehandler 使用

TypeHandler使用手册

场景:想保存user时 teacher自动转String ,不想每次保存都要手动去转String;从DB查询出来时,也要自动帮我们转换成Java对象 Teacher

@Data
public class User {

    private Integer id;

    private String name;

    private Integer sex;
    
    //这里直接使用数据库无法识别的自定义类型
    private Teacher teacher;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

当然Mybatis给我们提供了接口 TypeHandler(类型映射)

public interface TypeHandler<T> {
  //参数转换
  void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
   //列值转换
  T getResult(ResultSet rs, String columnName) throws SQLException;
	//列值转换
  T getResult(ResultSet rs, int columnIndex) throws SQLException;
	//列值转换
  T getResult(CallableStatement cs, int columnIndex) throws SQLException;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

看看mybatis内置的类型处理器,这就是为什么一些Java的数据类型不用我们手动转换的原因
在这里插入图片描述

我们可以参考String,看他是怎么处理的,发现都是通过原生的jdbc来处理的

public class StringTypeHandler extends BaseTypeHandler<String> {
  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
      throws SQLException {
    ps.setString(i, parameter);
  }

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

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

  @Override
  public String getNullableResult(CallableStatement cs, int columnIndex)
      throws SQLException {
    return cs.getString(columnIndex);
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
实战

我们结合springboot来看,启动容器

server:
  port: 8080
mybatis:
  mapper-locations: classpath:mappers/*.xml
  type-handlers-package: com.example.ssm.demos.web.typeHandler
  • 1
  • 2
  • 3
  • 4
  • 5

创建SqlSessionFactory的时候扫描并注册

public class SqlSessionFactoryBean implements InitializingBean {
    
  @Override
  public void afterPropertiesSet() throws Exception {
    this.sqlSessionFactory = buildSqlSessionFactory();
  }
    
  protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
    if (hasLength(this.typeHandlersPackage)) {
      //在包路径下找到实现TypeHandler的类并注册
      scanClasses(this.typeHandlersPackage, TypeHandler.class).stream().filter(clazz -> !clazz.isAnonymousClass())
          .filter(clazz -> !clazz.isInterface()).filter(clazz -> !Modifier.isAbstract(clazz.getModifiers()))
          .forEach(targetConfiguration.getTypeHandlerRegistry()::register);
    }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

注册并加入缓存

public final class TypeHandlerRegistry {
  private final Map<Type, Map<JdbcType, TypeHandler<?>>> typeHandlerMap = new ConcurrentHashMap<>();
  private final Map<Class<?>, TypeHandler<?>> allTypeHandlersMap = new HashMap<>();
    
  public void register(Class<?> typeHandlerClass) {
    boolean mappedTypeFound = false;
    //如果这个类有注解@MappedTypes,根据注解的指定的类进行有参构造实例化
    MappedTypes mappedTypes = typeHandlerClass.getAnnotation(MappedTypes.class);
    if (mappedTypes != null) {
      for (Class<?> javaTypeClass : mappedTypes.value()) {
        register(javaTypeClass, typeHandlerClass);
        mappedTypeFound = true;
      }
    }
    //没有注解,直接无参构造实例化
    if (!mappedTypeFound) {
      register(getInstance(null, typeHandlerClass));
    }
  }
    
   //加入缓存 
   private void register(Type javaType, JdbcType jdbcType, TypeHandler<?> handler) {
    if (javaType != null) {
      Map<JdbcType, TypeHandler<?>> map = typeHandlerMap.get(javaType);
      if (map == null || map == NULL_TYPE_HANDLER_MAP) {
        map = new HashMap<>();
      }
      map.put(jdbcType, handler);
      typeHandlerMap.put(javaType, map);
    }
    allTypeHandlersMap.put(handler.getClass(), handler);
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

容器启动完成,测试一下

@Mapper
public interface UserMapper {
    public User getUserListByEntity(Integer id);
    public int insertUser(User user);
}
  • 1
  • 2
  • 3
  • 4
  • 5

定义一个Teacher 处理器

public class TeacherTypeHandler extends BaseTypeHandler<Teacher> {

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

    @Override
    public Teacher getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return JSON.parseObject(rs.getString(columnName),Teacher.class);
    }

    @Override
    public Teacher getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return JSON.parseObject(rs.getString(columnIndex),Teacher.class);
    }

    @Override
    public Teacher getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return JSON.parseObject(cs.getString(columnIndex),Teacher.class);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

mapper文件

<?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.example.ssm.demos.web.mapper.UserMapper">
    <sql id="allUserCollun">
        id,name,sex,teacher
    </sql>
    <resultMap id="userMap" type="com.example.ssm.demos.web.pojo.User">
        <id column="id" property="id"></id>
        <result property="name" column="name"></result>
        <result property="sex" column="sex"></result>
        <!-- 指定字段处理器,反序列化成Teacher对象 -->
        <result property="teacher" column="teacher" typeHandler="com.example.ssm.demos.web.typeHandler.TeacherTypeHandler" ></result>
    </resultMap>
    
    <!-- 测试查询 -->
    <select id="getUserListByEntity" resultMap="userMap">
        select
            <include refid="allUserCollun"></include>
        from User
        <where>
            id = #{id}
        </where>
    </select>
    
    <!-- 测试新增 -->
    <insert id="insertUser" parameterType="com.example.ssm.demos.web.pojo.User">
        insert into user(
            <include refid="allUserCollun"></include>
        ) values (
        #{id},#{name},#{sex},
        <!-- 指定字段处理器,转换成json格式的字符串 -->
        #{teacher,typeHandler=com.example.ssm.demos.web.typeHandler.TeacherTypeHandler})
    </insert>
</mapper>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

经过测试,完全没有问题,插入数据库时,自动转 String,查询时,自动转 Teacher

在这里插入图片描述

如果想知道调用位置,参数可以看这个类: org.apache.ibatis.scripting.defaults.DefaultParameterHandler#setParameters

返回值可以看这个类: org.apache.ibatis.executor.resultset.DefaultResultSetHandler#getPropertyMappingValue

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/683347
推荐阅读
相关标签
  

闽ICP备14008679号