MyBatis_resultMap 的关联方式实现多表查询(多对一)

时间:2022-07-22
本文章向大家介绍MyBatis_resultMap 的关联方式实现多表查询(多对一),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

项目结构

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

项目截图

1、实体类

创建班级类(Clazz)和学生类(Student),添加相应的方法。 并在 Student 中添 加一个 Clazz 类型的属性, 用于表示学生的班级信息.

2 mapper 层

a) 在 StudentMapper.xml 中定义多表连接查询 SQL 语句, 一 次性查到需要的所有数据, 包括对应班级的信息. b) 通过定义映射关系, 并通过指 定对象属性的映射关系. 可以把看成一个 使用. javaType 属性表示当前对象, 可以写 全限定路径或别名.

StudentMapper.xml

<mapper namespace="cn.bjsxt.mapper.StudentMapper">
	<resultMap type="Student" id="smap">
		<id property="id" column="sid"/>
		<result property="name" column="sname"/>
		<result property="age" column="age"/>
		<result property="gender" column="gender"/>
		<result property="cid" column="cid"/>
		<association property="clazz" javaType="clazz" >
			<id property="id" column="cid"/>
			<result property="name" column="cname"/>
			<result property="room" column="room"/>
		</association>
	</resultMap>
	<select id="selAll" resultMap="smap">
		select s.id sid,s.name sname,s.age,s.gender,c.id cid,c.name cname,c.room
		from t_student s
		left join t_class c
		on s.cid=c.id
	</select>
</mapper>

3、service层

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

}

运行结果