Spring Boot 3 集成 MyBatis 连接 MySQL 数据库

Spring Boot 3 集成 MyBatis 连接 MySQL 数据库的步骤:

以下是集成 Spring Boot 3、MyBatis、HikariCP 连接池并操作 MySQL 数据库的完整步骤和代码:

一、创建 Spring Boot 项目

添加以下依赖:

<dependencies><!-- Spring Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- MyBatis --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.4</version></dependency><!-- MySQL 驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!-- HikariCP 连接池 (默认集成,无需显式添加) --><!-- Lombok (可选) --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>
</dependencies>

二、配置数据库连接

在 src/main/resources/application.yml 中添加配置:

spring:datasource:url: jdbc:mysql://localhost:3306/his2?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=trueusername: rootpassword: yourpassworddriver-class-name: com.mysql.cj.jdbc.Driverhikari:maximum-pool-size: 10       # 最大连接数minimum-idle: 5            # 最小空闲连接idle-timeout: 30000        # 空闲连接超时时间(毫秒)connection-timeout: 30000  # 连接超时时间(毫秒)max-lifetime: 1800000      # 连接最大生命周期(毫秒)mybatis:mapper-locations: classpath:mapper/*.xml  # Mapper XML 文件位置type-aliases-package: com.example.entity  # 实体类包路径configuration:map-underscore-to-camel-case: true      # 开启驼峰命名映射cache-enabled: true                     # 开启二级缓存

三、创建实体类

src/main/java/com/example/entity/User.java

import lombok.Data;@Data
public class User {private Long id;private String username;private String password;private Integer age;private String email;private LocalDateTime createTime;
}

四、创建 Mapper 接口

src/main/java/com/example/mapper/UserMapper.java

import com.example.entity.User;
import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper
public interface UserMapper {// 查询所有用户List<User> selectAll();// 根据 ID 查询用户User selectById(Long id);// 插入用户int insert(User user);// 更新用户int update(User user);// 删除用户int deleteById(Long id);
}

五、创建 Mapper XML 文件

src/main/resources/mapper/UserMapper.xml

<?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.mapper.UserMapper"><resultMap id="BaseResultMap" type="User"><id column="id" property="id" /><result column="username" property="username" /><result column="password" property="password" /><result column="age" property="age" /><result column="email" property="email" /><result column="create_time" property="createTime" /></resultMap><select id="selectAll" resultMap="BaseResultMap">SELECT * FROM user</select><select id="selectById" resultMap="BaseResultMap">SELECT * FROM user WHERE id = #{id}</select><insert id="insert" parameterType="User">INSERT INTO user (username, password, age, email, create_time)VALUES (#{username}, #{password}, #{age}, #{email}, #{createTime})</insert><update id="update" parameterType="User">UPDATE userSET username = #{username},password = #{password},age = #{age},email = #{email}WHERE id = #{id}</update><delete id="deleteById" parameterType="Long">DELETE FROM user WHERE id = #{id}</delete>
</mapper>

六、创建 Service 层

src/main/java/com/example/service/UserService.java

import com.example.entity.User;import java.util.List;public interface UserService {List<User> getAllUsers();User getUserById(Long id);int saveUser(User user);int updateUser(User user);int deleteUser(Long id);
}

src/main/java/com/example/service/impl/UserServiceImpl.java

import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@Service
@Transactional
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic List<User> getAllUsers() {return userMapper.selectAll();}@Overridepublic User getUserById(Long id) {return userMapper.selectById(id);}@Overridepublic int saveUser(User user) {return userMapper.insert(user);}@Overridepublic int updateUser(User user) {return userMapper.update(user);}@Overridepublic int deleteUser(Long id) {return userMapper.deleteById(id);}
}

七、创建 Controller 层

src/main/java/com/example/controller/UserController.java

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/api/users")
public class UserController {@Autowiredprivate UserService userService;// 获取所有用户@GetMappingpublic List<User> getAllUsers() {return userService.getAllUsers();}// 根据 ID 获取用户@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {return userService.getUserById(id);}// 添加用户@PostMappingpublic int saveUser(@RequestBody User user) {return userService.saveUser(user);}// 更新用户@PutMapping("/{id}")public int updateUser(@PathVariable Long id, @RequestBody User user) {user.setId(id);return userService.updateUser(user);}// 删除用户@DeleteMapping("/{id}")public int deleteUser(@PathVariable Long id) {return userService.deleteUser(id);}
}

