MyBatis:自定义映射resultMap
如果字段名和属性名不一致,
比如数据库中 表Emp中字段名为emp_name,而定义的属性名为empName,
无法对应映射关系,就会发生下面情况
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 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>
阅读剩余
版权声明:
作者:Tin
链接:http://www.tinstu.com/1252.html
文章版权归作者所有,未经允许请勿转载。
THE END