前情提要:Student和Teacher表,student,tid关联老师的tid
一对多
一个老师对应多个学生
老师和学生的接口,在两个文件里,太短了,就放在一起
public interface TeacherMapper { List<Teacher> selectTeacher(@Param("tid")int id); List<Teacher> selectTeacher2(@Param("tid")int id); } public interface StudentMapper { List<Student> selectStudent(); }
teacher 的map文件
<?xml version="1.0" encoding="GBK" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.xian.dao.TeacherMapper"> <!-- 根据查询===也是推荐的方式==================================--> <select id="selectTeacher" resultMap="Teacherss"> select s.id sid,s.name sname,t.tid tid,t.tname tname from testdb.teacher t,testdb.student s where s.tid=t.tid and t.tid=#{tid} </select> <resultMap id="Teacherss" type="Teacher"> <result property="tid" column="tid"/> <result property="tname" column="tname"/> <!-- collection 对应集合的意思,对应的Student是一个列表===对比多对一的association--> <collection property="studentlist" ofType="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="tid" column="tid"/> </collection> </resultMap> <!-- =============================================--> <select id="selectTeacher2" resultMap="Teacher2"> select * from testdb.teacher </select> <resultMap id="Teacher2" type="Teacher"> <collection property="studentlist" javaType="ArrayList" ofType="Student" select="getStudent" column="tid"/> </resultMap> <select id="getStudent" resultType="Student"> select * from testdb.student where tid=#{tid} </select> </mapper>
关联:association
集合:collection
Java type 和 of type
javatype 指定实体类中属性的类型
of Type 用来指定,集合、List的泛型
多对一
多个学生对应一个老师
接口文件和上面的一样不重复了,直接上代码
<?xml version="1.0" encoding="GBK" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.xian.dao.StudentMapper"> <!-- 多对一 子查询,联表查询--> <!-- =================================================--> <!--根据结果--> <select id="selectStudent2" resultMap="student2"> select s.id sid,s.name sname,t.tname tname from student s,teacher t where s.tid=t.tid </select> <resultMap id="student2" type="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="Teacher"> <result property="name" column="tname"/> </association> </resultMap> <!-- 根据查询--> <!-- =============================================--> <resultMap id="StudentMap" type="Student"> <result property="id" column="id"/> <result property="name" column="name"/> <association property="teacher" column="tid" javaType="Teacher" select="selectTeacher"/> </resultMap> <select id="selectStudent" resultMap="StudentMap"> select * from student </select> <select id="selectTeacher" resultType="com.xian.pojo.Teacher"> select * from teacher where tid=#{tid} </select> </mapper>