1.实体类
@Data
public class User implements Serializable {
private Integer id;
private String userName;
private String realName;
private String password;
private Integer age;
private Integer dId;
private ArrayList<String> hobbies;
}
2.自定义类型处理器
@MappedJdbcTypes(JdbcType.VARCHAR) @MappedTypes(ArrayList.class) public class MyTypeHandler extends BaseTypeHandler<ArrayList<String>> { @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, ArrayList<String> strings, JdbcType jdbcType) throws SQLException { StringBuffer stringBuffer = new StringBuffer(); for (int i1 = 0; i1 < strings.size(); i1++) { stringBuffer.append(strings.get(i)+","); } preparedStatement.setString(i,stringBuffer.toString()); } @Override public ArrayList<String> getNullableResult(ResultSet resultSet, String s) throws SQLException { ArrayList<String> result = new ArrayList<String>(); String string = resultSet.getString(s); String[] split = string.split(","); for (int i = 0; i < split.length; i++) { result.add(split[i]); } return result; } @Override public ArrayList<String> getNullableResult(ResultSet resultSet, int n) throws SQLException { ArrayList<String> result = new ArrayList<String>(); String string = resultSet.getString(n); String[] split = string.split(","); for (int i = 0; i < split.length; i++) { result.add(split[i]); } return result; } @Override public ArrayList<String> getNullableResult(CallableStatement callableStatement, int n) throws SQLException { ArrayList<String> result = new ArrayList<String>(); String string = callableStatement.getString(n); String[] split = string.split(","); for (int i = 0; i < split.length; i++) { result.add(split[i]); } return result; } }
3.xml配置
<resultMap id="BaseResultMap" type="user"> <id property="id" column="id" jdbcType="INTEGER"/> <result property="userName" column="user_name" jdbcType="VARCHAR" /> <result property="realName" column="real_name" jdbcType="VARCHAR" /> <result property="password" column="password" jdbcType="VARCHAR"/> <result property="age" column="age" jdbcType="INTEGER"/> <result property="hobbies" column="hobbies" jdbcType="VARCHAR" typeHandler="com.dxy.learn.type.MyTypeHandler"/> </resultMap> <select id="selectUserById" resultMap="BaseResultMap" statementType="PREPARED" > select * from t_user where id = #{id} </select>
4.测试