时间:2021-07-01 10:21:17 帮助过:13人阅读
然后创建部门接口以及对应的xml文件
package dao; import entity.Dept; import entity.Emp; import java.util.List; /** * Created by mycom on 2018/2/26. */ public interface IDeptDao { //根据部门编号获得部门名称 员工名称 单条sql public Dept getEmpByDeptNo(int deptNo); }
<?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="dao.IDeptDao"> <resultMap id="deptMaper" type="Dept"> <id column="d" property="deptNo"></id> <result column="deptName" property="deptName"></result> <collection property="emps" ofType="Emp"> <id column="empNo" property="empNo"></id> <result column="empName" property="empName"></result> </collection> </resultMap> <!--查询部门和员工 单条sql语句方案--> <select id="getEmpByDeptNo" resultMap="deptMaper"> SELECT dept.deptNo as d ,deptName,empName FROM dept,emp WHERE dept.`deptNo`=emp.`deptNo` AND dept.`deptNo`=#{deptNo} </select> </mapper>
编写测试类
//查询部门和员工 单条sql
@Test
public void oneToMany(){
SqlSession sqlSession = MyBatisUtil.getSession();
IDeptDao mapper = sqlSession.getMapper(IDeptDao.class);
Dept dept = mapper.getEmpByDeptNo(1);
System.out.println("部门名称"+dept.getDeptName());
for (Emp emp:dept.getEmps()) {
System.out.println(emp.getEmpName());
}
sqlSession.close();
}
MyBatis(四)关于多表联查 关联关系之一--------一对多(单条sql语句查询)
标签:where ted 3.0 查询 import 获得 man void sharp