好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

问题背景

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

问题描述

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

AreaDao.xml

?

1

2

3

4

5

6

< 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 >

?

1

2

AreaDaoTest.java

Area area = areaDao.queryAreaById( 3 );

?

1

2

3

4

5

6

area = {Area @7489 }

  areaId = null

  areaName = null

  priority = {Integer @7513 } 312

  createTime = null

  lastEditTime = null

数据库中对应的表tb_area:

?

1

2

3

4

5

6

7

8

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中的属性使用的是驼峰命名规则,默认情况下无法与数据库表的列名相匹配

?

1

2

3

4

5

6

7

8

9

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的各种属性配置可以参考官方文档

?

1

2

3

4

5

< configuration >

     < settings >

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

     </ settings >

</ configuration >

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

?

1

2

application.properties

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

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

mybatis 无法找到映射错误

mybatis 中报错:

Result Maps collection does not contain value for com测试数据mon.pojo.User

其中是因为在mapper.xml文件中的resultMap ,没有设置正确,没有将sql的列名与pojo类的属性名保持一致

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/franklin_lei/article/details/88222222

查看更多关于mybatis 解决从列名到属性名的自动映射失败问题的详细内容...

  阅读:20次