<个人学习笔记>
一、多对一 创建一个教师类和学生类(提前在数据库中创建好相应的表)
public class Teacher { private int id; private String name; public Teacher(int id, String name) { this.id = id; this.name = name; } } public class Student { private int id; private String name; private Teacher teacher; }编写StudentMapper接口
public interface StudentMapper { //基于查询嵌套 List<Student> getStudent(); //基于结果嵌套 List<Student> getStudent2(); }编写对应的xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.Dao.StudentMapper"> <!-- 结果嵌套--> <select id="getStudent2" resultMap="StudentTeacher2"> select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid = t.id </select> <resultMap id="StudentTeacher2" type="com.JavaBean.Student"> <result column="sid" property="id"/> <result column="sname" property="name"/> <association property="teacher" javaType="com.JavaBean.Teacher"> <result property="name" column="tname"></result> </association> </resultMap> <!-- 查询嵌套--> <select id="getStudent" resultMap="StudentTeacher"> select * from student </select> <resultMap id="StudentTeacher" type="com.JavaBean.Student"> <association property="teacher" javaType="com.JavaBean.Teacher" column="tid" select="getTeacher"></association> </resultMap> <select id="getTeacher" resultType="com.JavaBean.Teacher"> select * from teacher where id = #{id} </select> </mapper>编写测试类 public class Test1 { @Test public void test(){ SqlSession sqlsession = MybatisUtil.getSqlsession(); TeacherMapper mapper = sqlsession.getMapper(TeacherMapper.class); Teacher teaher = mapper.getTeacher(); System.out.println(teaher); } @Test public void test2(){ SqlSession sqlsession = MybatisUtil.getSqlsession(); StudentMapper mapper = sqlsession.getMapper(StudentMapper.class); List student = mapper.getStudent2(); for (Student student1 : student) { System.out.println(student1); } } }
一对多的情况类似,修改Teacher类、Student类中的属性,配置文件中写法类似,将javatype改为oftype即可。