mybatis-相关配置和resultmap-爱代码爱编程
配置解析
二级目录
三级目录
ResultMap
主要作用: 属性名和字段名不一致
提出问题
查询为null的解决方法
前提条件:
查询数据库中目标表USER中的字段为 id,name,pwd;
在Java中定义的实体类为 id,name,password;
public class User {
private int id; //id
private String name; //姓名
private String password; //密码和数据库不一样!
//构造
//set/get
//toString()
}
期间两者字段不能一一对应
接口如下:
//根据id查询用户
User selectUserById(int id);
mapper内容:
<select id="selectUserById" resultType="User ">
select * from user where id = #{id}
</select>
如此查询,在java实例中使用时,必然会出现password的字段为空的情况,这是两者字段所不想匹配的场合;
mybatis会根据这些查询的列名(会将列名转化为小写,数据库不区分大小写) , 去对应的实体类中查找相应列名的set方法设值 , 由于找不到setPwd() , 所以password返回null ; 【自动映射】
解决方案
指定别名
再SQL中通过as的方式指定别名,使查出的数据字段与实体类中的字段的属性名相一致;
别名设定如下:
select
id,
name,
pwd as password --通过赋别名的方式可以解决上述问题
from
USER
<select id="selectUserById" resultType="User">
select id , name , pwd as password from user where id = #{id}
</select>
使用ResultMap(结果集映射)
<resultMap id="UserMap" type="User">
<!-- id为主键 -->
<id column="id" property="id"/>
<!-- column是数据库表的列名 , property是对应实体类的属性名 -->
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="selectUserById" resultMap="UserMap">
select id , name , pwd from user where id = #{id}
</select>