引用场景
- 当实体类属性名和数据库中的字段名不一样的时候,可以采用result进行映射
- 在多表查询的时候,可以建立映射以简化数据库操作
- 另外:解决属性名和字段名不匹配问题也可以在sql语句中用as起别名(较为繁琐)
属性名和字段名不匹配(一般是查表容易忽略)
MyBatis 会在幕后自动创建一个 ResultMap,再根据属性名来映射列到 JavaBean 的属性上。如果列名和属性名不能匹配上,可以在 SELECT 语句中设置列别名
mapper映射语句
<select id="getUsers" resultType="com.LinXiaoDe.pojo.User">
select * from mybatis_db.user_t
</select>
这种情况就出现不匹配的情况,pwd和password不匹配,结果为空
解决方法1:sql语句用as映射
<select id="getUsers" resultType="com.LinXiaoDe.pojo.User">
select * from mybatis_db.user_t
</select>
------------->
<select id="getUsers" resultType="com.LinXiaoDe.pojo.User">
select id,userName,password as pwd from mybatis_db.user_t
</select>
解决方法2:resultMap映射
resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来,并在一些情形下允许你进行一些 JDBC 不支持的操作。ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
- 以后数据库的命名一般是下划线的命名方式
<resultMap id="getUserResultMap" type="com.LinXiaoDe.pojo.User">
<id property="id" column="id"/>
<id property="userName" column="userName"/>
<id property="pwd" column="password"/>
</resultMap>
<select id="getUsers" resultMap="getUserResultMap">
select id,userName,password from mybatis_db.user_t
</select>