Mybatis框架的多对一关联关系(六)

一、一对多的关联映射

  一对多关联查询多表数据

1接口

public interface IDeptDAO {

    //根据部门编号查询该部门单个查询
        public Emp getEmpById(Integer id);
}

2小配置

<?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="cn.happy.dao.IDeptDAO">
  
  <select id="selectDeptByemp" resultType="Dept">
      select deptno,deptname from dept where deptno=#{deptno}
  </select>
  
  
  
  <resultMap type="Emp" id="empMapper">
     <id property="empno" column="empno"/>
     <result property="empname" column="empname"/>
     <!-- 多对一 -->
     <association property="dept" javaType="Dept"
     
         select="selectDeptByemp"
         column="deptno"
     />
   </resultMap>    
  

 <!-- manytoone-->
  <!-- resultMap的id="empMapper" -->
  <!-- select标签id="getEmpById"接口的方法名一样 -->
  <select id="getEmpById" resultMap="empMapper">
     select deptno,empno,empname from emp
     where empno=#{empno}
  </select>
  
  
</mapper>

3测试类

package cn.happy.test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import cn.happy.dao.IDeptDAO;
import cn.happy.entity.Emp;


import cn.happy.util.MybatisUtil;

public class MyTest {
    IDeptDAO dao;
    @Before
    public void initData() throws IOException{
        SqlSession session = MybatisUtil.getSession();
         dao = session.getMapper(IDeptDAO.class);
    }


    @Test
    public void getEmpById() throws IOException{
        Emp emp = dao.getEmpById(2);
        System.out.println(emp.getEmpname());
    }

}

    剩余工具类和实体类可以去之前的Mybatis框架的博客园去找。

 

       

 

posted @ 2016-12-20 10:44  葉子。  阅读(288)  评论(0编辑  收藏  举报