对与采集别人接口数据时,返回格式Json中常常会出现数组类型,如
这时候用jackson去解析数据当然要用List type 来封装,但是我们又不想为这个type单独建一个数据表来存储他,就想用一个varchar字段就把这段数组字符串化的存于数据库。用mybatis-plus的话,直接用List 去对应varchar会报错,这时候我们要告诉mybatis如何把List存入varchar了。
这时候我们要自定义typeHandler,自定义typeHandler可以通过实现TypeHandler接口来实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 @MappedJdbcTypes(JdbcType.VARCHAR) @MappedTypes(List.class) public class ListToVarcharTypeHandler implements TypeHandler <List<String>> { @Override public void setParameter (PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException { StringBuffer sb = new StringBuffer (); for (int j = 0 ; j < strings.size(); j++) { if (j == strings.size() - 1 ) { sb.append(strings.get(j)); } else { sb.append(strings.get(j)).append("," ); } } preparedStatement.setString(i, sb.toString()); } @Override public List<String> getResult (ResultSet resultSet, String s) throws SQLException { String resultString = resultSet.getString(s); if (StringUtils.isNotEmpty(resultString)) { return Arrays.asList(resultString.split("," )); } return null ; } @Override public List<String> getResult (ResultSet resultSet, int i) throws SQLException { String resultString = resultSet.getString(i); if (StringUtils.isNotEmpty(resultString)) { return Arrays.asList(resultString.split("," )); } return null ; } @Override public List<String> getResult (CallableStatement callableStatement, int i) throws SQLException { String resultString = callableStatement.getString(i); if (StringUtils.isNotEmpty(resultString)) { return Arrays.asList(resultString.split("," )); } return null ; } }
在配置文件中注明自定义typehandler的包路径

在实体类中加入注解来标明这个字段用此typehandler来使用

以下就可以把实体类中List存入数据库中的varchar了