Mybatis多表查询,报错:Column 'id' in field list is ambiguous
Mybatis多表查询,报错:Column 'id' in field list is ambiguous
Mybatis错误示例:
<resultMap id="JoinResultMap" type="com.WorkDto">
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="work_city_code" jdbcType="VARCHAR" property="workCityCode"/>
<collection property="guardInfos" ofType="com.GuardInfo">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="work_id" jdbcType="BIGINT" property="workId" />
<result column="guarder_code" jdbcType="VARCHAR" property="guarderCode" />
</collection>
</resultMap>
<select id="selectById" parameterType="java.lang.Long" resultMap="JoinResultMap">
select t1.id, work_city_code,
t2.id , t2.work_id, t2.guarder_code
from tt_work t1
left join tt_work_info t2
on t1.id=t2.work_id
where id = #{id,jdbcType=BIGINT}
</select>
以上会报错:Column 'id' in field list is ambiguous
错误原因:
Mybatis 多表查询时,多个表有相同名字的字段,比如 id,名字重复,没有指定对应的表名。
有两个地方需要注意:
(1)将其中一个重复字段的 Mybatis的 column 修改为其他的名字。
(2)字段加上对应的表名。
修改如下:
以下将
(1)其中一个id对应的 column 修改为其他的不重复的名称 guarder_info_id
(2)给查询结果和查询条件中的 id 加上表名 t1.id
<resultMap id="JoinResultMap" type="com.WorkDto">
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="work_city_code" jdbcType="VARCHAR" property="workCityCode"/>
<collection property="guardInfos" ofType="com.GuardInfo">
<id column="guarder_info_id" jdbcType="BIGINT" property="id" />
<result column="work_id" jdbcType="BIGINT" property="workId" />
<result column="guarder_code" jdbcType="VARCHAR" property="guarderCode" />
</collection>
</resultMap>
<select id="selectById" parameterType="java.lang.Long" resultMap="JoinResultMap">
select t1.id, work_city_code,
t2.id as guarder_info_id, t2.work_id, t2.guarder_code
from tt_work t1
left join tt_work_info t2
on t1.id=t2.work_id
where t1.id = #{id,jdbcType=BIGINT}
</select>
分类:
其他--mybatis
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2016-05-30 java多线程与并发笔记
2016-05-30 java常用代码
2016-05-30 java学习笔记整理
2016-05-30 Android笔记:intent