Mybatis实体类属性和数据库字段对应关系总结

1. 别名对应

将字段的别名设置成和实体类属性一致。

xml 复制代码
<!-- 编写具体的SQL语句,使用id属性唯一的标记一条SQL语句 -->
<!-- resultType属性:指定封装查询结果的Java实体类的全类名 -->
<select id="selectEmployee" resultType="org.kkk.mybatis.entity.Employee">

  <!-- Mybatis负责把SQL语句中的#{}部分替换成"?"占位符 -->
  <!-- 给每一个字段设置一个别名,让别名和Java实体类中属性名一致 -->
  select emp_id empId,emp_name empName,emp_salary empSalary from t_emp where emp_id=#{maomi}

</select>

实体类属性是指: getXxx()方法、setXxx()方法把方法名中的get或set去掉,首字母小写。

2. 全局配置自动识别驼峰式命名规则

在Mybatis全局配置文件加入如下配置:

xml 复制代码
<!-- 使用settings对Mybatis全局进行设置 -->
<settings>

  <!-- 将xxx_xxx这样的列名自动映射到xxXxx这样驼峰式命名的属性名 -->
  <setting name="mapUnderscoreToCamelCase" value="true"/>

</settings>

SQL语句中可以不使用别名

xml 复制代码
<!-- Employee selectEmployee(Integer empId); -->
<select id="selectEmployee" resultType="com.atguigu.mybatis.entity.Employee">

  select emp_id,emp_name,emp_salary from t_emp where emp_id=#{empId}

</select>

3. 使用resultMap

使用resultMap标签定义对应关系,再在后面的SQL语句中引用这个对应关系

xml 复制代码
<resultMap id="selectEmployeeByRMResultMap" type="org.kkk.mybatis.entity.Employee">

  <id column="emp_id" property="empId"/>

  <result column="emp_name" property="empName"/>

  <result column="emp_salary" property="empSalary"/>

</resultMap>

<!-- Employee selectEmployeeByRM(Integer empId); -->
<select id="selectEmployeeByRM" resultMap="selectEmployeeByRMResultMap">

  select emp_id,emp_name,emp_salary from t_emp where emp_id=#{empId}

</select>

注意:

  • resultMap标签用来设定数据库字段和实体类书写之间的对应关系
    • 使用id标签设置主键列和主键属性之间的对应关系
      • column属性用于指定字段名;
      • property属性用于指定Java实体类属性名
    • result标签设置普通字段和Java实体类属性之间的关系
  • 在select语句中,可以直接根据resultMap的id值选定要使用的自定义映射关系
相关推荐
程序员小白条12 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
liulilittle12 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
郭涤生13 小时前
QT 架构笔记
java·数据库·系统架构
韩立学长13 小时前
基于Springboot流浪动物领养网站0kh2iyb4(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
DBA小马哥13 小时前
Oracle迁移到金仓数据库:完整迁移步骤与兼容性优化实战
数据库·oracle·国产化平替
@nengdoudou13 小时前
KStudio 客户端无法访问 KES 数据库服务器的指定 IP / 端口
数据库
宋军涛14 小时前
记一次Sqlserver数据库存储过程调用导致的连接池耗尽事件
数据库
前端小臻14 小时前
MySQL 错误 1005 (errno: 150) 深度解析与解决方案
数据库·mysql
魔镜前的帅比14 小时前
向量数据库原理
数据库·人工智能
Dev7z14 小时前
在MySQL里创建数据库
android·数据库·mysql