MyBatis_resultMap的N+1方式实现多表查询(多对 一)

项目结构

1.实体类
2.Mapper层
3.service层
4.工具层
5.测试层

项目截图

MyBatis_resultMap的N+1方式实现多表查询(多对 一)
1、实体类

创建班级类(Clazz)和学生类(Student),添加相应的方法。 并在 Student 中添
加一个 Clazz 类型的属性, 用于表示学生的班级信息.
MyBatis_resultMap的N+1方式实现多表查询(多对 一)
MyBatis_resultMap的N+1方式实现多表查询(多对 一)

2 mapper 层

提供StudentMapper和ClazzMapper, StudentMapper查询所
有学生信息, ClazzMapper 根据编号查询班级信息.
MyBatis_resultMap的N+1方式实现多表查询(多对 一)
MyBatis_resultMap的N+1方式实现多表查询(多对 一)

clazzMapper.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="cn.bjsxt.mapper.ClazzMapper">
	<select id="selById" resultType="Clazz" parameterType="int">
		select * from t_class where id=#{0}
	</select>
</mapper>

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">
<mapper namespace="cn.bjsxt.mapper.StudentMapper">
	<resultMap type="Student" id="smap">
	<!-- 只有二次使用才在result标签下写出 -->
		<result property="cid" column="cid" />
		<!-- 用于关联一个对象,并为学生装配班级信息 -->
		<association property="clazz" select="cn.bjsxt.mapper.ClazzMapper.selById" column="cid"></association>
	</resultMap>
	<select id="selAll" resultMap="smap">
		select * from t_student
	</select>
</mapper>

3、service层
MyBatis_resultMap的N+1方式实现多表查询(多对 一)

package cn.bjsxt.service.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import cn.bjsxt.mapper.StudentMapper;
import cn.bjsxt.pojo.Student;
import cn.bjsxt.service.StudentService;
import cn.bjsxt.util.MyBatisUtil;

public class StudentServiceImpl implements StudentService {

	@Override
	public List<Student> selAll() {
		SqlSession session = MyBatisUtil.getSession();

		// 学生Mapper
		StudentMapper stuMapper = session.getMapper(StudentMapper.class);

		List<Student> list = stuMapper.selAll();

		session.close();
		return list;
	}

}

4、工具层

public class MyBatisUtil {
	private static SqlSessionFactory factory=null;
	
	static {
		
		try {
			InputStream is = Resources.getResourceAsStream("mybatis-cfg.xml");
			factory=new SqlSessionFactoryBuilder().build(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static SqlSession getSession() {
		SqlSession session=null;
		if (factory!=null) {
			//true表示开启自动提交功能,防止回滚,但是运行多条sql语句可能出问题
			//session=factory.openSession(true);
			session=factory.openSession();
		}
		return session;
	}
}

5、测试层

public class TestQuery {

	public static void main(String[] args) {
		StudentService ss = new StudentServiceImpl();
		List<Student> list = ss.selAll();
		for (Student student : list) {
			System.out.println(student);
		}
	}

}

运行结果
MyBatis_resultMap的N+1方式实现多表查询(多对 一)