5-Mybatis-ResultMap

1-解决属性名和字段名不一致的问题

根据 4-配置详解.md 中的代码,将User.java中的pwd修改为password,这将导致字段不匹配

现象:

执行UserMapperTest.java中的getUserByIdTest()方法,得到返回值,但其中的pwd为空

User{id=1, name='ckj', pwd='null'}

原因:

UserMapper.xml中的SQL语句

select * from user where id = #{id};

根据数据库的结构(字段名)可知,其本质是

select id,name,pwd from user where id = #{id};

sql语句找到的数据,经过类型处理器处理,会找到其对应的字段,将找到的数据赋值给实体类字段,但pwdpassword并不对应,所以,此时将数据赋值给idname,而passwordnull

解决方法

1.1-别名

只要让pwd as password即可

<select id="getUserById" parameterType="int" resultType="config.pojo.User">
    select id,name,pwd as password from user where id = #{id};
</select>

1.2-resultMap

结果集映射

id ——> id
name ——> name
pwd ——> password

更改UserMapper.xml的代码

<!--id 对应的resultMap编号 type 对应的实体类-->
<resultMap id="UserMap" type="config.pojo.User">
    <!--column 数据库中的字段 property 实体类中的属性-->
    <result column="id" property="id"></result>
    <result column="name" property="name"></result>
    <result column="pwd" property="password"></result>
</resultMap>

<select id="getUserById" parameterType="int" resultMap="UserMap">
    select *
    from user
    where id = #{id};
</select>

对应的SQL语句中,resultMap属性指定了采用的映射对应所的id,同级,实现相应的映射resultMap,其中,id为编号,type为对应的实体类,其下,column对应数据库中的字段,property对应实体类中的属性

ResultMap 的优秀之处——完全可以不用显式地配置它们,即不需要更改的字段不用手动配置,即将第一行和第二行result删去

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值