Mybatis使用distinct问题及处理
作者:木灵木灵
Mybatis使用distinct查询时,插件自动生成的sql可能少去掉一行,导致查询不到期望的结果,修复方法是在生成的sql中去掉"Base_Column_List"
Mybatis使用distinct问题
使用插件自动生成sql
具体如下:
<resultMap id="versioncodeResult" type="java.lang.String" >
<result column="code" property="code" jdbcType="VARCHAR" />
</resultMap>
<select id="selectVersionCodeByParam" parameterType="com.entity.OdpsrequesttoidbtableParam" resultMap="versioncodeResult">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
-->
select
<if test="distinct">
distinct
</if>
versioncode as code
<include refid="Base_Column_List" />
from odpsrequesttoidbtable
<if test="_parameter != null">
<include refid="Param_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
<if test="page">
limit #{pageIndex},#{pageSize}
</if>
</select>
始终查询不到我想要的结果
| 序号 | code |
|---|---|
| 1 | 266 |
| 2 | 267 |
查看具体生成的sql发现
少去掉了一行
### SQL: select distinct versioncode as code id, gmt_create, gmt_modified, apiname, pkey, versioncode, appkey from odpsrequesttoidbtable WHERE ( appkey = ? )
修复后的sql如下
去掉"Base_Column_List" :
<select id="selectVersionCodeByParam" parameterType="com.entity.OdpsrequesttoidbtableParam" resultMap="versioncodeResult">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
-->
select
<if test="distinct">
distinct
</if>
versioncode as code
from odpsrequesttoidbtable
<if test="_parameter != null">
<include refid="Param_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
<if test="page">
limit #{pageIndex},#{pageSize}
</if>
</select>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
