测试环境搭建
1.导入lombok
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
⒉.新建实体类Teacher,Student
package com.wqs.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private Teacher teacher;
}
package com.wqs.pojo;
import lombok.Data;
@Data
public class Teacher {
private int id;
private String name;
}
3.建立Mapper接口
4.建立Mapper.XML文件
5.在核心配置文件中绑定注册我们的Mapper接口或者文件!
<mappers>
<mapper resource="com.wqs.dao/StudentMapper.xml"></mapper>
<mapper resource="com.wqs.dao/TeacherMapper.xml"></mapper>
</mappers>
6.测试查询是否能够成功!
查询所有学生信息,根据学生表的tid值查找老师信息
1.根据查询嵌套处理
Student接口
//查询所有学生信息和对应的老师信息
public List<Student> getStudent();
mapper文件配置
<mapper namespace="com.wqs.dao.StudentMapper">
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="com.wqs.pojo.Student">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<!-- 复杂的属性需要单独处理,对象:association 集合collection-->
<association property="teacher" column="tid" javaType="com.wqs.pojo.Teacher" select="getTeacher"></association>
</resultMap>
<select id="getTeacher" resultType="com.wqs.pojo.Teacher">
select * from teacher where id = #{tid}
</select>
</mapper>
测试
@Test
public void getStudent(){
SqlSession sqlSession = MybatisUntill.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> student = mapper.getStudent();
for (Student student1 : student) {
System.out.println(student1);
}
sqlSession.close();
}
运行结果
2.根据结果嵌套处理
接口
public List<Student> getStudent2();
mapper文件配置
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname from student s,teacher t where t.id=s.tid
</select>
<resultMap id="StudentTeacher2" type="com.wqs.pojo.Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<association property="teacher" javaType="com.wqs.pojo.Teacher">
<result property="name" column="pname"></result>
</association>
</resultMap>
测试
public void getStudent2(){
SqlSession sqlSession = MybatisUntill.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> student2 = mapper.getStudent2();
for (Student student : student2) {
System.out.println(student);
}
sqlSession.close();
}
运行结果