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

当数据库字段名与实体类属性名不一致时,MyBatis的ResultMap能解决这一问题。通过创建ResultMap,定义column(数据库字段)和property(实体类属性)的映射关系,可以避免硬编码字段别名。例如,将数据库中的'pwd'字段映射到实体类的'password'属性,只需在ResultMap中列出改动的属性即可。这样简化了XML配置,提高了代码的可读性。
摘要由CSDN通过智能技术生成

数据库的字段:
在这里插入图片描述
在这里插入图片描述
结果:
在这里插入图片描述
password接收不到正确信息

原因:
UserMapper.xml中
在这里插入图片描述

    <select id="getUserById" parameterType="int" resultType="com.xie.pojo.User">
        select * from mybatis.user where id = #{id}
    </select>

这里这句话,会自动转换成

    <select id="getUserById" parameterType="int" resultType="com.xie.pojo.User">
        select id,name,pwd from mybatis.user where id = #{id}
    </select>

解决方法:

1、暴力起别名

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

2、resultMap

结果集映射

  • resultMap 元素是MyBatis中最重要最强大的元素
  • ResultMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句,只需要描述它们的关系就行了
  • ResultMap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们

原来: id name pwd
改后: id name password

在这里插入图片描述
1、column是数据库中的字段,property是实体类中的属性

2、select 中的 resultMap 中的名字,要和 resultMap 中的 id 中的名字一样

3、type实际是com.xie.pojo.User,但是我在前面已经改过别名了

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--        namespace绑定一个对应的Dao接口(也可以叫Mapper接口)-->
<mapper namespace="com.xie.dao.UserMapper">


    <resultMap id="UserMap" type="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" resultMap="UserMap">
        select * from mybatis.user where id = #{id}
    </select>

</mapper>
  • ResultMap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们

所以上面可以改为:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--        namespace绑定一个对应的Dao接口(也可以叫Mapper接口)-->
<mapper namespace="com.xie.dao.UserMapper">


    <resultMap id="UserMap" type="user">
<!--        column是数据库中的字段,property是实体类中的属性-->

        <result column="pwd" property="password"></result>
    </resultMap>

    <select id="getUserById" resultMap="UserMap">
        select * from mybatis.user where id = #{id}
    </select>

</mapper>

只用列出改了名字的属性就行了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值