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

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 parameter, JdbcType jdbcType) throws SQLException {
        String str = Joiner.on(",").skipNulls().join(parameter);
        ps.setString(i, str);
    }

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

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

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


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

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

配置我们的自定义TypeHandler了

  <typeHandlers>
        
        <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 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);

}


<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.csdn.net/isea533, userid=[5, 3, 3])

你可能感兴趣的:(Mybatis源码解析)