mybatis 在配置关联关系查询的时候 关联查询的 2个表的字段名不能重名 否则就会出现 主表的数据吧宠表相同字段的数据给覆盖掉了。
比如学生表 student 有字段 s_id s_name grade_id 还有一张班级表 grade g_id g_name
student
<mapper namespace="lc.domain.Student">
<resultMap type="lc.domain.Student" id="studentResultMap">
<id property="id" column="s_id"/>
<result property="name" column="s_name"/>
<association property="grade_id" javaType="lc.domain.Grade" >
<id property="id" column="g_id"/>
<result property="name" column="g_name"/>
</association>
</resultMap>
<select id="selectStudent" resultMap="studentResultMap" >
select s.* , g.* from student s,grade g where g.g_id =#{grade.id} and s.id =#{id}
</select>
</mapper>
------------------------------------------------------------------------------------------------------
grade
<mapper namespace="lc.domain.Grade">
<resultMap type="lc.domain.Grade" id="gradeResultMap">
<id column="g_id" property="id"/>
<result column="g_name" property="name"/>
<collection property="studentList" ofType="lc.domain.Student">
<id column="s_id" property="id"/>
<result column="s_name" property="name"/>
</collection>
</resultMap>
<select id="selectGrade" resultMap="gradeResultMap">
select g.*,s.* from grade g,student s where g.g_id = #{id} and s.grade_id = #{id}
</select>
</mapper>
上面试一个一对多的配置的例子:
如果数据库里面的字段 和 配置里面 的column 属性 s_id 和 g_id s_name 和g_name 都改成 id 和name 的话 那么查出来的 student 的属性会把 student里面的grade属性的值全都覆盖掉了 所以mybatis 做关联查询 数据库字段的名字一定要区别开来
#{grade.id} grade 是student里面的属性 可以直接 点出grade 里面的属性 做相应的查询.
javaType 只的是当前对象的类型 ofType 因为collection 默认的javatype是 集合arrayList 所以 ofType用来指定 集合里的元素类型.