MyBatis_resultMap的N+1方式實現多表查詢(多對 一)

項目結構

1.實體類
2.Mapper層
3.service層
4.工具層
5.測試層

項目截圖

在這裏插入圖片描述
1、實體類

創建班級類(Clazz)和學生類(Student),添加相應的方法。 並在 Student 中添
加一個 Clazz 類型的屬性, 用於表示學生的班級信息.
在這裏插入圖片描述
在這裏插入圖片描述

2 mapper 層

提供StudentMapper和ClazzMapper, StudentMapper查詢所
有學生信息, ClazzMapper 根據編號查詢班級信息.
在這裏插入圖片描述
在這裏插入圖片描述

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層
在這裏插入圖片描述

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);
		}
	}

}

運行結果
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章