若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性
名符合Java的规则(使用驼峰)。此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系。
第一种处理方法:为字段起别名,使之与属性名一致
<select id="getEmpByEmpIdOld" resultType="Emp">
select emp_id empId,emp_name empName,age,gender from t_emp where emp_id = #{empId}
</select>
第二种处理方法:可以在MyBatis的核心配置文件中设置一个全局配置、mapUnderscoreT-oCamelCase,可以在查询表中数据时,自动将_类型的字段名转换为驼峰。
例如:字段名user_name,设置了mapUnderscoreToCamelCase,此时字段名就会转换为
userName
<settings>
<!--将下划线映射为驼峰-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<select id="getEmpByEmpIdOld" resultType="Emp">
select * from t_emp where emp_id = #{empId}
</select>
第三种方法是使用resultmap来处理
resultMap:设置自定义的映射关系 id:唯一标识 type:处理映射关系的实体类的类型 常用的标签: id:处理主键和实体类中属性的映射关系 result:处理普通字段和实体类 中属性的映射关系 association:处理多对一的映射关系(处理实体类类型的属性) collection:处理一对多的映射关系(处理集合类型的属性) 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 empId);-->
<select id="getEmpByEmpId" resultMap="empResultMap">
select * from t_emp where emp_id = #{empId}
</select>