问题描述:在使用mybatis进行多表联合查询时,如果两张表中的字段名称形同,会出现无法正常映射的问题。
问题解决办法:在查询时,给重复的字段 起别名,然后在resultMap中使用别名进行映射。
给出一个小demo:如下是一个**mapper.xml映射文件的一个查询片段,用到了四表联合查询,其中订单id,项目id,回报id,是需要查询的数据,并且字段名都是id,显然是重复字段,此时就需要为这些重复的id起别名了,请看下面的红色部分代码:
- <resultMap type="com.lz.pojo.MyOrder" id="myOrder">
- <result column="name" property="name" />
- <result column="type" property="type" />
- <result column="money" property="money" />
- <result column="content" property="content" />
- <result column="state" property="state" />
- <result column="pic" property="pic" />
- <result column="pid" property="pid" />
- <result column="hid" property="hid" />
- <result column="oid" property="oid" />
- </resultMap>
-
- <select id="findMyOrderByUserId" parameterType="int" resultMap="myOrder">
- SELECT p.name,p.type,o.money,h.content,o.state,h.pic,p.id pid,h.id hid,o.id oid
- FROM project p,huibao h,`order` o,`user` u
- WHERE o.projectId=p.id AND o.userId=u.id and o.hbId=h.id AND u.id=#{userId}
- </select>
这样处理后,查询时就可以成功的完成,实体类与查询字段的映射了。