mybatis Resolves Automatic Mapping Failure from Column Names to Attribute Names

  • 2021-10-13 07:49:10
  • OfStack

Problem background

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

Problem description

The following figure AreaDao. xml file describes the query process of the queryArea () method to obtain each attribute value of the Area object from the database, and the final query result shows that only the attribute priority is successfully assigned


<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
Area area = areaDao.queryAreaById(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> select * from tb_area;
| area_id | area_name | priority | create_time | last_edit_time |
|       1 |  South Garden       |      302 | NULL        | NULL           |
|       2 |  Bei Yuan       |      307 | NULL        | NULL           |
|       3 |  East Court       |      312 | NULL        | NULL           |


Attributes in the entity class Area use the hump naming convention and cannot match the column names of database tables by default
public class Area {
    private Integer areaId;
    private String areaName;
    private Integer priority;
    private Date createTime;
    private Date lastEditTime;
     Exactly Exactly Exactly Exactly Exactly 


Set mapUnderscoreToCamelCase to true in the configuration file mybatis-config. xml of mybatis. Please refer to the official documents for various attribute configurations of the configuration file mybatis-config. xml

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

Of course, for the file mybatis-config. xml to take effect, you need to add the path to the configuration of the global configuration file application. properties (or application. yml), as shown in

Here, my mybatis-config. xml file is in the resources directory, so use the path classpath: mybatis-config. xml

mybatis Unable to find mapping error

Error reported in mybatis:

Result Maps collection does not contain value for com.common.pojo.User

This is because resultMap in the mapper. xml file is not set correctly, and the column name of sql and the attribute name of pojo class are not kept as 1

Related articles: