mybatis使用association分步查询关联属性查询

2025-04-21 18:51:13

1、我们的程序是要查询员工信息的时候查询出相应的部门信息。

mybatis使用association分步查询关联属性查询

2、在xml中定义员工分步查询的sql实现。先按照员工id查询员工信息。根据查询员工信息中的部门id去部门表查出部门信息。然后把部门设置到员工中。<select id="getEmpById" resultMap="MyEmpByStep" databaseId="mysql"> select * from tbl_emp where emp_id = #{empId} </select>

mybatis使用association分步查询关联属性查询

3、定义员工信息返回的resultMap。<resu盟敢势袂ltMap type="com.gwolf.bean.Employee" id="MyEmpByStep"> <id column="emp_id" property="empId"/> <result column="emp_name" property="empName"/> <result column="gender" property="gender"/> <result column="email" property="email"/> <result column="emp_name" property="empName"/> <association property="department" select="com.gwolf.dao.DepartmentMapper.getDepartmentById"></association> </resultMap>

mybatis使用association分步查询关联属性查询

4、定义将员工的那一列的值传值给部门。<association property="department" select="com.gwolf.dao.DepartmentMapper.getDepartmentById" column="d_id"></association>

mybatis使用association分步查询关联属性查询

5、编写单元测试类。@Test public void test1() throws Exception { Stri荏鱿胫协ng resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); Map<Integer,Object> employee = employeeMapper.getEmpByIdReturnMap(1); System.out.println(employee); }finally { sqlSession.close(); } }

mybatis使用association分步查询关联属性查询

6、执行单元测试,查看部门的信息是否能够查询出来。

mybatis使用association分步查询关联属性查询
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