使用 MyBatis,通常会使用 MyBatis Generator 插件逆向生成一套接口和.xml映射文件, 来简化数据库SQL操作。在使用 selectByExample(RecordExample example)
进行数据库的查找时,发现长字段(实践时为 description varchar(256)
)获取结果为 null
。而其他字段则正常,查看该方法对应的xml配置文件如下:
<select id="selectByExample" parameterType="cn.novalue.community.model.QuestionExample" resultMap="BaseResultMap">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 01 15:04:56 CST 2019.
-->
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from QUESTION
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
可以看到 selectByExample
方法返回的是 BaseResultMap,查看 BaseResultMap,如下:
<resultMap id="BaseResultMap" type="cn.novalue.community.model.Question">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sun Dec 01 15:04:56 CST 2019.
-->
<id column="ID" jdbcType="INTEGER" property="id" />
<result column="TITLE" jdbcType="VARCHAR" property="title" />
<result column="GMT_CREATE" jdbcType="BIGINT" property="gmtCreate" />
<result column="GMT_MODIFIED" jdbcType="BIGINT" property="gmtModified" />
<result column="CREATOR" jdbcType="INTEGER" property="creator" />
<result column="COMMENT_COUNT" jdbcType="INTEGER" property="commentCount" />
<result column="VIEW_COUNT" jdbcType="INTEGER" property="viewCount" />
<result column="LIKE_COUNT" jdbcType="INTEGER" property="likeCount" />
<result column="TAG" jdbcType="VARCHAR" property="tag" />
</resultMap>
发现其中缺少 description
的映射,在浏览xml文件时,查看 selectByExampleWithBLOBs
对应的xml文件,如下:
<select id="selectByExampleWithBLOBs" parameterType="cn.novalue.community.model.QuestionExample" resultMap="ResultMapWithBLOBs">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
,
<include refid="Blob_Column_List" />
from QUESTION
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
这个方法返回的是的 ResultMapWithBLOBs,查看 ResultMapWithBLOBs 的定义:
<resultMap id="ResultMapWithBLOBs" type="cn.novalue.community.model.Question" extends="BaseResultMap">
<result column="param_data" property="paramData" jdbcType="LONGVARCHAR"/>
</resultMap>
ResultMapWithBLOBs 继承自 BaseResultMap,不过它有额外的 paramData
属性,并且指定的jdbcType为 LONGVARCHAR
类型,jdbcType是 JDBC 所需要的。
总结:
- Mybatis 使用 ResultMapWithBLOBs 来接收有长字段的查询结果,所以如果数据库有长字段,要用
selectByExampleWithBLOBs
方法查询,没有长字段时,使用selectByExample
方法即可。 - 如果不需要在使用 Mybatis Generator 逆向时针对长字段类型生成 ResultMapWithBLOBs,可以在配置文件中指明映射类型:
<table tableName="question" domainObjectName="Question" >
<columnOverride column="param_data" javaType="java.lang.String" jdbcType="VARCHAR" />
</table>