14、自定义TypeHandler之String转换为list

本文介绍了如何在MyBatis中自定义TypeHandler,将String转换为List。通过继承BaseTypeHandler,详细展示了StringToListTypeHandler的实现过程,并提供了配置、实体、Mapper的相关代码示例,以及测试方法和输出结果的展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mybatis为我们实现了那么多TypeHandler, 随便打开一个TypeHandler,看其源码,都可以看到,它继承自一个抽象类:BaseTypeHandler, 那么我们是不是也能通过继承BaseTypeHandler,从而实现自定义的TypeHandler ? 答案是肯定的, 那么现在下面就为大家演示一下自定义TypeHandler:

StringToListTypeHandler

package com.lf.typehandle;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LF on 2017/3/9.
 */

@MappedTypes({List.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class StringToListTypeHandler extends BaseTypeHandler<List<String>> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        String str = Joiner.on(",").skipNulls().join(parameter);
        ps.setString(i, str);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.stringToList(rs.getString(columnName));
    }

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

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.stringToList(cs.getString(columnIndex));
    }


    private List<String> stringToList(String str) {
        return Strings.isNullOrEmpty(str) ? new ArrayList<>() : Splitter.on(",").splitToList(str);
    }
}

此处如果不用注解指定jdbcType, 那么,就可以在配置文件中通过”jdbcType”属性指定, 同理, javaType 也可通过 @MappedTypes指定

配置我们的自定义TypeHandler了

  <typeHandlers>
        <!--当配置package的时候,mybatis会去配置的package扫描TypeHandler-->
        <package name="com.lf.typehandle"></package>
    </typeHandlers>

对应的实体和mapper

package com.lf.entity;



@Data
@ToString
@NoArgsConstructor
public class Blog {
    private String id;

    private String title;

    private String url;

    private List<String> userid;

}
package com.lf.dao;


import com.lf.entity.Blog;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface BlogMapper {

    int deleteByPrimaryKey(String id);


    int insertSelective(Blog record);

    Blog selectByPrimaryKey(String id);

    int updateByPrimaryKeySelective(Blog record);

}
<?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.lf.dao.BlogMapper">
  <resultMap id="BaseResultMap" type="com.lf.entity.Blog">
    <id column="id" jdbcType="VARCHAR" property="id" />
    <result column="title" jdbcType="VARCHAR" property="title" />
    <result column="url" jdbcType="VARCHAR" property="url" />
    <result column="userid" jdbcType="VARCHAR" property="userid" />
  </resultMap>
  <sql id="Base_Column_List">
    id, title, url, userid
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from blog
    where id = #{id,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
    delete from blog
    where id = #{id,jdbcType=VARCHAR}
  </delete>

  <insert id="insertSelective" parameterType="com.lf.entity.Blog">
    insert into blog
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="title != null">
        title,
      </if>
      <if test="url != null">
        url,
      </if>
      <if test="userid != null">
        userid,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=VARCHAR},
      </if>
      <if test="title != null">
        #{title,jdbcType=VARCHAR},
      </if>
      <if test="url != null">
        #{url,jdbcType=VARCHAR},
      </if>
      <if test="userid != null">
        #{userid,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.lf.entity.Blog">
    update blog
    <set>
      <if test="title != null">
        title = #{title,jdbcType=VARCHAR},
      </if>
      <if test="url != null">
        url = #{url,jdbcType=VARCHAR},
      </if>
      <if test="userid != null">
        userid = #{userid,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=VARCHAR}
  </update>

</mapper>

数据库的数据

1   偶尔记一下   http://blog.csdn.net/isea533    5,3,3
2   测试  http://www.google.com   1

测试方法

package com.lf;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class App {
    public static void main(String[] args) throws IOException {
        String resouce = "mybatis-config.xml";
        InputStream is = Resources.getResourceAsStream(resouce);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Object one = sqlSession.selectOne("com.lf.dao.BlogMapper.selectByPrimaryKey", "1");
        System.err.println(one);
        sqlSession.commit();
    }
}

输出结果

