[Mybatis错误集锦] 如何解决两张表中字段相同冲突问题

本文介绍了解决MyBatis中因多表查询导致字段冲突的问题,通过为冲突字段添加别名并在resultMap中引用这些别名,确保了查询结果能够正确地映射到Java对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

表结构

t_employee表(员工表)
t_employee表

t_department表(部门表)
t_department表

查询的xml映射

EmployeeMapper.xml

<resultMap id="BaseAndDepartmentResultMap" type="cn.comman.crud.pojo.Employee">
   <id column="id" javaType="java.lang.Integer" jdbcType="INTEGER" property="id"/>
   <result column="name" javaType="java.lang.String" jdbcType="VARCHAR" property="name"/>
   <result column="gender" javaType="java.lang.String" jdbcType="CHAR" property="gender"/>
   <result column="email" javaType="java.lang.String" jdbcType="VARCHAR" property="email"/>
   <result column="dpt_id" javaType="java.lang.Integer" jdbcType="INTEGER" property="dptId" />
   <association property="department" javaType="cn.comman.crud.pojo.Department">
       <id column="id" property="id"/>
       <result column="name" property="name"/>
   </association>
</resultMap>
<sql id="Base_And_Department_Column_List">
   e.id, e.name, e.gender, e.email, e.dpt_id, d.id, d.name
</sql>
<select id="selectByExampleWithDepartment" resultMap="BaseAndDepartmentResultMap">
   select
   <if test="distinct">
       distinct
   </if>
   <include refid="Base_And_Department_Column_List" />
   from t_employee e
   left join t_department d on e.dpt_id = d.id
   <if test="_parameter != null">
       <include refid="Example_Where_Clause" />
   </if>
   <if test="orderByClause != null">
       order by ${orderByClause}
   </if>
</select>

问题

因为t_employee表和t_department表中都有id和name字段, 所以按照以上方法在查询过程中, department的id和name不能正常赋值。

解决方法

解决方案

给查询的冲突字段赋予别名,再把resultMap中的column值改为赋予的别名

修改代码

<sql id="Base_And_Department_Column_List">
   e.id, e.name, e.gender, e.email, e.dpt_id, d.id, d.name
</sql>

改为

<sql id="Base_And_Department_Column_List">
   e.id, e.name, e.gender, e.email, e.dpt_id, d.id did, d.name dname
</sql>

   <association property="department" javaType="cn.comman.crud.pojo.Department">
       <id column="id" property="id"/>
       <result column="name" property="name"/>
   </association>

改为

   <association property="department" javaType="cn.comman.crud.pojo.Department">
       <id column="did" property="id"/>
       <result column="dname" property="name"/>
   </association>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值