import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import backStage.exception.SystemException;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@MappedTypes({List.class})
public class ListTypeHandler extends BaseTypeHandler<List> {
private final ObjectMapper mapper = new ObjectMapper();
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
try {
if (list != null && list.size() > 0) {
String value = this.mapper.writeValueAsString(list);
preparedStatement.setString(i, value);
}
} catch (JsonProcessingException e) {
throw new SystemException(e);
}
}
@Override
public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
List list = new ArrayList();
String value = resultSet.getString(s);
try {
if (!StringUtils.isBlank(value)) {
list = this.mapper.readValue(value, List.class);
}
} catch (IOException e) {
throw new SystemException(e);
}
return list;
}
@Override
public List getNullableResult(ResultSet resultSet, int i) {
return null;
}
@Override
public List getNullableResult(CallableStatement callableStatement, int i) {
return null;
}
}
注意:如要先数据库存储map格式的数据应该对前台传回的String字符串做如下处理
new ObjectMapper().writeValueAsString(string)