八、启用 MyBatis

在主应用类上添加 @MapperScan 注解:

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

九、数据库表结构

确保 MySQL 数据库 his2 中存在 user 表:

CREATE DATABASE his2;USE his2;CREATE TABLE user (id BIGINT PRIMARY KEY AUTO_INCREMENT,username VARCHAR(50) NOT NULL,password VARCHAR(100) NOT NULL,age INT,email VARCHAR(50),create_time DATETIME DEFAULT CURRENT_TIMESTAMP
);

十、测试应用

启动应用后,使用工具(如 Postman)测试接口:

  1. 获取所有用户

    GET http://localhost:8080/api/users
    
  2. 获取单个用户

    GET http://localhost:8080/api/users/1
    
  3. 添加用户

    POST http://localhost:8080/api/users
    请求体:
    {"username": "test","password": "123456","age": 25,"email": "test@example.com"
    }
    
  4. 更新用户

    PUT http://localhost:8080/api/users/1
    请求体:
    {"username": "updated","age": 26
    }
    
  5. 删除用户

    DELETE http://localhost:8080/api/users/1
    

十一、连接池配置

Spring Boot 3 默认使用 HikariCP 连接池,通过 spring.datasource.hikari 配置:

  • maximum-pool-size: 最大连接数(默认 10)
  • minimum-idle: 最小空闲连接数(默认与 maximum-pool-size 相同)
  • idle-timeout: 空闲连接超时时间(默认 30000 毫秒)
  • connection-timeout: 获取连接超时时间(默认 30000 毫秒)
  • max-lifetime: 连接最大生命周期(默认 1800000 毫秒)

十二、同包存放

  • 同包存放:Mapper 接口和 XML 文件放在同一包下时,无需额外配置 mapper-locations,MyBatis 会自动识别。
  • 核心配置:确保 @MapperScan 扫描到 Mapper 包,并通过 application.yml 配置数据库连接和连接池参数。
  • 资源打包:若 XML 在 Java 源码目录下,需在 pom.xml 中配置资源过滤,确保其被编译到类路径中。
  • 问题 1:XML 文件未被打包到类路径中

    如果 XML 文件未被编译到 target/classes 目录下,需在 pom.xml 中配置资源过滤:

    <build><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include>  <!-- 包含 Java 目录下的 XML 文件 --></includes></resource><resource><directory>src/main/resources</directory></resource></resources>
    </build>
    

    问题 2:手动指定 XML 路径(非必须)

    如果 XML 与 Mapper 接口不在同一包,需在 application.yml 中明确指定 XML 位置:

    mybatis:mapper-locations: classpath:/mapper/**/*.xml  # 例如:XML 放在 resources/mapper 目录下
    

     十三、关于传统的MyBatis 中的 SqlMapConfig.xml 

    • 传统 Spring + MyBatis:需要 SqlMapConfig.xml 配置 MyBatis 基础信息,再由 Spring 加载。
    • Spring Boot + MyBatis:无需 SqlMapConfig.xml,通过自动配置和属性文件即可完成大部分配置,更简洁。
    • 什么时候需要自定义配置?
      当需要修改 MyBatis 全局行为(如添加插件、自定义类型处理器)时,可通过 Java 配置类@Configuration + @Bean)替代传统的 XML 配置,例如:

      java

      @Configuration
      public class MyBatisConfig {@Beanpublic MyBatisConfiguration myBatisConfiguration() {MyBatisConfiguration configuration = new MyBatisConfiguration();configuration.setMapUnderscoreToCamelCase(true); // 开启驼峰映射return configuration;}
      }
      

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

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

相关文章

基于React + FastAPI + LangChain + 通义千问的智能医疗问答系统

&#x1f4cc; 文章摘要&#xff1a; 本文详细介绍了如何在前端通过 Fetch 实现与 FastAPI 后端的 流式响应通信&#xff0c;并支持图文多模态数据上传。通过构建 multipart/form-data 请求&#xff0c;配合 ReadableStream 实时读取 AI 回复内容&#xff0c;实现类似 ChatGPT…

YOLOv8 升级之路:主干网络嵌入 SCINet,优化黑暗环境目标检测

文章目录 引言1. 低照度图像检测的挑战1.1 低照度环境对目标检测的影响1.2 传统解决方案的局限性2. SCINet网络原理2.1 SCINet核心思想2.2 网络架构3. YOLOv8与SCINet的集成方案3.1 总体架构设计3.2 关键集成代码3.3 训练策略4. 实验结果与分析4.1 实验设置4.2 性能对比4.3 可视…

所有的Linux桌面环境

Linux操作系统提供了多种桌面环境&#xff0c;每种都有其独特的特点和适用场景。以下是一些常见的Linux桌面环境&#xff1a; 轻量级桌面环境 Xfce&#xff1a;广泛使用的轻量级桌面环境&#xff0c;适合资源有限的设备。Xfce 4.18带来了性能改进和新功能&#xff0c;如Thuna…

@component、@bean、@Configuration的区别

详细解析Spring框架中这三个最核心、也最容易混淆的注解&#xff1a;Component、Bean和Configuration。 为了快速理解&#xff0c;我们先看一个总结性的表格&#xff1a; 注解应用级别作用使用场景Component类级别将类标识为Spring组件&#xff0c;让Spring自动扫描并创建实例…

Android多媒体——音/视同步数据处理(二十)

在多媒体播放过程中,音频数据的处理不仅要保证其解码和输出的连续性,还需要与视频帧保持时间上的严格对齐,以实现良好的观看体验。Android 多媒体框架中的 NuPlayerRenderer 是负责最终渲染音视频数据的核心组件之一。 一、Audio数据处理 NuPlayerRenderer 是 Android 原生…

MYSQL 使用命令mysqldump备份数据库的时候需要用户具备什么权限

背景 之前都是使用数据库root用户备份数据库&#xff0c;没有权限问题&#xff0c;今天使用一个数据库基本用户备份数据库&#xff0c;提示一直没有权限&#xff0c;提示的很明显 mysqldump: Error: Access denied; you need (at least one of) the PROCESS privilege(s) for …

WebRTC源码线程-1

1、概述 本篇主要是简单介绍WebRTC中的线程&#xff0c;WebRTC源码对线程做了很多的封装。 1.1 WebRTC中线程的种类 1.1.1 信令线程 用于与应用层的交互&#xff0c;比如创建offer&#xff0c;answer&#xff0c;candidate等绝大多数的操作 1.1.2 工作线程 负责内部的处理逻辑&…

spring:使用标签xml静态工厂方法获取bean

在spring可以直接通过配置文件获取bean对象&#xff0c;如果获取的bean对象还有若干设置&#xff0c;需要自动完成&#xff0c;可以通过工厂方法获取bean对象。 静态工厂类&#xff0c;其中InterfaceUserDao和InterfaceUserService都是自定义的接口&#xff0c;可以自己替换。…

linux 用户态时间性能优化工具perf/strace/gdb/varlind/gprof

1. perf top -g或者top分析卡顿(cpu占用比较高的函数) gdb 是 GNU 调试器,可以用于分析程序的时间性能。虽然 info time 不是直接用于性能分析的命令,但 gdb 提供了与时间相关的功能,例如通过 timer 命令设置计时器或通过 info proc 查看进程的时间信息。 #include <…

客户端和服务器已成功建立 TCP 连接【输出解析】

文章目录 图片**1. 连接状态解析****第一条记录&#xff08;服务器监听&#xff09;****第二条记录&#xff08;客户端 → 服务器&#xff09;****第三条记录&#xff08;服务器 → 客户端&#xff09;** **2. 关键概念澄清****(1) 0.0.0.0 的含义****(2) 端口号的分配规则** *…

Win系统下的Linux系统——WSL 使用手册

我们在复现一些项目的时候&#xff0c;有些依赖包只能在 linux 环境下使用&#xff0c;还不打算使用远程服务器&#xff0c;那么此时我们可以使用 WSL 创建一个 ubutu 系统&#xff0c;在这个系统里创建虚拟环境、下载依赖包。然后&#xff0c;我们就可以在 windows 下的 vscod…

电脑同时连接内网和外网的方法,附外网连接局域网的操作设置

对于工作一般都设置在内网网段中&#xff0c;而同时由于需求需要连接外网&#xff0c;一般只能通过内网和外网的不断切换进行设置&#xff0c;如果可以同时连接内网和外网会更加便利&#xff0c;同时连接内网和外网方法具体如下。 一、电脑怎么弄可以同时连接内网和外网&#…

C++11:原子操作与内存顺序:从理论到实践的无锁并发实现

文章目录 0.简介1.并发编程需要保证的特性2.原子操作2.1 原子操作的特性 3.内存顺序3.1 顺序一致性3.2 释放-获取&#xff08;Release-Acquire)3.3 宽松顺序&#xff08;Relaxed)3.4 内存顺序 4.无锁并发5. 使用建议 0.简介 在并发编程中&#xff0c;原子性、可见性和有序性是…

oracle 归档日志与RECOVERY_FILE_DEST 视图

1. RECOVERY_FILE_DEST 视图的作用 RECOVERY_FILE_DEST 是 Oracle 数据库用于 管理快速恢复区&#xff08;Fast Recovery Area, FRA&#xff09; 的一个视图。FRA 是 Oracle 提供的一种集中存储恢复相关文件&#xff08;如归档日志、备份文件、闪回日志等&#xff09;的区域。…

零基础玩转物联网-串口转以太网模块如何快速实现与MQTT服务器通信

目录 1 前言 2 环境搭建 2.1 硬件准备 2.2 软件准备 2.3 驱动检查 3 MQTT服务器通信配置与交互 3.1 硬件连接 3.2 开启MQTT服务器 3.3 打开配置工具读取基本信息 3.4 填写连接参数进行连接 3.5 通信测试 4 总结 1 前言 MQTT&#xff1a;全称为消息队列遥测传输协议&#xff08;…

六、Sqoop 导出

作者&#xff1a;IvanCodes 日期&#xff1a;2025年6月7日 专栏&#xff1a;Sqoop教程 Apache Sqoop 不仅擅长从关系型数据库 (RDBMS) 向 Hadoop (HDFS, Hive, HBase) 导入数据&#xff0c;同样也强大地支持反向操作——将存储在 Hadoop 中的数据导出 (Export) 回关系型数据库。…

数据结构-如果将堆结构应用到TOP-K问题上会怎样?

数据结构的应用-如何用堆解决TOP-K问题 前言一、TOP-K问题是什么&#xff1f;二、如何用堆解决TOP-K问题1.怎么建堆&#xff0c;建大堆还是小堆&#xff1f;2.代码实现 总结 前言 本篇文章进行如何用堆结构解决TOP-K问题的讲解 一、TOP-K问题是什么&#xff1f; TOP-k问题&am…

Elasticsearch的索引

正向索引和倒排索引 什么是正向索引&#xff1f; 传统的数据库采用正向索引&#xff0c;如MySQL将表中的id创建索引&#xff0c;正向索引在进行不是id为索引进行搜索的时候&#xff0c;会逐条进行查询&#xff0c;比方说 上图的表格&#xff0c;数据库进行逐条查询&#xff0c;…

分散电站,集中掌控,安科瑞光伏云平台助力企业绿色转型

本项目位于香港全境共计52个分布式光伏站&#xff0c;总装机容量8.6MW。发电模式自发自用&#xff0c;余电上网&#xff0c;逆变器采用阳光电源SG100CX、SG20RT等12种型号共计103台&#xff0c;其余型号共计15台。每个站点均配置气象站。 项目采用AcrelCloud-1200分布式光伏运…

开发记录:修复一些Bug,并实现两个功能

开发记录&#xff1a; &#x1f4cb; 工作概述 到今天主要完成了AI阅读助手的两大核心功能&#xff1a;前情提要和名词解释&#xff0c;并对相关交互体验进行了优化。通过流式SSE技术实现了实时AI内容生成&#xff0c;大幅提升了用户体验。 &#x1f3af; 主要完成功能 1…