在 MyBatis 中,可以使用 TypeHandler 将数据库中的字符串类型(例如: "405", "404")转换为对应的普通类型(例如: 405, 404)。首先,需要创建一个自定义的 TypeHandler 类来完成转换的逻辑。 首先在你的工程中创建一个类,该类需要继承自 org.apache.ibatis.type.BaseTypeHandler,并实现泛型接口 org.apache.ibatis.type.TypeHandler<T>,其中泛型 T 是要转换的目标类型。在这个自定义的 TypeHandler 类中,需要实现两个方法:setNonNullParameter 和 getNullableResult。 示例代码如下: ```java import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.TypeHandler; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class StringToIntegerTypeHandler extends BaseTypeHandler<Integer> { @Override public void setNonNullParameter(PreparedStatement ps, int i, Integer parameter, JdbcType jdbcType) throws SQLException { ps.setInt(i, parameter); } @Override public Integer getNullableResult(ResultSet rs, String columnName) throws SQLException { String value = rs.getString(columnName); return convertToInteger(value); } @Override public Integer getNullableResult(ResultSet rs, int columnIndex) throws SQLException { String value = rs.getString(columnIndex); return convertToInteger(value); } @Override public Integer getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { String value = cs.getString(columnIndex); return convertToInteger(value); } private Integer convertToInteger(String value) { if (value == null) { return null; } value = value.replaceAll("[^\\d.]", ""); // 去除非数字的字符 return Integer.parseInt(value); } } ``` 然后,在你的 MyBatis 配置文件中,添加一个 typeHandler 元素来注册这个自定义的 TypeHandler。例如,在 mybatis-config.xml 中添加以下内容: ```xml <typeHandlers> <typeHandler handler="com.example.StringToIntegerTypeHandler"/> <!-- 其他自定义 TypeHandler --> </typeHandlers> ``` 这样,当使用 MyBatis 查询数据库时,会自动调用 StringToIntegerTypeHandler 类中相应的方法,将字符串类型转换为普通类型。 上述代码中的自定义 TypeHandler 是针对将字符串转换为整数类型的示例,你可以根据需要修改相应的逻辑,将字符串转换为其他类型。 [2024-04-25 09:10:33 | AI写代码神器 | 2080点数解答]