mybais-多对一查询
准备阶段(多个学生对应一个老师)
1.建表
2.编写实体类
package com.lv.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private Teacher teacher;
}
package com.lv.pojo;
import lombok.Data;
@Data
public class Teacher {
private int id;
private String name;
}
3.编写Mapper接口
package com.lv.dao;
public interface StudentMapper {
}
package com.lv.dao;
import com.lv.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface TeacherMapper {
@Select("select * from teacher where id = #{tid}")
Teacher getTeacher(@Param("tid") int id);
}
4.编写Mapper.xml配置文件
<?xml version="1.0" encoding="UTF8" ?>
<?xml version="1.0" encoding="UTF8" ?>
5.在mybatis-config.xml中添加映射
6.编写测试文件进行测试
package com.lv.dao;
import com.lv.pojo.Teacher;
import com.lv.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class MyTest {
@Test
public void getTeacher(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
}
7.测试结果
方式一:按查询嵌套处理(相当于SQL中的子查询)
1.在StudentMapper接口中编写方法
//查询所有的学生信息,以及对应的老师信息!
public List getStudent();
2.编写对应的Mapper.xml文件
3.测试
@Test
public void getStudent(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List studentList = mapper.getStudent();
for (Student student : studentList) {
System.out.println(student);
}
sqlSession.close();
}
方式二:按结果嵌套处理(相当于SQL中的连表查询)
1.在StudentMapper接口中编写方法
//查询所有的学生信息,以及对应的老师信息!
public List getStudent2();
2.编写对应的Mapper.xml文件
3.测试
@Test
public void getStudent2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List studentList = mapper.getStudent2();
for (Student student : studentList) {
System.out.println(student);
}
sqlSession.close();
}