13、mybatis多表关联查询级联属性
生活随笔
收集整理的這篇文章主要介紹了
13、mybatis多表关联查询级联属性
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1、創建表結構
- 2、EmployeeMapper接口
- 3、EmployeeMapper.xml
- 4、Test
1、創建表結構
CREATE TABLE `mybatis`.`dept` (`id` INT NOT NULL ,`dept_name` VARCHAR(45) NULL ,PRIMARY KEY (`id`) );alter table employee add d_id INT(45);INSERT INTO `mybatis`.`dept` (`id`, `dept_name`) VALUES ('1', '開發部'); INSERT INTO `mybatis`.`dept` (`id`, `dept_name`) VALUES ('2', '測試部');2、EmployeeMapper接口
package com.mi.dao;import com.mi.pojo.Employee; import org.apache.ibatis.annotations.MapKey; import org.apache.ibatis.annotations.Param;import java.util.List; import java.util.Map;public interface EmployeeMapper {//查詢員工及部門public Employee getEmpAndDept(Integer id); }3、EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--指定為接口的全類名--> <mapper namespace="com.mi.dao.EmployeeMapper"><!--聯合查詢,級聯屬性封裝結果集--><resultMap id="myEmpAndEmp" type="com.mi.pojo.Employee"><id column="id" property="id"/><result column="last_name" property="lastName"/><result column="gender" property="gender"/><result column="d_id" property="dept.id"/><result column="dept_name" property="dept.deptName"/></resultMap><!--關聯查詢員工及部門--><select id="getEmpAndDept" resultMap="myEmpAndEmp">select e.id,e.last_name, e.gender,d.id d_id,d.dept_name dept_namefrom employee e ,dept dwhere e.d_id = d.id and e.id = #{id}</select> </mapper>4、Test
@Testpublic void getEmpAndDept() throws IOException {//1、獲取SqlSessionFactory對象SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();//2、獲取Sqlsesion對象SqlSession sqlSession = sqlSessionFactory.openSession();try {//3、獲取接口的實現類對象//會為接口自動創建一個代理對象,代理對象去執行增刪改查方法EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);Employee employee = mapper.getEmpAndDept(3);System.out.println(employee);System.out.println(employee.getDept());}finally {sqlSession.close();}}總結
以上是生活随笔為你收集整理的13、mybatis多表关联查询级联属性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 12、mybatis返回map单条及多条
- 下一篇: 14、mybatis多表关联查询 ass