在Mybatis中进行基本数据查询的时候,如根据ID查询数据,实体类属性名和数据库表查询返回的字段名一致,Mybatis会自动封装。
如果实体类属性名和数据库表查询返回的字段名不一致,则不会自动封装。
数据封装的三种方法
1.起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一致。
@Select("select id, username, password, name, gender, image, job, entrydate, dept id deptld, create_time createTime, update_time updateTime from emp where id = #id) ")
public Emp getByld(Integer id);
2.手动结果映射:通过@Results和@Result进行结果映射。
@Select("select * from emp where id = #{id}")
@Results({
@Result(column ="dept id", property = "deptld"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "update_time", property = "updateTime")})
public Emp getByld(Integer id);
3.开启驼峰命名:如果字段名与属性名符合驼峰命名规则,Mybatis会自动通过驼峰命名规则映射。(推荐)
在src目录下找到resources文件夹,在其application.properties配置文件中配置以下内容。
#开启驼峰命名自动映射,即从数据库字段名 a column 映射到Java属性名 aColumn.
mybatis.configuration.map-underscore-to-camel-case=true