Mybatis之“一对多”映射关系的xml文件配置与关联查询

1、首先准备两个表:

dept部门表、employee员工表。他们的关系为一个部门下有多个员工

dept表:

employee表:

2、编写实体类:

关联查询就不能用与单表映射的实体类了,我们编写一个一对多的实体类。

该类继承dept类,然后用list集合保存一个部门下的多个员工信息。

package com.asiainfo.demo.myEntity;

import com.asiainfo.demo.entity.Dept;
import com.asiainfo.demo.entity.Employee;

import java.util.List;

/**
 * @author:tongys
 * @createTime:2020/6/11 19:24
 */
public class DeptWithEmployee extends Dept { //自定义一个“一对多”的实体类,一个部门下有多个员工
    private List<Employee> employeeList;
    public List<Employee> getEmployeeList(){
        return employeeList;
    }
    public void setEmployeeList(List<Employee> list){
        employeeList = list;
    }
}

3、编写mapper.xml映射文件

找到dept表的xml映射文件,在该文件中我们需要自定义一个结果集来接收查询返回的数据。

<!-- 自定义“一对多”的结果集 -->
  <resultMap id="deptAndEmployee" type="com.asiainfo.demo.myEntity.DeptWithEmployee">
      <result column="dept_name" property="deptName" jdbcType="VARCHAR"/>
    <!-- 用collection来声明结果集中的集合 -->
                                          <!-- 注意使用ofType来声明集合中的数据类型 -->
      <collection property="employeeList" ofType="com.asiainfo.demo.entity.Employee">
        <result column="name" property="name" jdbcType="VARCHAR"/>
      </collection>
  </resultMap>

然后编写sql语句,注意代码注释中的说明!

<!-- 以下为自定义sql -->
                                    <!-- 结果集要使用我们在上边自定义的那个 -->
  <select id="queryDeptAndEmployee" resultMap="deptAndEmployee">
    SELECT b.dept_name,a.name from employee a ,dept b where a.dept = b.id;
  </select>

4、在mapper.java类中声明方法,并进行测试

package com.asiainfo.demo.controller;

import com.asiainfo.demo.myEntity.DeptWithEmployee;
import com.asiainfo.demo.service.DeptService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author:tongys
 * @createTime:2020/4/9 13:27
 */
@Controller
public class TestController {
    
    @Resource
    private DeptService deptService;
    
    /**
     * 测试一对多(一个部门对应多个员工)的xml配置与查询
     * @return
     */
    @RequestMapping("test2")
    @ResponseBody
    public String test2(){
        List<DeptWithEmployee> list = deptService.queryDeptAndEmployee();
        System.out.println(list.size());
        return list.get(0).getDeptName();//返回结果成功
    }



}

测试结果可以发现,成功的查出了数据并保存到了自定义的结果集中。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值