在 VS Code 中用 MyBatis 操作数据库的 Spring Boot 示例

构建一个 非 Web 的 Spring Boot 项目 ,集成 MyBatis,通过 CommandLineRunner 或 JUnit 测试来验证 MyBatis 项目代码。


一、创建项目(不包含 Spring Web)

使用 Spring Initializr(VS Code 内)

  1. 在 VS Code 中按 Ctrl+Shift+P,输入:

    复制代码
    Spring Initializr: Generate a Maven Project
  2. 配置如下:

    • Language: Java
    • Spring Boot: 3.0.2
    • Group: com.example
    • Artifact: mybatis-demo-cli
    • Dependencies(关键!不要选 Spring Web)
      • MyBatis Framework
      • MySQL Driver(或其他数据库驱动)

这样生成的项目默认是 non-web application(因为没引入 Web starter)。


二、配置数据库(application.yml)

复制代码
# src/main/resources/application.yml
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo_db?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
    username: root
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  configuration:
    map-underscore-to-camel-case: true
  type-aliases-package: com.example.mybatisdemo.model

三、编写核心代码

1. 实体类

复制代码
// src/main/java/com/example/mybatisdemo/model/User.java
package com.example.mybatisdemo.model;

public class User {
    private Integer id;
    private String name;
    private String email;

    // Getters and Setters
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }

    @Override
    public String toString() {
        return "User{id=" + id + ", name='" + name + "', email='" + email + "'}";
    }
}

2. Mapper 接口

复制代码
// src/main/java/com/example/mybatisdemo/mapper/UserMapper.java
package com.example.mybatisdemo.mapper;

import com.example.mybatisdemo.model.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    @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);
}

3. 主启动类(使用 CommandLineRunner 测试)

复制代码
// src/main/java/com/example/mybatisdemo/MybatisDemoApplication.java
package com.example.mybatisdemo;

import com.example.mybatisdemo.mapper.UserMapper;
import com.example.mybatisdemo.model.User;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class MybatisDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisDemoApplication.class, args);
    }

    @Bean
    public CommandLineRunner demo(UserMapper userMapper) {
        return (args) -> {
            // 查询所有用户
            System.out.println("Existing users:");
            userMapper.findAll().forEach(System.out::println);

            // 插入新用户
            User newUser = new User();
            newUser.setName("CLI User");
            newUser.setEmail("cli@example.com");
            userMapper.insert(newUser);

            System.out.println("Inserted new user with ID: " + newUser.getId());

            // 再次查询
            System.out.println("All users after insert:");
            userMapper.findAll().forEach(System.out::println);
        };
    }
}

CommandLineRunner 会在 Spring 容器启动完成后自动执行,非常适合非 Web 场景的测试。


四、运行项目

在 VS Code 终端中执行:

复制代码
./mvnw spring-boot:run

你会看到控制台输出数据库中的用户列表,并插入一条新记录。


五、使用 JUnit 单元测试

你也可以写一个测试类来验证 MyBatis:

复制代码
// src/test/java/com/example/mybatisdemo/MybatisTest.java
package com.example.mybatisdemo;

import com.example.mybatisdemo.mapper.UserMapper;
import com.example.mybatisdemo.model.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
public class MybatisTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    void testFindAll() {
        List<User> users = userMapper.findAll();
        assertThat(users).isNotEmpty();
        System.out.println("Found users: " + users);
    }

    @Test
    void testInsert() {
        User user = new User();
        user.setName("Test User");
        user.setEmail("test@example.com");
        userMapper.insert(user);
        assertThat(user.getId()).isNotNull();
        System.out.println("Inserted user ID: " + user.getId());
    }
}

运行测试:

  • 在 VS Code 中点击测试方法旁的 "Run Test" 按钮
  • 或终端执行:./mvnw test
相关推荐
zhouyunjian2 小时前
syncronized使用与深入研究
java·开发语言
明洞日记2 小时前
【设计模式手册006】建造者模式 - 复杂对象的优雅构建之道
java·设计模式·建造者模式
S***q1922 小时前
后端服务架构设计:从单体到微服务
java·微服务·架构
T***u3332 小时前
微服务书籍
java·微服务·架构
ZHE|张恒3 小时前
设计模式(二)工厂方法模式 — 把创建权限下放给子类,像“可扩展的生产线”
java·开发语言·设计模式
qq_12498707533 小时前
基于springboot的兴趣生活展示交流平台的设计与实现(源码+论文+部署+安装)
java·spring boot·生活·毕设
明洞日记3 小时前
【设计模式手册008】适配器模式 - 让不兼容的接口协同工作
java·设计模式·适配器模式
zzz海羊3 小时前
VSCode配置java中的lombok
java·开发语言·vscode
A-code3 小时前
Git 多模块项目管理
java·开发语言