先定义一个ListTypeHandler
package com.fiture.marine.utils;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
@MappedJdbcTypes(JdbcType.VARBINARY)
@MappedTypes({List.class})
public abstract class ListTypeHandler extends BaseTypeHandler> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List parameter, JdbcType jdbcType)
throws SQLException {
String content = CollectionUtils.isEmpty(parameter) ? null : JSON.toJSONString(parameter);
ps.setString(i, content);
}
@Override
public List getNullableResult(ResultSet rs, String columnName) throws SQLException {
return this.getListByJsonArrayString(rs.getString(columnName));
}
@Override
public List getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return this.getListByJsonArrayString(rs.getString(columnIndex));
}
@Override
public List getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return this.getListByJsonArrayString(cs.getString(columnIndex));
}
private List getListByJsonArrayString(String content) {
return StringUtils.isBlank(content) ? new ArrayList<>() : JSON.parseObject(content, this.specificType());
}
protected abstract TypeReference> specificType();
}
泛型为需要Json转换为的目标实体对象
package com.fiture.marine.utils; import java.util.List; import com.alibaba.fastjson.TypeReference; import com.fiture.marine.wechat.pojo.dto.AttachmentAddDTO; public class AttachmentListTypeHandler extends ListTypeHandler{ @Override protected TypeReference > specificType() { return new TypeReference
>() {}; } }
使用
@TableField(value = "attachments", typeHandler = AttachmentListTypeHandler.class)
private List attachments;



