当前位置: 首页 > news >正文

Spring Boot 3.3 + MyBatis 基础教程:从入门到实践

在这里插入图片描述

Spring Boot 3.3 + MyBatis 基础教程:从入门到实践

在当今的Java开发领域,Spring Boot和MyBatis是构建高效、可维护的后端应用的两个强大工具。Spring Boot简化了Spring应用的初始搭建和开发过程,而MyBatis则提供了一种灵活的ORM(对象关系映射)解决方案。本文将介绍如何在Spring Boot 3.3中集成MyBatis,并通过一个简单的用户管理系统示例来展示其基本用法。同时,我们也会深入探讨MyBatis的实现原理,并通过类图来帮助理解其内部机制。

一、项目搭建

1. 创建Spring Boot项目

首先,使用Spring Initializr(https://start.spring.io/)创建一个Spring Boot项目,选择以下依赖:

  • Spring Web
  • MyBatis Framework
  • MySQL Driver

生成项目后,将项目导入到你的IDE中(如IntelliJ IDEA或Eclipse)。

2. 添加依赖

pom.xml文件中,确保添加了以下依赖:

<dependencies><!-- Spring Boot Starter Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- MyBatis Spring Boot Starter --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.4</version></dependency><!-- MySQL Connector --><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><!-- Spring Boot Starter Test --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>

3. 配置数据源和MyBatis

application.yml文件中,配置数据源和MyBatis的相关信息:

spring:application:name: spring-boot-demodatasource:url: jdbc:mysql://localhost:3306/db_spring_boot_demo?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=trueusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Drivermybatis:mapper-locations: classpath:mapper/*.xml
  • spring.datasource.*:配置数据库连接信息。
  • mybatis.mapper-locations:指定MyBatis映射文件的位置。

二、创建实体类

创建一个简单的User实体类,用于表示用户信息:

package com.example.demo.model;import lombok.Data;@Data
public class User {private Long id;private String username;private String password;
}
  • 使用@Data注解来自动生成getter和setter方法。

三、创建Mapper接口

MyBatis通过Mapper接口来定义数据库操作。创建UserMapper接口:

package com.example.demo.mapper;import com.example.demo.model.User;
import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper
public interface UserMapper {// 也可以用@Select @Update等注解来定义相关的sql语句,不用xml配图User selectById(Long id);void insert(User user);void update(User user);void deleteById(Long id);List<User> getAll();
}

直接代码定义SQL语句

@Mapper
public interface UserMapper {@Select("SELECT * FROM users WHERE id = #{id}")User selectById(Long id);@Insert("INSERT INTO users(username, password) VALUES(#{username}, #{password})")@Options(useGeneratedKeys = true, keyProperty = "id")void insert(User user);@Update("UPDATE users SET username = #{username}, password = #{password} WHERE id = #{id}")void update(User user);@Delete("DELETE FROM users WHERE id = #{id}")void deleteById(Long id);@Select("SELECT * FROM users")List<User> getAll();
}

使用XML配置SQL

src/main/resources/mapper目录下创建UserMapper.xml文件,定义SQL语句:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper"><select id="selectById" parameterType="long" resultType="com.example.demo.model.User">SELECT * FROM users WHERE id = #{id}</select><insert id="insert" parameterType="com.example.demo.model.User" useGeneratedKeys="true" keyProperty="id">INSERT INTO users(username, password) VALUES(#{username}, #{password})</insert><update id="update" parameterType="com.example.demo.model.User">UPDATE users SET username = #{username}, password = #{password} WHERE id = #{id}</update><delete id="deleteById" parameterType="long">DELETE FROM users WHERE id = #{id}</delete><select id="getAll" resultType="com.example.demo.model.User">SELECT * FROM users</select></mapper>
  • namespace:指定Mapper接口的全限定名。
  • 每个SQL语句通过<select><insert><update><delete>标签定义。

四、创建服务层

服务层是业务逻辑的核心部分。创建UserService类:

package com.example.demo.service;import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;import java.util.List;@Service
public class UserService {private final UserMapper userMapper;@Autowiredpublic UserService(UserMapper userMapper) {this.userMapper = userMapper;}public User createUser(User user) {userMapper.insert(user);return user;}public User getUserById(Long id) {return userMapper.selectById(id);}public List<User> getAllUsers() {return userMapper.getAll();}public void updateUser(User user) {userMapper.update(user);}public void deleteUserById(Long id) {userMapper.deleteById(id);}
}
  • 使用@Service注解标记这是一个服务类。
  • 通过构造函数注入UserMapper

五、创建控制器

控制器层用于处理HTTP请求。创建UserController类:

package com.example.demo.controller;import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/api/users")
public class UserController {private final UserService userService;@Autowiredpublic UserController(UserService userService) {this.userService = userService;}@PostMappingpublic ResponseEntity<User> createUser(@RequestBody User user) {return ResponseEntity.ok(userService.createUser(user));}@GetMapping("/{id}")public ResponseEntity<User> getUserById(@PathVariable Long id) {return ResponseEntity.ok(userService.getUserById(id));}@GetMappingpublic ResponseEntity<List<User>> getAllUsers() {return ResponseEntity.ok(userService.getAllUsers());}@PutMapping("/{id}")public ResponseEntity<Void> updateUser(@PathVariable Long id, @RequestBody User user) {user.setId(id);userService.updateUser(user);return ResponseEntity.noContent().build();}@DeleteMapping("/{id}")public ResponseEntity<Void> deleteUserById(@PathVariable Long id) {userService.deleteUserById(id);return ResponseEntity.noContent().build();}
}
  • 使用@RestController注解标记这是一个REST控制器。
  • 使用@RequestMapping定义请求路径。
  • 使用@Autowired注入UserService

六、MyBatis实现原理简述

MyBatis是一个半自动化的ORM框架,它通过以下机制实现数据访问:

  1. SQL映射

    • MyBatis通过Mapper接口和注解(或XML配置)将Java对象与SQL语句进行映射。
    • UserMapper中,@Select@Insert等注解定义了SQL语句和Java方法的对应关系。
  2. 动态SQL

    • MyBatis支持动态SQL,可以根据传入的参数动态生成SQL语句。
    • 例如,#{username}会被替换为实际的参数值。
  3. SQL会话管理

    • MyBatis通过SqlSession管理数据库会话,负责执行SQL语句、获取映射器和管理事务。
    • 在Spring Boot中,SqlSession的生命周期由Spring管理。
  4. 映射器代理

    • MyBatis为Mapper接口生成代理对象,当调用Mapper方法时,会通过代理机制执行对应的SQL语句。
    • 例如,调用userMapper.insert(user)时,MyBatis会根据注解生成并执行SQL语句。
  5. 结果映射

    • MyBatis将查询结果自动映射为Java对象。
    • selectById方法中,查询结果会被映射为User对象。

MyBatis主要类图(Mermaid格式)

以下是MyBatis主要类的UML类图,使用Mermaid格式表示:

creates
uses
has
uses
uses
creates
has
creates
implements
SqlSessionFactory
+open()
+getConfiguration()
SqlSession
+selectOne()
+selectList()
+insert()
+update()
+delete()
+getMapper()
Configuration
+getEnvironment()
+getMapperRegistry()
Environment
+getDataSource()
+getTransactionFactory()
DataSource
+getConnection()
TransactionFactory
+newTransaction()
Transaction
+commit()
+rollback()
MapperRegistry
+getMappers()
MapperProxy
+invoke()
Mapper
+selectById()
+insert()
+update()
+deleteById()
+getAll()
  • SqlSessionFactory:负责创建SqlSession实例。
  • SqlSession:负责执行SQL语句、获取映射器和管理事务。
  • Configuration:存储MyBatis的配置信息,包括环境配置、数据源、事务管理器和映射器。
  • Environment:定义了数据源和事务管理器的配置。
  • DataSource:提供数据库连接。
  • TransactionFactory:用于创建事务管理器。
  • Transaction:管理事务的提交和回滚。
  • MapperRegistry:管理映射器接口。
  • MapperProxy:为映射器接口生成代理对象。
  • Mapper:映射器接口,定义了数据库操作方法。

七、运行项目

启动Spring Boot应用后,你可以通过以下RESTful API进行测试:

  • 创建用户POST /api/users
  • 获取用户GET /api/users/{id}
  • 获取所有用户GET /api/users
  • 更新用户PUT /api/users/{id}
  • 删除用户DELETE /api/users/{id}

http测试脚本

IntelliJ http接口请求脚本

### 创建用户 POST /api/users
POST http://localhost:8080/api/users
Content-Type: application/json{"username": "john_doe——2","password": "securePassword123"
}### 根据ID查询用户 GET /api/users/{id}
GET http://localhost:8080/api/users/1### 查询所有用户 GET /api/users
GET http://localhost:8080/api/users### 更新用户 PUT /api/users/{id}
PUT http://localhost:8080/api/users/1
Content-Type: application/json{"username": "john_doe_updated","password": "newSecurePassword456"
}### 删除用户 DELETE /api/users/{id}
DELETE http://localhost:8080/api/users/1

九、总结

通过本文,我们展示了如何在Spring Boot 3.3中集成MyBatis,并实现了一个简单的用户管理系统。MyBatis的灵活性和强大的SQL映射能力使其成为Java开发中常用的ORM框架之一。同时,通过Mermaid格式的类图,我们深入探讨了MyBatis的实现原理,帮助你更好地理解其内部机制。

希望本文对你有所帮助!如果你有任何问题或建议,欢迎留言交流。


以我之思,借AI之力

相关文章:

  • Android座舱系统Agent改造方案
  • cmake编译LASzip和LAStools
  • CVE-2023-25194源码分析与漏洞复现(Kafka JNDI注入)
  • Java优化:双重for循环
  • 2023年ASOC SCI2区TOP,随机跟随蚁群优化算法RFACO,深度解析+性能实测
  • B站Miachael_ee——蓝牙教程笔记
  • 又是一年高考季
  • Redis 与 MySQL 数据一致性保障方案
  • 微服务架构实战:Nacos 单机版的安装与启动流程
  • 2.4 vcpkg 使用
  • Linux 文件系统与 I/O 编程核心原理及实践笔记
  • 关于队列的使用
  • 6.7本日总结
  • python打卡day47
  • 第1讲、包管理和环境管理工具Conda 全面介绍
  • 理想汽车5月交付40856辆,同比增长16.7%
  • 《开篇:课程目录》
  • 33、原子操作
  • Vue中渲染函数的使用
  • Java编程中常见的条件链与继承陷阱
  • 网址申请域名/武汉网站搜索引擎优化
  • 如何快速用手机做网站/株洲最新今日头条
  • 鹏鹞网站页面代码/seo公司 杭州
  • 建设网站总经理讲话范本/谷歌站长平台
  • 网站空间 哪个公司好/搜索引擎营销的优缺点及案例
  • 芜湖网站优化公司/小说推广平台有哪些