mybatis:自定义映射关系resultMap
创建表t_emp
定义实体类
package org.example.entity; public class Emp { private Integer empId; private String empName; private Integer age; private String gender; private Integer deptId; public Emp() { } public Emp(Integer empId, String empName, Integer age, String gender, Integer deptId) { this.empId = empId; this.empName = empName; this.age = age; this.gender = gender; this.deptId = deptId; } public Integer getEmpId() { return empId; } public void setEmpId(Integer empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Integer getDeptId() { return deptId; } public void setDeptId(Integer deptId) { this.deptId = deptId; } @Override public String toString() { return "Emp{" + "empId=" + empId + ", empName='" + empName + '\'' + ", age=" + age + ", gender='" + gender + '\'' + ", deptId=" + deptId + '}'; } }
mapper接口
public interface EmpMapper { public Emp queryEmpById(@Param("id") int id); }
EmpMapper.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="org.example.mapper.EmpMapper"> <!-- resultMap:设置自定义映射关系 id:唯一标识 type:处理映射关系的实体类的类型 常用的标签: id:处理主键和实体类中属性的映射关系 result:处理普通字段实体类中属性的映射关系 column:设置映射关系中的字段名,必须是sql查询出的某个字段 property:设置映射关系中的属性的属性名,必须是处理的实体类类型中的属性名 --> <resultMap id="empResultMap" type="emp"> <id column="emp_id" property="empId"></id> <result column="emp_name" property="empName"></result> <result column="age" property="age"></result> <result column="gender" property="gender"></result> <result column="dept_id" property="deptId"></result> </resultMap> <select id="queryEmpById" resultMap="empResultMap"> select * from t_emp where emp_id = #{id} </select> </mapper>
测试代码
@Test public void queryEmpById(){ SqlSession sqlSession = SqlSessionUtil.getSqlSession(); EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); Emp emp = mapper.queryEmpById(2); System.out.println(emp); sqlSession.close(); }