mybatis学习日记-连表查询-多对一
按照结果集嵌套查询
dao层:
1 package com.fu.dao; 2 3 import com.fu.pojo.Student; 4 5 6 import java.util.List; 7 8 public interface StudentMapper { 9 10 //查询所有的学生信息以及其老师的信息 11 ListgetStudentList(); 12 13 14 }
1 package com.fu.dao; 2 3 public interface TeacherMapper { 4 }
pojo层:
package com.fu.pojo; import org.apache.ibatis.type.Alias; @Alias("student") public class Student { private int id; private String name; private Teacher teacher; public Student(int id, String name, Teacher teacher) { this.id = id; this.name = name; this.teacher = teacher; } public Student() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", teacher=" + teacher + '}'; } }
package com.fu.pojo; import org.apache.ibatis.type.Alias; @Alias("teacher") public class Teacher { private int id; private String name; public Teacher(int id, String name) { this.id = id; this.name = name; } public Teacher() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Teacher{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
dao层对应的student的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">
测试类:
package com.fu.dao; import com.fu.pojo.Student; import com.fu.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class StudentMapperTest { @Test public void getStudentListTest(){ //获取sqlSession对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); ListstudentList = mapper.getStudentList(); for (Student student : studentList) { System.out.println(student); } sqlSession.close(); } }
测试结果: