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值选定要使用的自定义映射关系
相关推荐
武子康1 小时前
Java-171 Neo4j 备份与恢复 + 预热与执行计划实战
java·开发语言·数据库·性能优化·系统架构·nosql·neo4j
无敌最俊朗@1 小时前
02-SQLite 为了防止多人同时乱写,把整个数据库文件“当一本账本加锁”
jvm·数据库·oracle
小坏讲微服务1 小时前
MaxWell中基本使用原理 完整使用 (第一章)
大数据·数据库·hadoop·sqoop·1024程序员节·maxwell
赵渝强老师2 小时前
【赵渝强老师】MySQL集群解决方案
数据库·mysql
jason.zeng@15022072 小时前
my.cnf详解
运维·数据库·adb
百***62852 小时前
MySQL 常用 SQL 语句大全
数据库·sql·mysql
2501_915918412 小时前
移动端 HTTPS 抓包实战,多工具组合分析与高效排查指南
数据库·网络协议·ios·小程序·https·uni-app·iphone
百***6973 小时前
MySQL数据库(SQL分类)
数据库·sql·mysql
只因在人海中多看了你一眼3 小时前
B.40.5.1-数据库基础与核心原理
数据库
2503_928411563 小时前
11.11 Express-generator和文件上传和身份认证
数据库·node.js·express