MyBatis 详解及代码示例

MyBatis 是一个 半自动 ORM 框架,主要用于 Java 与数据库之间的持久化操作,它本质是对 JDBC 的封装

  • 全名:MyBatis(前身 iBATIS)
  • 核心作用:自动将 SQL 执行结果映射为 Java 对象;也可以将 Java 对象自动转成 SQL 参数
  • 特点
    • SQL 写在 XML 或注解中,开发者可控制 SQL 逻辑(相比 Hibernate 更灵活)
    • 支持参数映射、结果映射
    • 支持动态 SQL(根据条件生成 SQL)

🏗️ 1. 在 SpringMVC 项目中的使用步骤


🌱 一、技术栈说明

  • Spring MVC(控制层)
  • MyBatis(持久层)
  • Spring(IoC、事务管理)
  • MySQL 数据库
  • Maven 构建

🧱 二、项目结构示意(SpringMVC 示例)

spring-mybatis-demo/
├── src/main/java/
│   ├── com.example.controller/     # 控制层
│   ├── com.example.service/        # 业务逻辑
│   ├── com.example.mapper/         # MyBatis Mapper 接口
│   ├── com.example.model/          # 实体类
│   └── com.example.config/         # 配置类(可选)
├── src/main/resources/
│   ├── mapper/                     # MyBatis XML 映射文件
│   ├── spring-mybatis.xml          # 核心整合配置
│   └── db.properties               # 数据源配置
├── webapp/
│   ├── WEB-INF/
│   │   ├── jsp/                    # 视图层 JSP
│   │   └── web.xml                 # Web 配置
└── pom.xml

📦 三、核心配置文件

3.1 pom.xml(关键依赖)
<dependencies><!-- Spring 核心依赖 --><dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId><version>5.3.30</version></dependency><!-- MyBatis --><dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.15</version> </dependency><dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.1.1</version> </dependency><!-- MySQL 驱动 --><dependency><groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.30</version> </dependency><!-- 其他:日志、JSTL、Servlet 等 -->
</dependencies>

3.2 db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/testdb
jdbc.username=root
jdbc.password=123456

3.3 spring-mybatis.xml(Spring + MyBatis 整合配置)
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="..."><!-- 1. 读取属性配置 --><context:property-placeholder location="classpath:db.properties"/><!-- 2. 配置数据源 --><bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!-- 3. 配置 SqlSessionFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="mapperLocations" value="classpath:mapper/*.xml"/><property name="typeAliasesPackage" value="com.example.model"/></bean><!-- 4. Mapper 接口扫描 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.example.mapper"/></bean><!-- 5. 扫描 Service、Controller --><context:component-scan base-package="com.example"/><!-- 6. 事务管理 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

3.4 web.xml 配置 Spring MVC 和核心监听器
<web-app ...><!-- Spring 容器监听器 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mybatis.xml</param-value></context-param><!-- Spring MVC 核心配置 --><servlet><servlet-name>spring</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>spring</servlet-name><url-pattern>/</url-pattern></servlet-mapping>
</web-app>

💻 四、代码示例

4.1 实体类 User.java
public class User {private Integer id;private String name;private Integer age;// Getter / Setter
}

4.2 Mapper 接口 UserMapper.java
java复制编辑public interface UserMapper {User selectById(Integer id);List<User> selectAll();
}

4.3 Mapper XML 文件 UserMapper.xml
<mapper namespace="com.example.mapper.UserMapper"><select id="selectById" resultType="User">SELECT * FROM user WHERE id = #{id}</select><select id="selectAll" resultType="User">SELECT * FROM user</select>
</mapper>

4.4 Service 类
@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public User getUser(Integer id) {return userMapper.selectById(id);}public List<User> getAllUsers() {return userMapper.selectAll();}
}

4.5 Controller 类
@Controller
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@RequestMapping("/list")public String list(Model model) {List<User> users = userService.getAllUsers();model.addAttribute("users", users);return "userList"; // 对应 userList.jsp}
}

4.6 JSP 页面(视图层)userList.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
<h2>User List</h2>
<table border="1"><tr><th>ID</th><th>Name</th><th>Age</th></tr><c:forEach var="u" items="${users}"><tr><td>${u.id}</td><td>${u.name}</td><td>${u.age}</td></tr></c:forEach>
</table>
</body>
</html>

💡 五、动态 SQL 示例(补充)

可以在 UserMapper.xml 中这样写:

<select id="searchUser" resultType="User">SELECT * FROM user<where><if test="name != null and name != ''">AND name LIKE CONCAT('%', #{name}, '%')</if><if test="age != null">AND age = #{age}</if></where>
</select>

调用时只传入某些字段,MyBatis 会自动拼接对应 SQL 语句。


📌 六、总结

内容说明
Spring MVC控制器接收请求,返回视图
MyBatis封装了 JDBC,实现 SQL 到 Java 映射
配置方式XML 文件整合(spring-mybatis.xmlmapper.xml
特点灵活、轻量、适合手写 SQL

在 SpringBoot 项目中的使用步骤

一、项目结构

1.1 引入依赖(Maven)
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.0</version>
</dependency>
1.2 配置 application.yml
spring:datasource:url: jdbc:mysql://localhost:3306/testdbusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Drivermybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: com.example.modelconfiguration:map-underscore-to-camel-case: true
2.3 编写实体类
public class User {private Integer id;private String name;private Integer age;// getter/setter...
}
2.4 编写 Mapper 接口
@Mapper
public interface UserMapper {User selectUserById(Integer id);List<User> selectAllUsers();
}
2.5 编写 Mapper.xml(放在 resources/mapper/UserMapper.xml
<mapper namespace="com.example.mapper.UserMapper"><select id="selectUserById" resultType="User">SELECT * FROM user WHERE id = #{id}</select><select id="selectAllUsers" resultType="User">SELECT * FROM user</select>
</mapper>
2.6 Service 和 Controller 层调用
@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public User getUser(Integer id) {return userMapper.selectUserById(id);}
}

⚙️ 2. 配置文件详解(MyBatis 配置)

除了 application.yml 中配置项,MyBatis 也支持独立 XML 配置(mybatis-config.xml),示例:

<configuration><settings><!-- 驼峰命名自动映射 --><setting name="mapUnderscoreToCamelCase" value="true"/></settings><typeAliases><package name="com.example.model"/></typeAliases><mappers><mapper resource="mapper/UserMapper.xml"/></mappers>
</configuration>

这些配置项在 Spring Boot 项目中一般都写在 application.yml


🧱 3. 核心组件说明

组件作用说明
SqlSessionMyBatis 的 SQL 会话对象,封装了 JDBC 操作
Mapper 接口定义与数据库交互的方法
XML Mapper 文件定义 SQL 语句,与接口方法一一对应
TypeHandler类型处理器,用于 Java 类型与 JDBC 类型互相转换
ExecutorMyBatis 的 SQL 执行器,控制 SQL 执行流程
Configuration全局配置对象,保存所有配置信息

🧠 4. 动态 SQL(重点)

动态 SQL 是 MyBatis 的亮点之一,常用标签如下:

4.1 <if>

<if test="name != null">AND name = #{name}
</if>

4.2 <where>

自动拼接 WHERE,去掉多余 AND/OR:

<where><if test="name != null"> AND name = #{name} </if><if test="age != null"> AND age = #{age} </if>
</where>

4.3 <set>

用于动态生成 UPDATE SET,避免多余逗号:

<set><if test="name != null"> name = #{name}, </if><if test="age != null"> age = #{age} </if>
</set>

4.4 <foreach>

用于 IN 查询等场景:

<foreach collection="idList" item="id" open="(" separator="," close=")">#{id}
</foreach>

4.5 <choose> <when> <otherwise>

<choose><when test="type == 'admin'"> AND role = 'ADMIN' </when><otherwise> AND role = 'GUEST' </otherwise>
</choose>

✅ 5. 优缺点总结

✅ 优点

  • SQL 可控,适合复杂业务
  • 支持动态 SQL、注解与 XML 并存
  • 易于与 Spring/Spring Boot 集成
  • 性能好,轻量级

❌ 缺点

  • SQL 手写多,维护成本高
  • 不支持完整的 ORM 功能(不像 Hibernate 自动生成表结构)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/77263.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

1.6-抓包技术(Burp Suite\Yakit抓包\Web、APP、小程序)

1.6-抓包技术&#xff08;Burp Suite\Yakit抓包\Web、APP、小程序&#xff09; 如果要使用抓包软件&#xff0c;基本上第一步都是要安装证书的。原因如下&#xff1a; 客户端&#xff08;浏览器或应用&#xff09;会检测到证书不受信任&#xff0c;并弹出 证书错误&#xff0…

Java 大视界 -- 基于 Java 的大数据隐私保护在金融客户信息管理中的实践与挑战(178)

&#x1f496;亲爱的朋友们&#xff0c;热烈欢迎来到 青云交的博客&#xff01;能与诸位在此相逢&#xff0c;我倍感荣幸。在这飞速更迭的时代&#xff0c;我们都渴望一方心灵净土&#xff0c;而 我的博客 正是这样温暖的所在。这里为你呈上趣味与实用兼具的知识&#xff0c;也…

第十届 蓝桥杯 嵌入式 省赛

一、分析 这届的真题&#xff0c;有点像第七届的液位检测。 这届的题目开始&#xff0c;貌似比赛描述的功能&#xff0c;逻辑上变得更好梳理了。一开始就把大致的功能给你说明一遍&#xff0c;不像之前都是一块一块的说明。 1. 基本功能 1&#xff09;测量竞赛板上电位器 R…

实现usb的MTP功能

前言:最终结果根据用户自主选择可实现host和device功能的切换。 效果展示: 当插入usb时设备会弹窗 当用户选择设备模式时pc端就会出现mtp设备盘符 实现mtp设备 ubuntu架构根文件系统通过uMTP-Responder实现usb的MTP功能 添加服务 /home/flynn/firfly_rootfs/lib/system…

React-05React中props属性(传递数据),propTypes校验,类式与函数式组件props的使用

1.类式组件props基本数据读取与解构运算符传递 <script type"text/babel">// 创建组件class PersonalInfo extends React.Component {render() {// 读取props属性 并读取值console.log(props,this.props);return(<ul><li>姓名&#xff1a;{this.p…

PCI认证 密钥注入 ECC算法工具 NID_secp521r1 国密算法 openssl 全套证书生成,从证书提取公私钥数组 x,y等

步骤 1.全套证书已经生成。OK 2.找国芯要ECC加密解密签名验签代码。给的逻辑说明没有示例代码很难的上。 3.集成到工具 与SP联调。 1.用openssl全套证书生成及验证 注意&#xff1a;这里CA 签发 KLD 证书用的是SHA256。因为芯片只支持SHA256算法,不支持SHA512。改成统一。…

蓝桥杯每日刷题c++

目录 P9240 [蓝桥杯 2023 省 B] 冶炼金属 - 洛谷 (luogu.com.cn) P8748 [蓝桥杯 2021 省 B] 时间显示 - 洛谷 (luogu.com.cn) P10900 [蓝桥杯 2024 省 C] 数字诗意 - 洛谷 (luogu.com.cn) P10424 [蓝桥杯 2024 省 B] 好数 - 洛谷 (luogu.com.cn) P8754 [蓝桥杯 2021 省 AB2…

oracle 数据库字段类型为NUMBER(5,2)时,并且数据库值为0.1,为什么Java执行SQL查出来时为“.1“?

在 Oracle 数据库中&#xff0c;当字段类型为 NUMBER(5,2) 且存储的值为 0.1 时&#xff0c;Java 程序查询结果可能显示为 ".1"&#xff08;省略前导零&#xff09;&#xff0c;这是由 Oracle JDBC 驱动默认的数字格式化行为 导致的。以下是原因分析和解决方案&#…

3月AI论文精选十篇

1. Feature-Level Insights into Artificial Text Detection with Sparse Autoencoders[1] 核心贡献&#xff1a;通过稀疏自编码器揭示AI生成文本的检测特征&#xff0c;提出基于特征分布的鉴别方法。研究发现&#xff0c;AI文本在稀疏编码空间中呈现独特的"高频低幅"…

STM32在裸机(无RTOS)环境下,需要手动实现队列机制来替代FreeRTOS的CAN发送接收函数

xQueueSendToBackFromISR(ecuCanRxQueue, hcan->pRxMsg, &xHigherPriorityTaskWoken)&#xff0c;xQueueReceive(mscCanRxQueue,&mscRxMsg,0)和xQueueSendToBack(mscCanTxQueue, &TxMessageTemp, 0 )这3个函数&#xff0c;在裸机下实现&#xff1a; 在裸机&…

使用PX4,gazebo,mavros为旋翼添加下视的相机(仿真采集openrealm数据集-第一步)

目录 一.方法一&#xff08;没成功&#xff09; 1.运行PX4 2.运行mavros通讯 3.启动仿真世界和无人机 &#xff08;1&#xff09;单独测试相机 &#xff08;2&#xff09;make px4_sitl gazebo启动四旋翼iris无人机 二.方法二&#xff08;成功&#xff09; 1.通过 rosl…

7、nRF52xx蓝牙学习(nrf_gpiote.c库函数学习)

续前一篇文章。 3、nrfx_gpiote_in_event_enable void nrfx_gpiote_in_event_enable(nrfx_gpiote_pin_t pin, bool int_enable) {NRFX_ASSERT(nrf_gpio_pin_present_check(pin));NRFX_ASSERT(pin_in_use_by_gpiote(pin));if (pin_in_use_by_port(pin)){nrf_gpiote_polarity_t…

Java 实现插入排序:[通俗易懂的排序算法系列之三]

引言 大家好!欢迎继续关注我的排序算法系列。今天,我们要学习的是另一种非常基础且重要的排序算法——插入排序 (Insertion Sort)。 插入排序的思路非常贴近我们日常整理扑克牌的方式,理解起来相对自然。虽然它在最坏情况下的效率不高,但在某些特定场景下,它的表现甚至优…

Java的spring boot项目编译成功启动报错

问题现象&#xff1a;spring boot项目&#xff0c;候删除一些无用代码后&#xff0c;build成功&#xff0c;启动时报错&#xff1a;找不到java.util.Map或者其他对象&#xff08;用Lombok注解Data&#xff09;中的字段属性找不到等错误。解答&#xff1a; 常见是Lombok版本问题…

PyTorch参数管理详解:从访问到初始化与共享

本文通过实例代码讲解如何在PyTorch中管理神经网络参数&#xff0c;包括参数访问、多种初始化方法、自定义初始化以及参数绑定技术。所有代码可直接运行&#xff0c;适合深度学习初学者进阶学习。 1. 定义网络与参数访问 1.1 定义单隐藏层多层感知机 import torch from torch…

基于springboot+vue的课程管理系统

一、系统架构 前端&#xff1a;vue | element-ui 后端&#xff1a;springboot | mybatis-plus 环境&#xff1a;jdk1.8 | mysql8 | maven | node v16.20.2 | idea 二、代码及数据 三、功能介绍 01. 登录 02. 管理员-首页 03. 管理员-系管理 04. 管理员-专业管理 05. 管…

ssh密钥连接远程服务器并用scp传输文件

ssh密钥连接远程服务器 私钥的权限必须是600chmod 600 id_rsa连接时在命令中加上私钥的地址ssh -i PATH_to_id_rsa usernameip -p port scp -P port -i PATH_to_id_rsa file usernameip:PATH

ElasticSearch迁移数据

一、查询索引 1、查询所有索引 curl --user elastic:123456 -XGET "http://localhost:19200/_cat/indices?v&sindex" 2、查询索引配置 以索引名称hello为例 curl --user elastic:123456 -XGET "http://localhost:19200/hello/_settings?pretty" 3…

【Unity】animator检测某state动画播放完毕方法

博主对动画系统很不熟&#xff0c;可能使用的方法比较曲折&#xff0c;但是我确实没找到更有效的方法了。 unity的这个animator在我看来简直有毛病啊&#xff0c;为什么那么难以获取某状态动画的信息呢&#xff1f;&#xff1f;&#xff1f; 想要知道动画播完没有只有用norma…

Jmeter 插件【性能测试监控搭建】

1. 安装Plugins Manager 1.1 下载路径&#xff1a; Install :: JMeter-Plugins.org 1.2 放在lib/ext目录下 1.3 重启Jmeter&#xff0c;会在菜单-选项下多一个 Plugins Manager菜单&#xff0c;打开即可对插件进行安装、升级。 2. 客户端(Jmeter端) 2.1 安装plugins manager…