问题描述
今天在做测试的时候使用Mybatis查询了一个简单的person表,但是发现带有person_name属性没办法查到。最开始以为是中文问题,但是表中性别也是中文,就能查到,就很奇怪。自己试了半天,发现只要把字段名称改为没有下划线的名称并且实体类对应成员变量名改为全小写的变量名就能查到。
person表:
![](https://i-blog.csdnimg.cn/blog_migrate/a9a96c048e7c99bbd9613e97392d495d.png)
![](https://i-blog.csdnimg.cn/blog_migrate/9e882598873b8f3a8b52ca0a0c6cdb1b.png)
实体类:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable {
@Serial
private static final long serialVersionUID = 398328312809817705L;
/**
* Id
*/
private Integer id;
/**
* 姓名
*/
private String personName;
/**
* 性别
*/
private String sex;
/**
* 年龄
*/
private Integer age;
}
personMapper.xml (已设置路径别名)
<select id="selectById" resultType="Person" parameterType="integer">
select *
from person
where id=#{id}
</select>
Dao方法:
/**
* 根据id查找对应的Person
* @param id Person的id
* @return Person对象
*/
Person selectById(@Param("id") Integer id);
测试类:
@SpringBootTest
class SiTechSpringbootApplicationTests {
@Resource
PersonDao personDao;
@Test
void contextLoads() {
System.out.println(personDao.selectById(100001));
}
}
查询结果:
解决方法:
其一,在application.yml(.properties)中开启MyBatis的驼峰映射(Springboot项目)
mybatis:
configuration:
map-underscore-to-camel-case: true
其二,在你的MyBatis的配置文件(不是Mapper文件!!!)开启驼峰映射
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
其三,直接使用MyBatisplus对MyBatis进行扩展!!!(如果可以)
总结
因为Mybatisplus用多了,渐渐地原生MyBatis的注意事项也都忘光光,碰到这个问题也可以借此机会重新复习以下原生MyBatis。
如有大佬发现问题,还请指正,谢谢。