MyBatis 字段映射的解决方案
引言
在使用 MyBatis 进行数据库操作时,数据库字段名(如下划线命名 delete_flag)与 Java 实体类属性名(驼峰命名 deleteFlag)之间的映射是一个常见问题。本文将介绍三种解决方案:手动 @Results 映射、可复用的 @Results(id) 映射以及全局驼峰命名配置。
首先,我们定义一个实体类UserInfo,后续所有示例都基于这个类:
public class UserInfo {
private Integer id;
private String username;
private String password;
private Integer age;
private String gender;
private String phone;
private Integer deleteFlag; // 数据库字段 delete_flag
private Date createTime; // 数据库字段 create_time
private Date updateTime; // 数据库字段 update_time
// getter / setter 省略
}手动 @Results 映射
最直接的方式是在每个查询方法上使用 @Results 注解,手动指定字段映射关系。
@Mapper
public interface UserInfoMapper {
@Results({
@Result(column = "delete_flag", property = "deleteFlag"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "update_time", property = "updateTime")
})
@Select("select * from user_info")
List<UserInfo> selectAll();
// 另一个查询方法,需要重复写一遍 @Results
@Results({
@Result(column = "delete_flag", property = "deleteFlag"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "update_time", property = "updateTime")
})
@Select("select * from user_info where id = #{id}")
UserInfo selectById(Integer id);
}可复用的 @Results(id) 映射
为了解决重复代码问题,MyBatis 允许为@Results 注解指定一个 id,其他方法可以通过 @ResultMap 引用该映射。
@Mapper
public interface UserInfoMapper {
@Results(id = "BaseMap", value = {
@Result(column = "delete_flag", property = "deleteFlag"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "update_time", property = "updateTime")
})
@Select("select * from user_info")
List<UserInfo> selectAll();
// 直接引用上面定义的 BaseMap,无需重复写 @Results
@ResultMap(value = "BaseMap")
@Select("select * from user_info where id = #{id}")
UserInfo selectById(Integer id);
// 再多一个方法也能复用
@ResultMap(value = "BaseMap")
@Select("select * from user_info where username = #{username}")
UserInfo selectByUsername(String username);
}全局驼峰命名自动转换
如果数据库字段命名规范统一(如下划线命名),最优雅的方式是开启 MyBatis 的全局驼峰命名自动转换功能。
# application.yml
mybatis:
configuration:
map-underscore-to-camel-case: true # 配置驼峰自动转换开启后,Mapper 接口变得极其简洁,无需任何 @Results 注解:
@Mapper
public interface UserInfoMapper {
@Select("select * from user_info")
List<UserInfo> selectAll();
@Select("select * from user_info where id = #{id}")
UserInfo selectById(Integer id);
@Select("select * from user_info where username = #{username}")
UserInfo selectByUsername(String username);
}MyBatis 会自动将 delete_flag 映射为 deleteFlag,create_time 映射为 createTime,
建议在项目初期就统一数据库命名规范,并开启 map-underscore-to-camel-case 配置,这样可以最大程度减少冗余的映射代码。
到此这篇关于MyBatis 字段映射的解决方案的文章就介绍到这了,更多相关mybatis 字段映射内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot 2.0 整合sharding-jdbc中间件实现数据分库分表
这篇文章主要介绍了SpringBoot 2.0 整合sharding-jdbc中间件,实现数据分库分表,本文图文并茂给大家介绍的非常详细,具有一定的参考借鉴价值 ,需要的朋友可以参考下2019-06-06
详解Spring系列之@ComponentScan批量注册bean
本文介绍各种@ComponentScan批量扫描注册bean的基本使用以及进阶用法和@Componet及其衍生注解使用,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧2022-02-02


最新评论