1 在mysql 5.7 支持json类型,那么在表实体是怎么运用的
在mybatis-plus 中有相关的handler
/**
* Jackson 实现 JSON 字段类型处理器
*
* @author hubin
* @since 2019-08-25
*/
@Slf4j
@MappedTypes({Object.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class JacksonTypeHandler extends AbstractJsonTypeHandler<Object>
2 对象 json类型 List<字符串> json 类型
@TableField(typeHandler = JacksonTypeHandler.class)
private List<String> tag;
@TableField(typeHandler = JacksonTypeHandler.class)
private Tag tag;
3 List<对象> json 类型
直接用默认的是不行的,虽然查询没有问题,但是对List操作是会有类型转换异常
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.ruleengine.model.rules.SeriesModel
那么我要自定义handler
1 ListTypeHandler
@MappedJdbcTypes(JdbcType.VARBINARY)
@MappedTypes( {List.class})
public abstract class ListTypeHandler<T> extends BaseTypeHandler<List<T>> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int parameterIndex, List<T> parameter, JdbcType jdbcType)
throws SQLException {
String content = CollUtil.isEmpty(parameter) ? null : JSON.toJSONString(parameter);
preparedStatement.setString(parameterIndex, content);
}
@Override
public List<T> getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
return this.getListByJsonArrayString(resultSet.getString(columnName));
}
@Override
public List<T> getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
return this.getListByJsonArrayString(resultSet.getString(columnIndex));
}
@Override
public List<T> getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
return this.getListByJsonArrayString(callableStatement.getString(columnIndex));
}
private List<T> getListByJsonArrayString(String content) {
return StrUtil.isBlank(content) ? new ArrayList<>() : JSON.parseObject(content, this.specificType());
}
/**
* 具体类型,由子类提供
*
* @return 具体类型
*/
protected abstract TypeReference<List<T>> specificType();
}
2 SeriesModelListTypeHandler
public class SeriesModelListTypeHandler extends ListTypeHandler<SeriesModel> {
@Override
protected TypeReference<List<SeriesModel>> specificType() {
return new TypeReference<List<SeriesModel>>() { };
}
}
3 运用
@TableField(typeHandler = SeriesModelListTypeHandler.class)
private List<SeriesModel> series;
标签:return,自定义,TypeHandler,List,class,content,JSON,public
From: https://www.cnblogs.com/linzm14/p/17893677.html