mybatis 复杂sql 一对多 多对一
主意:每次从官网添加 xml映射文件时要修改namespace,xml配置文件别忘添加啊mapper
一、搭建环境
注意:
1、多个javaBean时,xml映射文件,储存到rescourse 文件下, 与dao文件同名和同级下
2、xml映射文件,别忘记修改 namespace
3、xml配置文件的 mapper resource 貌似不能简写(使用*符号)
复杂查询的关系
assocation 用于对象 javaType 作为返回值的关键字
collection 用于集合 ofType 对于数据类型
二、多对一
1、sql语句
SELECT student.id as sid, student.name as sname, teacher.name as tname FROM student left JOIN teacher on student.tid = teacher.id
2、接口
package com.wt.dao; import com.wt.pojo.Student; import java.util.List; public interface StudentMapper { List<Student> getStudentList(); }
3、xml 映射文件
<select id="getStudentList" resultMap="isStudentTeacher"> SELECT student.id as sid, student.name as sname, teacher.name as tname FROM student left JOIN teacher on student.tid = teacher.id </select> <resultMap id="isStudentTeacher" type="Student"> <result column="sid" property="id"/> <result column="sname" property="name"/> <!--association 用于对象 javaType 为返回值类型 --> <association property="teacher" javaType="Teacher"> <result property="name" column="tname"/> </association> </resultMap>
4、pojo
package com.wt.pojo; import lombok.Data; @Data public class Student { private int id; private String name; private Teacher teacher; }
package com.wt.pojo; import lombok.Data; @Data public class Teacher { private int id; private String name; }
三、一对多
1、sql语句
SELECT teacher.id as tid, teacher.name as tname, student.id as sid, student.name as sname FROM student RIGHT JOIN teacher on student.tid = teacher.id where tid = 1
2、接口类
List<Teacher> getTeacherList(@Param("tid") int id);
3、xml 配置文件
<select id="getTeacherList" resultMap="teacherStudent"> SELECT teacher.id as tid, teacher.name as tname, student.id as sid, student.name as sname FROM student RIGHT JOIN teacher on student.tid = teacher.id where tid = #{tid} </select> <!-- collection 集合 类型 ofType--> <resultMap id="teacherStudent" type="teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <collection property="students" ofType="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> </collection> </resultMap>
4、pojo
package com.wt.pojo; import lombok.Data; @Data public class Student { private int id; private String name; }
package com.wt.pojo; import lombok.Data; import java.util.List; @Data public class Teacher { private int id; private String name; private List<Student> students; }