SpringBoot集成MyBatis和FlyWay

一、什么是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精细化地操作数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值