1.导包
2.实体类
Student
package com.xy.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Data @AllArgsConstructor @NoArgsConstructor @ToString public class Student { private int id; private String name; //学生需要关联一个老师 private int tid; }
Teacher
package com.xy.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor @ToString public class Teacher { private int id; private String name; //一个老师拥有多个学生 private List<Student> students; }
3.接口
StudentMapper.java
package com.xy.dao; import com.xy.pojo.Student; import java.util.List; public interface StudentMapper { }
TeacherMapper.java
package com.xy.dao; import com.xy.pojo.Student; import com.xy.pojo.Teacher; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; public interface TeacherMapper { //查找教师信息以及其对应的学生的信息 Teacher getTeacher(@Param("tid") int id); }
4.建立Mapper接口
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="com.xy.dao.StudentMapper"> </mapper>
TeacherMapper.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="com.xy.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"></result> <!--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> <!--选出来要查询的老师id,得到查询结果,这个是一个集合所以要写javaType--> <resultMap id="TeacherStudent2" type="Teacher"> <collection property="students" javaType="ArrayList" ofType="Stundet" select="getStudentByTeacherID" column="id"/> </resultMap> <select id = "getStudentByTeacherID" resultType="Student"> select * from mybatis.student where tid = #{tid} </select> </mapper>
5.在核心配置文件中绑定注册mapper
<mappers> <!--mapper不能用通配符 *--> <mapper resource="xiaoqi/dao/TeacherMapper.xml"/> <mapper resource="xiaoqi/dao/StudentMapper.xml"/> </mappers>
6.测试
关联-association【多对一】
集合-collection【一对多】
javaType ofType
javaType 用来指定属性实体类中的类型
ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
注意点: