自定義映射resultMap

resultMap處理字段和屬性的映射關系如果字段名與實體類中的屬性名不一致,該如何處理映射關系?

  • 第一種方法:為查詢的字段設置別名,和屬性名保持一致
    下面是實體類中的屬性名:
    private Integer empId;private String empName;private Integer age;private String gender;這是建表時設置的字段名:
    emp_idemp_nameagegender我們只需要在Mapper.xml中在寫sql語句時,對字段名進行設置別名,使得與屬性名一致:
    select emp_id empId,emp_name empName,age,gender from t_emp where emp_id = #{empId}
  • 第二種方法:當字段符合Mysql要求使用下劃線,而屬性名符合Java要求使用駝峰,此時可以在Mybatis的核心配置文件中設置一個全局配置信息mapUnderscoreToCamelCase,就可以在查詢表中數據時,自動將下劃線類型的字段名轉換為駝峰 。
    <settings><!--將下劃線映射為駝峰--><setting name="mapUnderscoreToCamelCase" value="https://www.huyubaike.com/biancheng/true"/> </settings>
  • 第三種方法:使用resultMap處理
    <!--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></resultMap><!-- Emp getEmpByEmpId(@Param("empId") Integer emId);--><select id="getEmpByEmpId" resultMap="empResultMap">select * from t_emp where emp_id = #{empId}</select>
多對一的映射關系1.級聯方式處理映射關系當Emp實體類中具有Dept對象,但是字段中不存在這個屬性,我們需要將Dept對象中的屬性與查詢的字段名建立映射關系 。
<resultMap id="empAndDeptResultMap" 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="dept.deptId"></result><result column="dept_name" property="dept.deptName"></result></resultMap><select id="getEmpAndDeptByEmpId" resultMap="empAndDeptResultMap">select t_emp.*,t_dept.*from t_emp left join t_dept on t_emp.dept_id = t_dept.dept_idwhere t_emp.emp_id = #{empId}</select>2.使用association處理映射關系
  • association:處理多對一的映射關系(處理實體類類型的屬性)
  • property:設置需要處理映射關系的屬性的屬性名
  • javaType:設置要處理的屬性的類型
<resultMap id="empAndDeptResultMap" 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><association property="dept" javaType="Dept"><id column="dept_id" property="deptId"></id><result column="dept_name" property="deptName"></result></association></resultMap>3.分步查詢