MyBatis—resultMap 的关联方式实现多表查询(多 对一)

mapper

a)在 StudentMapper.xml 中定义多表连接查询 SQL 语句, 一次性查到需要的所有数据, 包括对应班级的信息.

b)通过<resultMap>定义映射关系, 并通过<association>指定对象属性的映射关系. 可以把<association>看成一个<resultMap>使用. javaType 属性表示当前对象, 可以写全限定路径或别名.

<?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="com.bjsxt.mapper.StudentMapper">
	    <resultMap type="Student" id="smap">
		  	<id property="stid" column="sid"/>
		  	<result property="stname" column="name"/>
		  	<result property="stage" column="age"/>
		  	<result property="stsex" column="sex"/>
		  	<result property="stcid" column="c_id"/>
		  	<!-- 用于关联一个对象 -->
		  	<association property="clazz" javaType="clazz">
		  		<id property="id" column="cid"/>
		  		<result property="name" column="cname"/>
		  		<result property="room" column="croom"/>
		  	</association>
	    </resultMap>
		<select id="selAll" resultMap="smap">
			select s.sid,s.name,s.age,s.sex,s.c_id,c.cid,c.cname,c.croom
			from t_stu s
			left join t_class c
			on s.c_id=c.cid
		</select>
  </mapper>

 Test测试类:

package com.bjsxt.test;

import java.util.List;

import com.bjsxt.pojo.Student;
import com.bjsxt.service.StudentService;
import com.bjsxt.service.Impl.StudentServiceImpl;

public class TestSel {
	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方式实现不需要ClazzMapper

运行截图: 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值