Mybatis多对一和一对多
resultMap
<select id="方法名" resultMap="XX"></select> <!--(要和resultMap中的id相同)-->
<resultMap id="XX" type="最终要查询的pojo对象">
<result column="表的一个字段名" property="pojo对象的一个属性"/>
<!--查找另一个pojo对象(另一张实体表)-->
<association property="pojo对象的一个属性" column="最终的pojo对象对应表中的列" javaType="被查询的pojo对象对应的表" select="接口中查询的方法名"></association>
<!--或者-->
<association property="pojo对象的一个属性" javaType="被查询的pojo对象对应的表">
<result column="表的一个字段名" property="pojo对象的一个属性"/>
</association>
<!-- 集合中的property须为oftype定义的pojo对象的属性-->
<collection column="{skuId=ID}" property="attributes" ofType="com.meikai.shop.entity.TShopAttribute" select="getAttribute"></collection>
</resultMap>
例:
多个学生对应一个老师
对于学生而言,关联...多个学生关联一个老师
对于老师而言,集合...一个老师对于多个学生
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO teacher(`id`, `name`) VALUES (1, '菜老师');
CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
- 两表查询(学生查询老师)
<!--联表查询-->
<select id="getStudentList" resultMap="student-teacher">
select s.id,s.name,t.name tname from student s,teacher t where s.tid = t.id;
</select>
<resultMap id="student-teacher" type="Student">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<association property="teacher" javaType="Teacher">
<result column="tname" property="name"></result>
</association>
</resultMap>
<!--或者-->
<!--子查询-->
<select id="getStudentList" resultMap="student-teacher">
select s.id,s.name,t.name tname from student s,teacher t where s.tid = t.id;
</select>
<resultMap id="student-teacher" type="Student">
<!--property映射pojo对象的属性,column表示数据库中的列-->
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<association property="teacher" javaType="Teacher" column="tid" select="getTeacher"></association>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{id};
</select>
- 多对一(老师查询学生)
<!--注意,方法的返回值一定要是拥有集合的对象(老师)-->
<select id="getStudentList" resultMap="teacher-student">
select t.id tid,t.name tname,s.name sname from student s,teacher t where s.tid = t.id;
</select>
<resultMap id="teacher-student" type="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<collection property="list" ofType="Student">
<result property="name" column="sname"></result>
</collection>
</resultMap>