MyBatis 在处理 bigint 类型的数据时,可以使用以下技巧进行转换和映射:
使用 resultMap 自定义映射规则:在 MyBatis 的映射文件中,可以使用 resultMap 标签自定义映射规则。例如,将 bigint 类型的数据映射到 Java 中的 Long 类型:
<id property="id" column="id" /> <result property="yourBigIntField" column="your_bigint_column" javaType="java.lang.Long" jdbcType="BIGINT" /></resultMap>使用 result 标签指定映射规则:在 select 查询语句中,可以使用 result 标签指定映射规则。例如,将 bigint 类型的数据映射到 Java 中的 Long 类型:
SELECT id, your_bigint_column FROM your_table <result property="yourBigIntField" column="your_bigint_column" javaType="java.lang.Long" jdbcType="BIGINT" /></select>使用 MyBatis 的类型处理器(TypeHandler):MyBatis 提供了类型处理器(TypeHandler),可以用于在 Java 类型和 JDBC 类型之间进行转换。对于 bigint 类型的数据,可以创建一个自定义的类型处理器,将其映射到 Java 中的 Long 类型。
首先,创建一个自定义的类型处理器:
import org.apache.ibatis.type.BaseTypeHandler;import org.apache.ibatis.type.JdbcType;import org.apache.ibatis.type.MappedTypes;import java.sql.CallableStatement;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;@MappedTypes(Long.class)public class BigIntToLongTypeHandler extends BaseTypeHandler<Long> { @Override public void setNonNullParameter(PreparedStatement ps, int i, Long parameter, JdbcType jdbcType) throws SQLException { ps.setLong(i, parameter); } @Override public Long getNullableResult(ResultSet rs, String columnName) throws SQLException { long result = rs.getLong(columnName); return result == 0 && rs.wasNull() ? null : result; } @Override public Long getNullableResult(ResultSet rs, int columnIndex) throws SQLException { long result = rs.getLong(columnIndex); return result == 0 && rs.wasNull() ? null : result; } @Override public Long getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { long result = cs.getLong(columnIndex); return result == 0 && cs.wasNull() ? null : result; }}然后,在 MyBatis 配置文件中注册这个类型处理器:
<!-- ... --> <typeHandlers> <typeHandler handler="com.example.BigIntToLongTypeHandler" /> </typeHandlers></configuration>这样,MyBatis 会自动将 bigint 类型的数据映射到 Java 中的 Long 类型。




