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值选定要使用的自定义映射关系
相关推荐
悟能不能悟25 分钟前
在 MyBatis 的xml中,什么时候大于号和小于号可以不用转义
xml·java·mybatis
远方160929 分钟前
59-Oracle 10046事件-知识准备
大数据·数据库·sql·oracle·database
静听山水1 小时前
PostgreSQL/Hologres 外部数据包装器系统表 pg_foreign_data_wrapper 详解
数据库·postgresql
神洛华1 小时前
SQL Server基础语句1:基础查询、数据筛选 / 排序 、分组聚合
数据库·sql
DoWeixin61 小时前
【请关注】mysql一些经常用到的高级SQL
数据库·mysql
时序数据说1 小时前
时序数据库双存储引擎技术解析
大数据·数据库·物联网·开源·时序数据库·iotdb
远方16091 小时前
54-Oracle 23 ai DBMS_HCHECK新改变-从前的hcheck.sql
大数据·数据库·sql·oracle·database
Java初学者小白1 小时前
秋招Day14 - MySQL - 数据库架构
java·数据库·数据库架构
慌糖2 小时前
XML重复查询一条Sql语句??怎么解决
xml·数据库·sql
ybdesire2 小时前
MCPServer编程与CLINE配置调用MCP
android·java·数据库