实质上,无论是一对多还是多对一都是利用一个表查询共有属性,把共有属性传递到另一个表中进行查询。而这个过程关键也是利用resultMap这个标签来是实现的。
OneToMany
例子:
<resultMap id="rmClass" type="com.imooc.mybatis.entity.Classes">
<id column="id" property="id"></id>
<result column="classno" property="classno"/>
<collection property="studentList" select="student.selectByClassno"
column="classno"/>
</resultMap>
<select id="selectOneToMany" resultMap="rmClass" parameterType="String">
select * from classes where name=#{value}
</select>
id标签是class表的主键,
一对多的情况下使用collection标签,property是entity实体类中的查询出的studentList,select是student.xml定义的SQL名称,column则是传递的字段名。下方select则是定义查询的班级名称,可以此查出此班级下的学生信息。
多对一
<resultMap id="rmStudent" type="com.imooc.mybatis.entity.Student">
<id column="id" property="id"/>
<result column="classno" property="classno"/>
<association property="classes" select="class.selectByClassno" column="classno"></association>
</resultMap>
<select id="selectManyToOne" resultMap="rmStudent" parameterType="String">
select * from student where stuname=#{value}
</select>
关于resultMap的使用大体同上,只是此时标签选择association。下方利用学生姓名可以查出班级信息。