Before the article published in a mybaits operation json mysql in today to mention the use of custom data processing classes before appearing.
List operations today take as a test array, in the past, we need to save to the database or database type when converted or taken out of value to do some processing, so very inconvenient, where we can inherit BaseTypeHandler <T>, to achieve their own various conversion.
See Below is the source List <String> type conversion. Setxxx a method, which represents the setting value to PreparedStatement. Three getxxx method, is to obtain a value according to the column name, a column index is acquired value according to the position of the last one is a stored procedure.
package com.inspur.archives.dao.handler; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import edu.emory.mathcs.backport.java.util.Arrays; @SuppressWarnings("unchecked") public class ListTypeHandler extends BaseTypeHandler<List<String>>{ @Override public void setNonNullParameter(PreparedStatement ps, int i, List<String> param, JdbcType jdbcType) throws SQLException { String str = String.join("", param); ps.setString(i, str); } @Override public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException { String result = rs.getString(columnName); return Arrays.asList(result.split(",")); } @Override public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException { String result = rs.getString(columnIndex); return Arrays.asList(result.split(",")); } @Override public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { String result = cs.getString(columnIndex); return Arrays.asList(result.split(",")); } }
In the mapper.xml
When using insert data
#{filed, typeHandler=*.*.ListTypeHandler}
Custom data fetch time resultMap
<result column="column_filed" typeHandler="*.*.ListHandler" property="field" />