問題描述
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>