SpringBoot集成MyBatis和FlyWay

news2024/9/22 9:40:28

一、什么是FlyWay

一个开源的数据库迁移工具,用于管理和执行数据库结构的版本变更。通俗来说,它帮助开发者跟踪和应用数据库中的更改,比如表的创建、列的修改等。主要的功能为:

数据库版本控制

  • Flyway 使用一组迁移脚本来定义数据库的版本。每个脚本对应一个数据库变更(如新增表、修改表结构等)。这些脚本按顺序执行,确保数据库始终处于最新版本。

自动迁移

  • 当你启动应用程序或执行 Flyway 命令时,它会自动检查数据库版本,并应用所有尚未执行的迁移脚本。这使得数据库与应用程序代码的版本保持一致。

迁移历史管理

  • Flyway 会在数据库中维护一个历史表(默认名称为 flyway_schema_history),记录所有已执行的迁移脚本的状态。这有助于跟踪数据库变更的历史记录。

具体工作流程为创建一个SQL迁移脚本,注意这里的命名是有规范的,例如V1__create_table.sql就代表版本为1。

在应用程序的配置文件中,你指定 Flyway 的数据库连接信息和迁移脚本的位置。Flyway 会读取这些配置,连接到数据库。

当应用程序启动时,Flyway 会检查数据库的当前版本,并对比迁移脚本中的版本。如果发现有新的迁移脚本,Flyway 会按照脚本的顺序执行这些脚本。

二、什么是MyBatis

一个 Java 持久化框架,用于简化与数据库的交互。它通过映射文件或注解将 Java 对象与数据库表之间的关系定义得非常清晰,从而简化了数据库操作。也将颗粒度划分的更细。主要功能为:

SQL 映射

  • MyBatis 允许开发者在 XML 文件中或者使用注解定义 SQL 语句,并将这些 SQL 语句与 Java 方法进行映射。这种方式比起 JPA 提供了更大的灵活性,因为你可以手动编写 SQL 语句,完全控制数据库的操作。

对象与数据库的映射

  • MyBatis 可以将查询结果映射为 Java 对象,也可以将 Java 对象转换为 SQL 语句的参数。这使得开发者可以直接在 Java 代码中操作数据库中的数据,而不需要处理复杂的 JDBC 代码。

动态 SQL

  • MyBatis 支持动态 SQL,这意味着你可以在 SQL 语句中使用条件逻辑来生成不同的 SQL 语句。这样可以根据不同的参数构建不同的查询,从而提供更灵活的数据库操作。

事务管理

  • MyBatis 集成了事务管理功能,可以与 Spring 框架一起使用,支持声明式事务管理。这简化了事务的处理,确保数据一致性。

缓存机制

  • MyBatis 内置了一级缓存(会话级别缓存)和二级缓存(全局缓存),可以提高数据库访问的性能。缓存机制可以减少数据库的读取操作,提升应用程序的效率。

三、集成MyBatis

1、导入MySQL与MyBatis的依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.33</version> 
</dependency>

2、配置MySQL与MyBatis的配置信息

这里MyBatis我使用注解的形式,当日也可以使用xml文件的形式

spring.datasource.url=jdbc:mysql://localhost:3306/goods?useSSL=false&serverTimezone=UTC
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

mybatis.type-aliases-package=com.example.web.model
#mybatis.mapper-locations=classpath:mapper/*.xml

3、创建实体

package com.example.web.model;

public class User {
    private Long id;
    private String name;
    private String email;
}

4、创建Mapper接口

package com.example.web.mapper;

import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.example.WebSo.model.User;

@Mapper
public interface UserMapper {
    @Select("select * from user where id = #{id}")
    User findById(Long id);

    @Select("select * from user")
    List<User> findAll();

    @Insert("insert into user(name,email) values(#{name},#{email})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(User user);

    @Update("update user set name = #{name}, email = #{email} where id = #{id}")
    int update(User user);

    @Delete("delete from user where id = #{id}")
    int delete(Long id);
}

5、创建Service层

package com.example.web.service;

import org.springframework.stereotype.Service;
import com.example.WebSo.mapper.UserMapper;
import com.example.WebSo.model.User;
import java.util.List;

@Service
public class UserService {
    private final UserMapper userMapper;

    
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public User insert(User user) {
        int bool = userMapper.insert(user);
        if(bool==1){
            return user;
        }
        return null;
    }

