一. 测试环境
数据库 : mysql
字段类型:varchar 值为数组类型
实体类对象属性对应类型: String [] 数组类型
查询方式: 两表联查
二. 问题描述
mybatis查询字段类型为数组的字段时,值为空,数据库查询可以查询出来
三 . 已排除的问题
1. 实体类对象属性和sql列名一致
四. 解决方法
1. result 加上 typeHandler 做类型的装换
<result property="specifications" column="specifications" typeHandler="com.test.JsonStringArrayTypeHandler"></result>
2.JsonStringArrayTypeHandler 代码如下
package com.test;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
<columnOverride column="urls" javaType="java.lang.String[]" typeHandler="JsonStringArrayTypeHandler"/>
*/
public class JsonStringArrayTypeHandler extends BaseTypeHandler<String[]> {
private static final ObjectMapper mapper = new ObjectMapper();
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType)
throws SQLException {
ps.setString(i, toJson(parameter));
}
@Override
public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
return this.toObject(rs.getString(columnName));
}
@Override
public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return this.toObject(rs.getString(columnIndex));
}
@Override
public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return this.toObject(cs.getString(columnIndex));
}
private String toJson(String[] params) {
try {
return mapper.writeValueAsString(params);
} catch (Exception e) {
e.printStackTrace();
}
return "[]";
}
private String[] toObject(String content) {
if (content != null && !content.isEmpty()) {
try {
return (String[]) mapper.readValue(content, String[].class);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
return null;
}
}
}