mybatis之数组与BLOB数据转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28379809/article/details/81460512
mybatis中,当需要将复杂类型,如数组、List等数据保存至数据库时,是无法直接存取的。必须定义自己的类型转换器。即继承BaseTypeHandler类。
在下面的实例中,实现了java中的Integer数组和数据库中BLOB类型字段互相转换的功能。
首先看使用方法:
insert into  user (name, families) values (#{user}, #{familied, jdbcType=BLOB, typeHandler=com.exmple.handler.IntegerArrayHandler})
Handler类的定义
package com.example;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import javax.sql.rowset.serial.SerialBlob;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


/**
 * Integer数组TypeHandler
 * 在数据库和java之间将Integer[]与BLOB类型字段互相转换
 * @author amdin
 * @since WebComment1.0
 */
public class IntegerArrayTypeHandler extends BaseTypeHandler<Integer[]> {

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, Integer[] parameter, JdbcType jdbcType) throws SQLException {
    String str = "";
    for (Integer s : parameter){
      str = str + "***" + s;
    }
    Blob blob = new SerialBlob(str.getBytes());
    ps.setBlob(i, blob);
  }

  @Override
  public Integer[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
    Blob blob = rs.getBlob(columnName);
    String str = new String(blob.getBytes(1, (int)blob.length()));
    String[] strArray = str.split("\\*\\*\\*");
    List<Integer> list = new ArrayList<>();
    for (String s : strArray){
      if (!s.equals("") && !s.equals(null)) {
        list.add(Integer.parseInt(s));
      }
    }

    Integer[] resultArray = new Integer[list.size()];
    return list.toArray(resultArray);
  }

  @Override
  public Integer[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    return new Integer[0];
  }

  @Override
  public Integer[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return new Integer[0];
  }
}

总结:从上面的代码看,使用了***作为分隔符,以此来区分数组的不同项。这当然不是一种好方法,不过确实能解决问题。
更好的方法当然也有,下一节将会介绍任意类型数组与BLOB类型数据的互相映射。

猜你喜欢

转载自blog.csdn.net/qq_28379809/article/details/81460512