mybatis中从列名到属性名的自动映射失败问题

2022-07-30 12:56:42

问题背景

从数据库中取出数据映射到实体类时,实体类中只有部分属性映射成功,其余属性值皆为null。

问题描述

如下图AreaDao.xml文件中描述了queryArea()方法从数据库获取Area对象的各个属性值的查询过程,最后执行查询结果显示只有属性priority被成功地赋值

AreaDao.xml

<select id="queryArea" resultType="com.imooc.wechatpro.model.Area">
        SELECT area_id, area_name, priority, create_time, last_edit_time
        FROM tb_area
        ORDER BY priority
        DESC
</select>
AreaDaoTest.java

Area area = areaDao.queryAreaById(3);
area = {Area@7489} 
 areaId = null
 areaName = null
 priority = {Integer@7513} 312
 createTime = null
 lastEditTime = null

数据库中对应的表tb_area:

mysql> select * from tb_area;
+---------+-----------+----------+-------------+----------------+
| area_id | area_name | priority | create_time | last_edit_time |
+---------+-----------+----------+-------------+----------------+
|       1 | 南苑      |      302 | NULL        | NULL           |
|       2 | 北苑      |      307 | NULL        | NULL           |
|       3 | 东苑      |      312 | NULL        | NULL           |
+---------+-----------+----------+-------------+----------------+

原因

实体类Area中的属性使用的是驼峰命名规则,默认情况下无法与数据库表的列名相匹配

Area.java

public class Area {

    private Integer areaId;

    private String areaName;

    private Integer priority;

    private Date createTime;

    private Date lastEditTime;
    ······
}

解决办法

在mybatis的配置文件mybatis-config.xml中将mapUnderscoreToCamelCase设为true,关于配置文件mybatis-config.xml的各种属性配置可以参考官方文档

<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>

当然这还没完,为了让文件mybatis-config.xml生效,需要将该文件的路径添加到全局配置文件application.properties(or application.yml)的配置中,如

application.properties

mybatis.config-location=classpath:mybatis-config.xml

在这里,我的mybatis-config.xml文件在resources目录下,因此使用路径classpath:mybatis-config.xml

  • 作者:franklin_lei
  • 原文链接:https://blog.csdn.net/franklin_lei/article/details/88222222
    更新时间:2022-07-30 12:56:42