mybatis数据库字段名和实体类属性名不一致(四)

一、问题出现原因

      分析:如果数据库中有一些字段是user_name等复杂方式命名,而数据库实体类中的相应字段是username,这种情况常常会导致我们数据库语句查询不到报错,主要原因就是数据库字段映射不到实体类上,解决这个问题的方案主要有三种方式:

     1、在sql语句中使用别名:

<select id="queryUserById" resultType="com.zpc.mybatis.pojo.User">
   select
    tuser.id as id,
    tuser.user_name as userName,
    tuser.password as password,
    tuser.name as name,
    tuser.age as age,
    tuser.birthday as birthday,
    tuser.sex as sex,
    tuser.created as created,
    tuser.updated as updated
    from
    tb_user tuser
    where tuser.id = #{id};
</select>

       2、resultMap强制映射的方式解决

 <resultMap id="user" type="com.achuan.demo.entity.User">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="user_name" property="username" jdbcType="VARCHAR"/>
        <result column="telephone" property="telephone" jdbcType="VARCHAR"/>
        <result column="imax_email" property="iMaxEmail" jdbcType="VARCHAR"/>
        <result column="sex" property="sex" jdbcType="VARCHAR"/>
        <result column="age" property="age" jdbcType="INTEGER"/>
    </resultMap>

     3、驼峰匹配 — mybatis-config.xml 

          在mybatis全局文件中加入下面这个配置

<configuration>
    <!-- 开启驼峰映射 ,为自定义的SQL语句服务-->
    <!--设置启用数据库字段下划线映射到java对象的驼峰式命名属性,默认为false-->  
    <settings>
      <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
 
</configuration>

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值