使用MyBatis-Plus处理JSON数组转为List<Integer>,可以通过自定义TypeHandler实现。 1. 创建自定义TypeHandler: ```java 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; import java.util.List; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonIntegerListTypeHandler extends BaseTypeHandler<List<Integer>> { private static final ObjectMapper objectMapper = new ObjectMapper(); @Override public void setNonNullParameter(PreparedStatement ps, int i, List<Integer> parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, toJson(parameter)); } @Override public List<Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException { return parseJson(rs.getString(columnName)); } @Override public List<Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return parseJson(rs.getString(columnIndex)); } @Override public List<Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return parseJson(cs.getString(columnIndex)); } private String toJson(List<Integer> list) { try { return objectMapper.writeValueAsString(list); } catch (Exception e) { throw new RuntimeException("Failed to convert list to JSON", e); } } private List<Integer> parseJson(String json) { if (json == null || json.trim().isEmpty()) { return null; } try { return objectMapper.readValue(json, new TypeReference<List<Integer>>() {}); } catch (Exception e) { throw new RuntimeException("Failed to parse JSON to list", e); } } } ``` 2. 在实体类字段上使用TypeHandler: ```java import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import java.util.List; @TableName("your_table") public class YourEntity { @TableField(value = "json_array_column", typeHandler = JsonIntegerListTypeHandler.class) private List<Integer> integerList; // getter和setter方法 public List<Integer> getIntegerList() { return integerList; } public void setIntegerList(List<Integer> integerList) { this.integerList = integerList; } } ``` 3. 确保数据库字段类型为能够存储JSON字符串的类型(如VARCHAR或TEXT)。 我在以往的开发过程中,碰到过以下几点需要格外小心处理的地方: - JSON字符串格式必须正确,否则解析会失败导致异常。 - 数据库字段长度需足够存储序列化后的JSON字符串,避免数据截断。 - 使用Jackson库时确保版本兼容性,避免因版本问题导致序列化或反序列化错误。 [2025-08-26 11:26:36 | AI写代码神器 | 656点数解答]