在 MyBatis 的映射文件中使用 Decimal 类型时,需要注意以下几点技巧:
<resultMap id="resultMap" type="com.example.User"> <id property="id" column="id" /> <result property="salary" column="salary" jdbcType="DECIMAL" javaType="java.math.BigDecimal"/> </resultMap> <select id="getUserById" parameterType="int" resultType="com.example.User"> SELECT * FROM user WHERE id = #{id, jdbcType=DECIMAL} </select> public class BigDecimalTypeHandler extends BaseTypeHandler<BigDecimal> { @Override public void setNonNullParameter(PreparedStatement ps, int i, BigDecimal parameter, JdbcType jdbcType) throws SQLException { ps.setBigDecimal(i, parameter); } @Override public BigDecimal getNullableResult(ResultSet rs, String columnName) throws SQLException { return rs.getBigDecimal(columnName); } @Override public BigDecimal getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return rs.getBigDecimal(columnIndex); } @Override public BigDecimal getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return cs.getBigDecimal(columnIndex); } } 然后在 MyBatis 的配置文件中注册该 TypeHandler:
<typeHandlers> <typeHandler handler="com.example.BigDecimalTypeHandler"/> </typeHandlers> 通过以上技巧,可以在 MyBatis 的映射文件中灵活地使用 Decimal 类型,并且处理不同数据库字段类型之间的转换。