数据库表结构
学生表多对一老师表
XML中的两种书写方式:
方式一:子查询
<select id="getStudent" resultMap="StudentMapper"> select * from student; </select> <resultMap id="StudentMapper" type="Student"> <result property="id" column="id"/> <result property="name" column="name"/> <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="Teacher"> select * from teacher where id=#{id}; </select>
方式二:链表查询
<select id="getStudent2" resultMap="StudentTeacher"> SELECT s.id sid, s.name sname, T.name tname FROM student s, teacher T WHERE s.tid = T.id; </select> <resultMap id="StudentTeacher" type="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="Teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> </association> </resultMap>
测试文件
public class MyTest { @Test public void getTeacherTest() { SqlSession sqlSession = MybatisUtils.getSqlSession(); StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); List<Student> student = mapper.getStudent2(); for (Student student1 : student) { System.out.println(student1); } sqlSession.close(); } }