    public User findById(Long id) {
        return userMapper.findById(id);
    }

    public User update(User user) {
        int bool = userMapper.update(user);
        if (bool == 1) {
            return user;
        }
        return null;
    }

    public boolean delete(Long id) {
        int bool = userMapper.delete(id);
        if (bool != 1) {
            return false;
        }
        return true;
    }

    public List<User> findAll() {
        return userMapper.findAll();
    }
}

6、创建Controller层

package com.example.web.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.WebSo.model.User;
import com.example.WebSo.service.UserService;

@RestController
@RequestMapping(value = "api/server")
public class UserController {

    @Autowired
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User findById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public ResponseEntity<Map<String, Object>> findAll() {
        Map<String, Object> response = new HashMap<>();
        response.put("users", userService.findAll());
        return ResponseEntity.ok(response);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseEntity<User> insert(@RequestBody User user) {
        userService.insert(user);
        return ResponseEntity.ok(user);
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public ResponseEntity<User> update(@RequestBody User user) {
        userService.update(user);
        return ResponseEntity.ok(user);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Boolean> delete(@PathVariable Long id) {
        boolean success = userService.delete(id);
        return ResponseEntity.ok(success);
    }
}

这样就已经集成了MyBatis,MyBatis映射到User实体上,并可以通过Mapper接口对该表进行一些操作。但是需要提前创建好这个数据表,因为MyBatis不能像JPA那样自动创建映射表。这时候我们就可以结合FalyWay来使用。

四、集成FlyWay

1、导入依赖

<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-core</artifactId>
    <version>9.22.2</version>
</dependency>
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-mysql</artifactId>
    <version>9.22.2</version>
</dependency>

2、配置FlyWay相关信息

#启动
spring.flyway.enabled=true
#指定脚本路径
spring.flyway.locations=classpath:db/migration
#指定表名
spring.flyway.table=flyway_schema_history
#指定版本
spring.flyway.baseline-version=0
#是否自动执行
spring.flyway.baseline-on-migrate=true
#描述
spring.flyway.baseline-description=Initial baseline setup for existing database

在resources下创建目录db/migration,所有的SQL脚本都放在这个目录下。

3、编写SQL迁移脚本

#V1__create_user_table.sql
create table user (
    id int primary key auto_increment,
    name varchar(255) not null,
    email varchar(255) not null
);
#V2__add_user_table.sql
insert into user (name, email) values ('刘德华', 'john@doe.com');
insert into user (name, email) values ('张学友', 'jane@doe.com');
insert into user (name, email) values ('周星驰', 'joe@doe.com');

五、效果

直接启动程序,可以看到数据库中多了一张flyway_schema_history表,用于记录数据库的版本信息。并且sql脚本也被成功执行
在这里插入图片描述
在这里插入图片描述

现在我们通过Apifox来测试一下
在这里插入图片描述

在这里插入图片描述

可以看到已经成功的添加和查询,FlyWay和MyBatis非常完美的结合在了一起。

六、总结

结合使用MyBatis和Flyway,可以实现高效的数据库管理和数据操作。Flyway通过执行SQL脚本进行数据库迁移,确保数据库结构的自动更新和版本控制;MyBatis则负责将SQL语句映射到Java对象,使得复杂的数据操作和查询更灵活、面向对象。这样,你可以利用Flyway来管理数据库结构演变,同时用MyBatis精细化地操作数据。

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

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

相关文章

硬件I2C和软件I2C(模拟I2C)的区别

硬件I2C和软件I2C是两种不同的实现I2C&#xff08;Inter-Integrated Circuit&#xff0c;集成电路间&#xff09;通信协议的方式&#xff0c;它们在实现方式、性能特点以及应用场景上存在显著差异。 一、实现方式 硬件I2C&#xff1a;通过专门的硬件电路实现&#xff0c;这些…

泛交通领域的可视化大屏作品欣赏,各个都相当惊艳。

各位新老朋友大家好&#xff0c;本次给大家带来泛交通领域的可视化大屏&#xff0c;供大家鉴赏。 泛交通领域是指综合利用各种交通方式和资源&#xff0c;提供全方位、多元化的出行选择和服务的交通体系。 它包括以下几个方面&#xff1a; 1. 公共交通&#xff1a;包括地铁、…

花钱买不到系列之—linux系统调用

关于系统调用是什么&#xff0c;为什么用系统调用? 也是通过生活的例子来说明白。 我们生活中有一种东西叫银行&#xff0c;银行是不是有存钱的仓库对不对&#xff1f;好银行有存钱的仓库&#xff0c;银行有桌椅板凳啊&#xff0c;银行还有电脑&#xff0c;设备啊&#xff0c;…

文华财经期货DK多空提示指标源码

N1:40; A:(COHL)/4; AA0:MA(A,N1),LINETHICK3;//中 MA1:MA(CLOSE,5), NODRAW; MA2:MA(CLOSE,10), NODRAW; MA3:MA(C,60), NODRAW,LINETHICK1; 转折线:MA3, NODRAW,COLORCYAN; 顺势线:MA(CLOSE,10), NODRAW; MA20:MA(C,20), NODRAW; MA30:MA(C,30), NODRAW; ZD:MA3>…

网络 基础

目录 1、协议&#xff1a; 2、OSI 七层 模型&#xff1a; 3、TCP/IP 五层 / 四层 协议 3.1、为什么要有TCP / IP 协议&#xff1f; 3.1.1、主机之间变远产生的问题&#xff1a; 3.1.2、TCP/IP协议于操作系统的关系 4、局域网 4.1、Mac 4.1.1 在Linux内使用指令 …

leetCode - - - 哈希表

目录 1.模拟行走机器人&#xff08;LeetCode 874&#xff09; 2.数组的度&#xff08;LeetCode 697&#xff09; 3.子域名访问次数&#xff08;LeetCode 811&#xff09; 4.字母异位词分组&#xff08;LeetCode 49&#xff09; 5.小结 1.常见的哈希表实现 2.遍历Map 1.模…

基于Java中的SSM框架实现医院收费系统项目【项目源码+论文说明】计算机毕业设计

基于Java中的SSM框架实现医院收费系统演示 摘要 随着医疗体制改革的不断深入&#xff0c;医院收费系统成为医院信息化建设的重点内容。医院收费系统是利用计算机、网络技术和数据库技术&#xff0c;实现病人在医疗机构的诊疗信息的电子化存储、传递和分析&#xff0c;从而提高…

[Meachines] [Medium] Mango PHP弱比较绕过+MongoDB注入+TRP00F自动化权限提升+JJS权限提升

信息收集 IP AddressOpening Ports10.10.10.162TCP:22&#xff0c;80&#xff0c;443 $ nmap -p- 10.10.10.162 --min-rate 1000 -sC -sV PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) | ssh-host…

<数据集>快递识别数据集<目标检测>

数据集格式&#xff1a;VOCYOLO格式 图片数量&#xff1a;5382张 标注数量(xml文件个数)&#xff1a;5382 标注数量(txt文件个数)&#xff1a;5382 标注类别数&#xff1a;1 标注类别名称&#xff1a;[Box-Packet] 序号类别名称图片数框数1Box-Packet53828965 使用标注工…

8.15-配置mysql5.7环境+使用python管理数据库+使用中间件mycat配置读写分离

一、配置mysql5.7的环境 1.基础配置 # 将mysql5.7的包拖入xshell [rootmysql_5 ~]# ls anaconda-ks.cfg mysql-5.7.44-linux-glibc2.12-x86_64.tar.gz ​ # 解压 [rootmysql_5 ~]# tar -xf mysql-5.7.44-linux-glibc2.12-x86_64.tar.gz ​ # 备份文件 [rootmysql_5 ~]# cp…

短说V4.2.0测试版发布|字体更换、小名片及个人中心UI更换

Hi 大家好&#xff0c; 我是给你们带来惊喜的运营小番茄。 本期更新为短说V4.2.0测试版&#xff0c;本次更新涉及平台有H5、App、微信小程序。 4.2.0版本除功能优化外&#xff0c;新增了如下功能&#xff1a; 一、新增功能 通用版&#xff1a; ①全站默认字体全部更换为…

淘宝到一个墨水屏,成功实现显示经历记录

一&#xff0c;淘一个墨水屏的原因 在一些小的PCB设计和编程中发现&#xff0c;许多程序控制运行情况如果能够显示出来&#xff0c;会很完美。大学时期使用LCD1602&#xff08;经典&#xff09;显示了一个称重传感器的课程设计&#xff0c;后来尝试OLED显示。在过程中发现墨水…

【嵌入式linux开发】智能家居入门5(QT、微信小程序、HTTP协议、ONENET云平台、旭日x3派)

智能家居入门5&#xff08;QT、微信小程序、HTTP协议、ONENET云平台、旭日x3派&#xff09; 前言一、QT界面设计二、云平台产品创建与连接三、下位机端QT代码总览&#xff1a;四、微信小程序端代码总览五、板端测试 前言 前四篇智能家居相关文章都是使用STM32作为主控&#xf…

报表的多行业应用!用工具做报表省了我不少事...

一、什么是报表&#xff1f; 说起报表&#xff0c;你不会还停留在Excel报表的层面上吧&#xff1f; 传统的报表一般都是基于Excel制作的&#xff0c;主要面向业务人员、开发人员等&#xff0c;也有一些公司会自己去开发设计&#xff0c;只不过周期较长&#xff0c;耗费人力多。…

端到端自动驾驶落地挑战与驱动力

1、端到端的发展驱动力 1.1 对标驱动&#xff1a;特斯拉FSD的标杆作用吸引行业关注 大部分行业专家表示&#xff0c;特斯拉FSD v12的优秀表现&#xff0c;是端到端自动驾驶这一技术路线快速形成大范围共识的最重要的推动力&#xff1b;而在此之前&#xff0c;从来没有一个自动…

C#模拟量线性变换小程序

1、一步步建立一个C#项目 一步步建立一个C#项目(连续读取S7-1200PLC数据)_s7协议批量读取-CSDN博客文章浏览阅读1.7k次,点赞2次,收藏4次。本文详细介绍了如何使用C#构建一个项目,通过S7net库连接并连续读取S7-1200 PLC的数据,包括创建窗体应用、配置存储位置、安装S7net库…

服务器端请求伪造漏洞

1.客户端请求 客户端请求指的是由客户端设备(如个人计算机、智能手机、平板电脑等)或软件(浏览器、各种APP)发出的请求&#xff0c;以获取指定的网页、图片、视频或其他资源。比如当用户在浏览器中输入URL或点击链接时&#xff0c;浏览器会自动发起HTTP请求&#xff0c;请求服…

Python | Leetcode Python题解之第335题路径交叉

题目&#xff1a; 题解&#xff1a; class Solution:def isSelfCrossing(self, distance: List[int]) -> bool:n len(distance)# 处理第 1 种情况i 0while i < n and (i < 2 or distance[i] > distance[i - 2]):i 1if i n:return False# 处理第 j 次移动的情况…

【语义通信】灵(Genie)——6G的第四维元素

6G 不仅包含 5G 涉及的人类社会、信息空间、 物理世界&#xff08;人、机、物&#xff09;这 3 个核心元素&#xff0c;还第四维元素—灵&#xff08;Genie&#xff09;。Genie存在于虚拟世界体系&#xff0c;虚拟世界体系包括&#xff08;VPS, VBS, VSS&#xff09;&#xff0…

BvSP_ Broad-view Soft Prompting for Few-Shot Aspect Sentiment Quad Prediction

中文题目: 英文题目: BvSP: Broad-view Soft Prompting for Few-Shot Aspect Sentiment Quad Prediction 论文地址: aclanthology.org/2024.acl-long.460.pdf 代码地址: https://github.com/byinhao/BvSP 论文级别&#xff0c; 单位: (2024 ACL long paper) 南开大学&#xff0…