MyBatis:自定义映射resultMap

如果字段名和属性名不一致,

比如数据库中 表Emp中字段名为emp_name,而定义的属性名为empName,

无法对应映射关系,就会发生下面情况

1.若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性名符合Java的规则(使用驼峰)。此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系

1.可以通过为字段起别名的方式,保证和实体类中的属性名保持一致

    <!--List<Emp> getAll();-->
    <select id="getAll" resultType="Emp">
        <!--select * from t_emp-->
       select emp_id empId,emp_name empName,emp_password password,email from t_emp
   </select>

2. 可以在MyBatis的核心配置文件中的`setting`标签中,设置一个全局配置信息mapUnderscoreToCamelCase,可以在查询表中数据时,自动将_类型的字段名转换为驼峰,例如:字段名user_name,设置了mapUnderscoreToCamelCase,此时字段名就会转换为userName。[核心配置文件详解](#核心配置文件详解)

```xml
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

 2.通过resultMap解决字段名和属性名的映射关系

  • 若字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射,即使字段名和属性名一致的属性也要映射,也就是全部属性都要列出来

    <resultMap id="empResultMap" type="Emp">
        <id property="empId" column="emp_id"></id>
        <result property="empName" column="emp_name"></result>
        <result property="password" column="password"></result>
        <result property="email" column="email"></result>
    </resultMap>
    <!--List<Emp> getAll();-->
    <select id="getAll" resultMap="empResultMap">
        <!--select * from t_emp-->
        select * from t_emp
    </select>

 

 

 

阅读剩余
THE END