今天在做测试的时候使用Mybatis查询了一个简单的person表,但是发现带有person_name属性没办法查到。最开始以为是中文问题,但是表中性别也是中文,就能查到,就很奇怪。自己试了半天,发现只要把字段名称改为没有下划线的名称并且实体类对应成员变量名改为全小写的变量名就能查到。
person表:
实体类:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable {
@Serial
private static final long serialVersionUID = 398328312809817705L;
private Integer id;
private String personName;
private String sex;
private Integer age;
}
personMapper.xml (已设置路径别名)
select * from person where id=#{id}
Dao方法:
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文件!!!)开启驼峰映射
其三,直接使用MyBatisplus对MyBatis进行扩展!!!(如果可以) 总结
因为Mybatisplus用多了,渐渐地原生MyBatis的注意事项也都忘光光,碰到这个问题也可以借此机会重新复习以下原生MyBatis。
如有大佬发现问题,还请指正,谢谢。



