9、Mybatis执行流程
10、多对一
建立老师,学生表
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');
实体类
//老师
public class Teacher {
private int id;
private String name;
}
//学生
public class Student {
private int id;
private String name;
//学生关联老师
private Teacher teacher;
}
查询学生信息,学生类中含有老师对象属性,需要嵌套处理:StudentMapper.xml
<!--方式一-->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.StudentMapper">
<resultMap id="StudentTeacher" type="Student">
<!--复杂属性单独处理,对象:association;集合:collection
javaType="Teacher" 属性的类型
select="queryTeacher" 字段的使用,执行sql
-->
<association property="teacher" column="tid" javaType="Teacher" select="queryTeacher"/>
</resultMap>
<!--字段的使用,执行sql-->
<select id="queryTeacher" resultType="Teacher">
select * from mybatis.teacher where id=#{id}
</select>
<select id="queryStudent" resultMap="StudentTeacher">
select * from mybatis.student s,mybatis.teacher t where s.tid=t.id
</select>
</mapper>