项目结构

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

项目截图

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

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

2 mapper 层

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

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

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层
MyBatis_resultMap 的关联方式实现多表查询(多对一)

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 的关联方式实现多表查询(多对一)

相关文章:

  • 2022-12-23
  • 2021-08-04
  • 2021-11-27
  • 2021-07-22
  • 2021-08-15
  • 2021-07-09
  • 2022-12-23
  • 2021-12-01
猜你喜欢
  • 2021-12-08
  • 2021-05-18
  • 2022-12-23
  • 2022-12-23
  • 2021-09-24
  • 2021-06-11
相关资源
相似解决方案