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值选定要使用的自定义映射关系
相关推荐
橙露13 分钟前
Spring Boot 核心原理:自动配置机制与自定义 Starter 开发
java·数据库·spring boot
冰暮流星14 分钟前
sql语言之分组语句group by
java·数据库·sql
符哥200815 分钟前
Ubuntu 常用指令集大全(附实操实例)
数据库·ubuntu·postgresql
C++ 老炮儿的技术栈32 分钟前
Qt 编写 TcpClient 程序 详细步骤
c语言·开发语言·数据库·c++·qt·算法
怣5042 分钟前
MySQL子查询零基础入门教程:从小白到上手(零基础入门版)
数据库·mysql
码界调试侠1 小时前
MongoDB 常用查询语法
数据库·mongodb
静听山水1 小时前
StarRocks导入数据【Stream Load】
数据库
藦卡机器人1 小时前
国产机械臂做的比较好的品牌有哪些?
大数据·数据库·人工智能
jiunian_cn1 小时前
【Redis】数据库管理操作
数据库·redis·缓存
_Johnny_2 小时前
ETCD 配额/空间告警模拟方案
网络·数据库·etcd