首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MyBatis_resultMap 的关联方式实现多表查询(多对一)

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

作者头像
时间静止不是简史
发布2020-07-26 20:04:49
1.2K0
发布2020-07-26 20:04:49
举报

项目结构

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

}

运行结果

在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-03-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 项目结构
  • 项目截图
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档