使用 MyBatis 執行 SQL 查詢時,返回對象的部分屬性為 null,但在數據庫直接執行 SQL 卻能正常返回所有字段。經排查發現是映射配置問題。
<select id="selectByArticle" parameterType="com.pet.bean.Article" resultMap="com.pet.bean.Article">
SELECT * FROM ARTICLE
<include refid="queryCondition"/>
</select>
<sql id="queryCondition">
<if test="@org.apache.commons.lang.StringUtils@isNotBlank(id)">AND ID = #{id,jdbcType=INTEGER}</if>
<if test="@org.apache.commons.lang.StringUtils@isNotBlank(authorName)">AND AUTHOR_NAME = #{authorName,jdbcType=VARCHAR}</if>
<!-- 其他條件省略 -->
</sql>
關鍵錯誤: resultMap="com.pet.bean.Article" 直接使用類全限定名,MyBatis 會嘗試按屬性名自動匹配列名,但數據庫列名(如 AUTHOR_NAME)與 Java 屬性名(authorName)命名風格不一致,導致映射失敗。


<select id="selectByArticle" parameterType="com.pet.bean.Article" resultMap="BaseResultMap">
SELECT * FROM ARTICLE
<include refid="queryCondition"/>
</select>
<resultMap id="BaseResultMap" type="com.pet.bean.Article">
<id column="ID" jdbcType="INTEGER" property="id"/>
<result column="AUTHOR_NAME" jdbcType="VARCHAR" property="authorName"/>
<result column="TITLE" jdbcType="VARCHAR" property="title"/>
<result column="CONTENT" jdbcType="VARCHAR" property="content"/>
<result column="MAKE_TIME" jdbcType="VARCHAR" property="makeTime"/>
<result column="UPDATE_TIME" jdbcType="VARCHAR" property="updateTime"/>
<result column="KIND" jdbcType="VARCHAR" property="kind"/>
<result column="ABOUT" jdbcType="VARCHAR" property="about"/>
</resultMap>

| 配置方式 | 映射機制 | 適用場景 |
|---|---|---|
resultType | 自動映射:列名轉駝峰(需開啟 mapUnderscoreToCamelCase=true) | 列名與屬性名符合駝峰規約 |
resultMap(顯式) | 手動指定 column → property 映射 | 列名不規範、複雜關聯、嵌套結果 |
resultMap="類全名" | 錯誤用法:MyBatis 視為 resultMap id,找不到則退化為 resultType 行為 | 無 |
mybatis-config.xml 中設置 <setting name="mapUnderscoreToCamelCase" value="true"/>,配合 resultType 使用<id> 標識主鍵列,有助於結果集去重與嵌套查詢性能優化