创建两个类一个employee,一个department
package com.cn.orm; public class Department { private Integer deptId; private String deptName; public Integer getDeptId() { return deptId; } public void setDeptId(Integer deptId) { this.deptId = deptId; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName == null ? null : deptName.trim(); } @Override public String toString() { return "Department{" + "deptId=" + deptId + ", deptName=‘" + deptName + ‘\‘‘ + ‘}‘; } }
package com.cn.orm; public class Employee { private Integer id; private String name; private Integer age; private String sex; private Department department; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex == null ? null : sex.trim(); } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Employee{" + "id=" + id + ", name=‘" + name + ‘\‘‘ + ", age=" + age + ", sex=‘" + sex + ‘\‘‘ + ", department=" + department + ‘}‘; } }
在employeeMapper.xml文件中配置
<?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="com.cn.dao.EmployeeMapper"> <resultMap id="BaseResultMap" type="com.cn.orm.Employee"> <result column="id" jdbcType="INTEGER" property="id" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="age" jdbcType="INTEGER" property="age" /> <result column="sex" jdbcType="CHAR" property="sex" /> <association property="department" javaType="com.cn.orm.Department"> <result column="dept_id" javaType="INTEGER" property="deptId"></result> <result column="dept_name" jdbcType="VARCHAR" property="deptName" /> </association> </resultMap> <select id="fetchEmployeesList" resultMap="BaseResultMap"> select e.id,e.name,e.age,e.sex,t.id as dept_id,t.name as dept_name from employee e left join department t on e.dept_id = t.id </select> </mapper>
说明两个类中具有同名属性id,name。若不指定别名,则会将属性名相同的赋值成相同的内容,无法达到联合查询的效果。
column为sql查询之后列的名称,property为java中属性字段名称
原文地址:https://www.cnblogs.com/noob-mengling/p/9338991.html
时间: 2024-10-13 12:55:47