package org.sxkj.common.handler; 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 java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * String 与 smallint/int 的类型转换处理器 * 用于 Java 字段为 String 但数据库列为 smallint/int 的场景 * 写入时将 String 转为 Integer,读取时将 Integer 转为 String */ @MappedTypes(String.class) @MappedJdbcTypes(JdbcType.SMALLINT) public class StringToIntegerTypeHandler extends BaseTypeHandler { @Override public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { ps.setInt(i, Integer.parseInt(parameter)); } @Override public String getNullableResult(ResultSet rs, String columnName) throws SQLException { Object value = rs.getObject(columnName); return value == null ? null : value.toString(); } @Override public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { Object value = rs.getObject(columnIndex); return value == null ? null : value.toString(); } @Override public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { Object value = cs.getObject(columnIndex); return value == null ? null : value.toString(); } }