|
在MyBatis-Plus中读取带有下划线的私有字段(如bandwidth_number),可通过以下方案实现:
关闭自动驼峰命名转换
在application.yml中配置:
mybatis-plus:
configuration:
map-underscore-to-camel-case: false
或通过Java配置类:
@Bean
public MybatisConfiguration mybatisConfiguration() {
MybatisConfiguration config = new MybatisConfiguration();
config.setMapUnderscoreToCamelCase(false);
return config;
}
此方法直接保持数据库字段与实体类字段名一致。
使用@TableField注解显式映射
在实体类中指定数据库字段名:
@TableField("bandwidth_number")
private Integer bandwidth_number;
确保MyBatis-Plus使用精确匹配而非驼峰转换。
自定义结果映射(ResultMap)
在Mapper XML中手动定义字段映射:
<resultMap id="customMap" type="YourEntity">
<result column="bandwidth_number" property="bandwidth_number"/>
</resultMap>
适用于复杂场景或需要兼容历史代码的情况。
反射工具类辅助方案
若需直接访问私有字段,可封装工具类:
public class FieldAccessor {
public static Object getFieldValue(Object obj, String fieldName)
throws NoSuchFieldException, IllegalAccessException {
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(obj);
}
}
调用示例:FieldAccessor.getFieldValue(entity, "bandwidth_number")。
SQL别名转换
在查询SQL中使用别名保持一致性:
SELECT bandwidth_number AS bandwidth_number FROM table
此方法需配合@TableField注解使用。
最佳实践建议:
生产环境优先采用方案2(@TableField注解)
需要动态字段访问时选择方案4(反射工具)
避免同时开启驼峰转换和下划线字段混用
|
|