You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MyBatis中下划线字段返回null问题求助(SpringMVC+MyBatis环境)

解决MyBatis下划线命名字段返回null的问题

我之前在SpringMVC+MyBatis的项目里也踩过这个坑,给你几个实用的排查和解决方向:

1. 检查ResultMap的完整性

从你贴的mapper.xml片段来看,你的BaseResultMap只配置了employee_code到employeeCode的映射,如果实体类ReportPersonGrouping里还有其他下划线命名的数据库字段(比如group_name、create_time这类),没在ResultMap里对应配置的话,这些字段就会返回null。

确保ResultMap里所有数据库下划线字段都对应到实体类的驼峰属性:

<resultMap id="BaseResultMap" type="com.model.ReportPersonGrouping">
    <result column="employee_code" property="employeeCode" />
    <result column="group_name" property="groupName" />
    <result column="create_time" property="createTime" />
    <!-- 其他需要映射的字段依次补充 -->
</resultMap>

2. 开启自动驼峰命名映射(推荐)

如果不想手动配置每一个字段的映射,可以开启MyBatis的自动驼峰转换功能,这样MyBatis会自动把下划线命名的数据库字段(比如employee_code)映射到驼峰命名的实体类属性(比如employeeCode)。

方式一:在MyBatis核心配置文件(mybatis-config.xml)中添加配置

<configuration>
    <settings>
        <!-- 开启下划线到驼峰的自动映射 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!-- 其他MyBatis配置 -->
</configuration>

方式二:在Spring配置文件中通过SqlSessionFactoryBean配置

如果你的项目是通过Spring管理MyBatis的SqlSessionFactory,可以在applicationContext.xml里添加:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    <!-- 配置自动驼峰映射 -->
    <property name="configurationProperties">
        <props>
            <prop key="mapUnderscoreToCamelCase">true</prop>
        </props>
    </property>
</bean>

3. 验证SQL查询语句是否正确

检查你的select语句是否正确返回了所有需要的字段,有没有漏写或者别名错误。比如如果你的SQL写成:

select employeeCode from report_person_grouping where ...

而数据库里的字段实际是employee_code,这样查询结果里根本没有employee_code列,自然映射到employeeCode会是null。确保SQL里的字段名和数据库一致:

select employee_code, group_name from report_person_grouping where ...

4. 检查实体类的Getter/Setter方法

确保实体类的驼峰属性有正确的Getter和Setter方法,比如employeeCode对应的方法应该是:

public String getEmployeeCode() {
    return employeeCode;
}

public void setEmployeeCode(String employeeCode) {
    this.employeeCode = employeeCode;
}

如果方法名写错了(比如写成getEmployeecode或者setEmployee_code),MyBatis无法正确注入属性值,也会导致返回null。

内容的提问来源于stack exchange,提问作者user9270170

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:29:34