字段名和属性名不一致的情况,如何处理映射关系
使用resultMap自定义映射
<!-- 使用resultMap完成实体的属性名称和表字段名称的映射-->
<!-- id唯一标识,type处理映射关系的实体类的类型-->
<resultMap id="brandResultMap" type="brand">
<!-- id设置主键与属性的映射关系,result设置普通字段与属性的映射关系
column:设置映射关系中的字段名,必须是sql查询出的某个字段,property:设置映射关系中的属性的属性名,必须是处理的实体类类型中的属性名 association:处理多对一映射关系
fetchType:在开启了延迟加载的环境中,通过该属性设置当前的分步查询是否使用延迟加载fetchType="eager(立即加载)/Lazy(延迟加载)“
-->
<result property="brandName" column="brand_name" />
<result property="companyName" column="company_name" />
</resultMap>
<!--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>
<!--Emp{empId=1,empName= '张三', age=20,gender='男', dept=Dept{deptId=1,deptName- 'A'}}
-->
<!--分布查询-->
<resultMap id="empAndDeptBystepResultMap" 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>
<!--
property :设置需要处理映射关系的属性的属性名select:设置分步查询的sqL的唯一标识
column :将查询出的某个字段作为分步查询的sql的条件-->
<association property="dept"
select="com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptBystepTwo"
column="dept_id"></association>
< /resultMap>
public interface DeptMapper {
<!--
通过分步查询查询员工以及所对应的部i门信息的第二步-->
Dept getEmpArFDeptBystepTwo(@Param( "deptId") Integer deptId);
}
xml:
<select id="getEmpAndDeptBystepTwo" resultType="Dept">
select * from t_dept where dept_id = #{ deptId}</select>
当字段符合MysQL的要求使用,而属性符合java的要求使用驼峰,此时可以在Mybatis核心配置文件中设置一个全局配置,可以自动将下划线映射为驼峰
<settings>
<!--将下划线映射为驼峰-->
<setting name="mapunderscoreTocame1case" va1ue="true"/>
</ settings>










网友评论