mybatis_关联表_带有相同字段_解决办法

问题描述

mybatis_关联表的情况下,如果两个表的字段名称相同。
例如:clazz表的主键是id,student表的主键也是id.
那么后一个id 会被覆盖。

表结构

班级表
在这里插入图片描述
学生表
在这里插入图片描述

ClazzMapper.xml

Clazz、Student表中都有ID,在mapper中出现两次

<mapper namespace="test.dao.ClazzMapper" >
  <resultMap id="BaseResultMap" type="test.model.Clazz" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="classname" property="classname" jdbcType="VARCHAR" />
    <collection property="students" ofType="test.model.Student" >
      <result column="id" property="id" jdbcType="DECIMAL" />
      <result column="name" property="name" jdbcType="VARCHAR" />
      <result column="sex" property="sex" jdbcType="VARCHAR" />
      <result column="birthday" property="birthday" jdbcType="DATE" />
      <result column="age" property="age" jdbcType="INTEGER" />
      <result column="classid" property="classid" jdbcType="INTEGER" />
    </collection>
  </resultMap>
  <select id="searchAll" resultMap="BaseResultMap"  >
    SELECT c.*,s.* FROM  student s ,clazz c WHERE s.`classid`=c.`id`
  </select>

Mybatis 查询结果(错误)
并不存在1,2的学生id ,学生id 实际上是ClazzID覆盖后的结果。
在这里插入图片描述
实际结果
关联表——各个班级下的所有学生

在这里插入图片描述

修改后的查询结果(正确)
在这里插入图片描述

解决方案——起别名

ClazzMapper.xml

在这里student的id 使用别名did(在下面定义)

<mapper namespace="test.dao.ClazzMapper" >
  <resultMap id="BaseResultMap" type="test.model.Clazz" >
    <id column="did" property="id" jdbcType="INTEGER" />
    <result column="classname" property="classname" jdbcType="VARCHAR" />
    <collection property="students" ofType="test.model.Student" >
      <result column="did" property="id" jdbcType="DECIMAL" />
      <result column="name" property="name" jdbcType="VARCHAR" />
      <result column="sex" property="sex" jdbcType="VARCHAR" />
      <result column="birthday" property="birthday" jdbcType="DATE" />
      <result column="age" property="age" jdbcType="INTEGER" />
      <result column="classid" property="classid" jdbcType="INTEGER" />
    </collection>
  </resultMap>

在这里给student表中的id 起别名为 did

  <select id="searchAll" resultMap="BaseResultMap"  >
    SELECT c.*,s.id did, s.name, s.sex, s.birthday, s.age, s.classid FROM  student s ,clazz c WHERE s.`classid`=c.`id`
  </select>
发布了21 篇原创文章 · 获赞 6 · 访问量 9324

猜你喜欢

转载自blog.csdn.net/qq1032350287/article/details/87715398