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值选定要使用的自定义映射关系
相关推荐
Hoshino.411 小时前
基于Linux中的数据库操作——下载与安装(1)
linux·运维·数据库
Oueii3 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
未来龙皇小蓝3 小时前
【MySQL-索引调优】11:Group by相关概念
数据库·mysql·性能优化
2401_831824963 小时前
使用Fabric自动化你的部署流程
jvm·数据库·python
njidf4 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
twc8294 小时前
大模型生成 QA Pairs 提升 RAG 应用测试效率的实践
服务器·数据库·人工智能·windows·rag·大模型测试
@我漫长的孤独流浪4 小时前
Python编程核心知识点速览
开发语言·数据库·python
2401_851272994 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
枕布响丸辣4 小时前
MySQL 从入门到精通:完整操作手册与实战指南
数据库·mysql
电商API&Tina4 小时前
【电商API接口】开发者一站式电商API接入说明
大数据·数据库·人工智能·云计算·json