Blog(id=1, title=偶尔记一下, url=http://blog.youkuaiyun.com/isea533, userid=[5, 3, 3])
<think>好的,我现在需要帮助用户将之前处理List<String>的TypeHandler修改为处理List<Integer>的情况。用户之前提供的代码是将数据库中的字符串用逗号分隔转换List<String>,现在需要处理的是JSON格式存储的数据,并且转换List<Integer>。 首先,我需要明确用户的需求。他们可能在使用MyBatis,并且希望将MySQL中存储的JSON数组映射到Java的List<Integer>类型。原来的代码是将逗号分隔的字符串转换List<String>,但现在数据源是JSON格式,所以需要解析JSON而不是简单的字符串分割。接下来,我需要考虑如何解析JSON。在Java中,常用的JSON库有Jackson、Gson等。这里用户可能希望不引入额外的依赖,或者使用MyBatis自带的处理方式。不过,处理JSON通常需要库的支持,所以可能需要引入比如Jackson的ObjectMapper。 然后,我需要修改原来的TypeHandler。原来的代码中使用StringUtils.join和split方法,但现在需要处理JSON数组。因此,在setParameter方法中,需要将List<Integer>转换为JSON字符串,而不是用逗号连接。而在getResult方法中,需要从结果集中获取JSON字符串,然后解析为List<Integer>。 需要注意的是,数据库中的JSON数据可能是像"[1,2,3]"这样的格式,所以在序列化和反序列化时要确保正确性。使用ObjectMapper可以方便地将List转换为JSON字符串,以及将JSON字符串解析回List<Integer>。 另外,异常处理也很重要。原来的代码中有try-catch块,但可能需要更详细的错误处理,比如在解析失败时抛出异常,而不是仅打印堆栈跟踪。 然后,注册TypeHandler的方式可能也需要调整,确保MyBatis知道在哪个字段上使用这个处理器。可能需要在MyBatis的配置文件中或者通过注解来指定。 最后,测试这个TypeHandler是否正常工作,比如插入和查询数据时是否能正确转换类型,处理空值或无效的JSON数据等情况。 可能用户还关心如何处理数据库中的NULL值,或者JSON格式不正确时的异常处理。此外,是否需要考虑性能问题,比如使用缓存的ObjectMapper实例来提高效率。总结步骤: 1. 修改TypeHandler的泛型类型为List<Integer>。 2.使用JSON库(如Jackson)进行序列化和反序列化。 3. 替换原有的字符串操作为JSON处理。 4.处理可能的异常情况,确保代码健壮性。5. 提供使用示例和相关配置说明。</think>以下是针对MySQL数据库JSON格式数据与Java List<Integer>类型转换的MyBatis TypeHandler实现: ```java @MappedJdbcTypes(JdbcType.VARCHAR) @MappedTypes(List.class) public class JsonToListIntegerTypeHandler implements TypeHandler<List<Integer>> { private static final ObjectMapper objectMapper = new ObjectMapper(); @Override public void setParameter(PreparedStatement ps, int i, List<Integer> parameter, JdbcType jdbcType) throws SQLException { try { String json = objectMapper.writeValueAsString(parameter); ps.setString(i, json); } catch (JsonProcessingException e) { throw new SQLException("Error converting List<Integer> to JSON", e); } } @Override public List<Integer> getResult(ResultSet rs, String columnName) throws SQLException { return parseJson(rs.getString(columnName)); } @Override public List<Integer> getResult(ResultSet rs, int columnIndex) throws SQLException { return parseJson(rs.getString(columnIndex)); } @Override public List<Integer> getResult(CallableStatement cs, int columnIndex) throws SQLException { return parseJson(cs.getString(columnIndex)); } private List<Integer> parseJson(String json) throws SQLException { if (json == null || json.trim().isEmpty()) { return new ArrayList<>(); } try { return objectMapper.readValue(json, new TypeReference<List<Integer>>() {}); } catch (JsonProcessingException e) { throw new SQLException("Error parsing JSON to List<Integer>", e); } } } ``` 代码说明: 1. 使用Jackson的ObjectMapper进行JSON序列化和反序列化 2. JdbcType设置为VARCHAR(MySQL的JSON类型实际存储为字符串) 3. 自定义parseJson方法处理空值和异常 4. 使用TypeReference保持泛型类型信息 5. 异常处理转换为SQLException以符合接口规范 需要添加Jackson依赖(pom.xml): ```xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.3</version> </dependency> ``` MyBatis配置(mybatis-config.xml): ```xml <typeHandlers> <typeHandler handler="com.example.JsonToListIntegerTypeHandler"/> </typeHandlers> ``` 实体类使用示例: ```java public class User { @TableField(typeHandler = JsonToListIntegerTypeHandler.class) private List<Integer> scores; // getter/setter } ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值