1.简单的映射
作用:解决表中字段和和实体类中字段不一致的情况,通过建立一种映射关系使其一一对应
<!--id指定map唯一id,type指定映射javaBean类型,可以写全类名也可以写类名让mybatis自己去找-->
<resultMap id="brandResultMap" type="brand">
<!--colum指的是表中字段,property指的是java中属性名-->
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
</resultMap>
在mapper.xml的sql中resultMap属性指定映射map
<!--sql中指定映射-->
<select id="selectAll" resultMap="brandResultMap">
select *
from tb_brand;
</select>
2.当需要返回给前端的对象类中包含对象属性,对象属性也需要映射时,如下类
3.当需要查询的对象中有list属性时
主类:
package com.xyj.entity;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
private int eid;
private String ename;
private String epwd;
private String address;
private String tel;
private List<Sport> sports;//职员所参加的所有运动项目
}
集合泛型类
package com.xyj.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Sport {
private int sportId;
private String sportName;
private String sportScore;
}
xml
<select id="findSportsInfoByEmpId" resultMap="empmap">
select e.*,s.*
from employee as e,sport as s
where e.eid=s.eid
and e.eid=#{eid}
</select>
<resultMap type="Employee" id="empmap">
<id property="eid" column="eid"/>
<result property="ename" column="ename"/>
<result property="epwd" column="epwd"/>
<result property="address" column="address"/>
<result property="tel" column="tel"/>
<!-- collection描述一对多的关系,property是集合属性名,ofType是集合所包含的类型,可以写完整Java类名或别名 -->
<collection property="sports" ofType="Sport">
<id property="sportId" column="sportid"/>
<result property="sportName" column="sportname"/>
<result property="sportScore" column="sportscore"/>
</collection>
</resultMap>
以上不能达到复用的效果,以下可以
<select id="findSportsInfoByEmpId" resultMap="empmap">
select e.*,s.*
from employee as e,sport as s
where e.eid=s.eid
and e.eid=#{eid}
</select>
<resultMap type="Employee" id="empmap">
<id property="eid" column="eid"/>
<result property="ename" column="ename"/>
<result property="epwd" column="epwd"/>
<result property="address" column="address"/>
<result property="tel" column="tel"/>
<collection property="sports" ofType="Sport" resultMap="sportmap"></collection>
</resultMap>
<resultMap type="Sport" id="sportmap">
<id property="sportId" column="sportid"/>
<result property="sportName" column="sportname"/>
<result property="sportScore" column="sportscore"/>
</resultMap>