SoFunction
Updated on 2025-03-08

mybatis solves the problem of automatic mapping from column names to attribute names failed

Problem background

When the data is extracted from the database and mapped to the entity class, only some attributes in the entity class are mapped successfully, and the other attribute values ​​are null.

Problem description

The query process of queryArea() method obtaining the various attribute values ​​of the Area object from the database in the following figure describes the queryArea() method. Finally, the query result shows that only the attribute priority is successfully assigned.

<select  resultType="">
        SELECT area_id, area_name, priority, create_time, last_edit_time
        FROM tb_area
        ORDER BY priority
        DESC
</select>

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

The corresponding table tb_area in the database:

mysql&gt; select * from tb_area;
+---------+-----------+----------+-------------+----------------+
| area_id | area_name | priority | create_time | last_edit_time |
+---------+-----------+----------+-------------+----------------+
|       1 | Nanyuan      |      302 | NULL        | NULL           |
|       2 | Beiyuan      |      307 | NULL        | NULL           |
|       3 | Dongyuan      |      312 | NULL        | NULL           |
+---------+-----------+----------+-------------+----------------+

reason

The properties in the entity class Area use camel naming rules, which cannot match the column names of the database table by default.


public class Area {
    private Integer areaId;
    private String areaName;
    private Integer priority;
    private Date createTime;
    private Date lastEditTime;
    ······
}

Solution

Set mapUnderscoreToCamelCase to true in mybatis configuration file. For various attribute configurations of the configuration file, please refer toOfficial Documentation

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

Of course this is not over yet. In order for the file to take effect, the path of the file needs to be added to the configuration of the global configuration file (or), such as


-location=classpath:

Here, my file is in the resources directory, so use the path classpath:

mybatis cannot find mapping error

Mybatis reported an error:

Result Maps collection does not contain value for

This is because the resultMap in the file is not set correctly, and the column name of the sql is not consistent with the attribute name of the pojo class.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.