目录
1、多对一(多个学生有一个老师)
1.1、在项目的pom.xml中导入lombok
1.2、新建实体类Student和Teacher
1.3、建立Mapper接口和Mapper.xml文件
<?xml version="1.0" encoding="UTF8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zhou.dao.StudentMapper"> <!-- 按结果嵌套处理 推荐--> <select id="getStudent2" resultMap="StudentTeacher2"> select s.id sid, s.name sname, t.name tname from mybatis.student s, mybatis.teacher t where s.tid = t.id </select> resultMap 这个是结果集映射,有的实体类中属性名和数据库中不一致,所以需要映射property是实体类中的属性名,column是数据库中的字段名,这边写成sid是因为select语句中给它重新命名 <resultMap id="StudentTeacher2" type="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="Teacher"> <result property="name" column="tname"/> </association> </resultMap> <!-- ============================================--> <!-- 思路 1.查询所有学生信息 2.根据查出来的学生的tid,寻找对应的老师 子查询 --> <select id="getStudent" resultMap="StudentTeacher"> select * from mybatis.student; </select> <resultMap id="StudentTeacher" type="Student"> <result property="id" column="id"/> <result property="name" column="name"/> <!-- 复杂属性我们需要单独处理,association:对象,collection:集合 --> <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap>
<select id="getTeacher" resultType="Teacher"> select * from mybatis.teacher where id = #{tid} </select> </mapper> |
1.4、核心配置文件绑定注册Mapper接口或文件
1.5、测试
2、一对多(一个老师有多个学生)
2.1、 实体类
2.2、Mapper接口和Mapper.xml文件
<?xml version="1.0" encoding="UTF8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zhou.dao.TeacherMapper"> <!-- 按结果嵌套查询 推荐这种方式--> <select id="getTeacher" resultMap="TeacherStudent"> select s.id sid, s.name sname, t.name tname, t.id tid from mybatis.student s, mybatis.teacher t where s.tid = t.id and t.id = #{tid} </select> <resultMap id="TeacherStudent" type="Teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <!-- 复杂属性我们需要单独处理,association:对象,collection:集合 javaType="" 指定属性的类型 集合中的泛型信息,我们使用ofType获取 --> <collection property="students" ofType="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="tid" column="tid"/> </collection> </resultMap> <!-- ===========================================================--> <select id="getTeacher2" resultMap="TeacherStudent2"> select * from mybatis.teacher where id = #{tid} </select> <resultMap id="TeacherStudent2" type="Teacher"> <result property="id" column="id"/> <result property="name" column="name"/> <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/> </resultMap> <select id="getStudentByTeacherId" resultType="Student"> select * from mybatis.student where tid = #{tid} </select> </mapper> |
2.3、测试
3、小结