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>

posted on 2022-05-30 00:08  乐之者v  阅读(1180)  评论(0编辑  收藏  举报

导航