转换器类
package com.tiger.handler;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
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.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StringAndListTypeHandler extends BaseTypeHandler<List<String>> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameterList, JdbcType jdbcType) throws SQLException {
if (CollectionUtils.isNotEmpty(parameterList)) {
String param = parameterList.stream().map(String::valueOf).collect(Collectors.joining(","));
ps.setString(i, param);
}
}
@Override
public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
String paramStr = rs.getString(columnName);
return splitAndConvert(paramStr);
}
@Override
public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String paramStr = rs.getString(columnIndex);
return splitAndConvert(paramStr);
}
@Override
public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String paramStr = cs.getString(columnIndex);
return splitAndConvert(paramStr);
}
private List<String> splitAndConvert(String paramStr) {
if (StringUtils.isBlank(paramStr)) {
return new ArrayList<>();
} else {
List<String> scopes = Arrays.asList(paramStr.split(","));
return scopes.stream().map(String::valueOf).collect(Collectors.toList());
}
}
}
使用1
mybatis:
type-handlers-package: com.tiger.handler
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
使用2
<result column="JSKC" property="teachCoursesList"
jdbcType="VARCHAR" typeHandler="com.tiger.handler.StringAndListTypeHandler" />