在 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
相关推荐
FastBean1 天前
BizAssert:一个轻量级、生产就绪的 Java 业务断言工具类
java·后端
zhuiyisuifeng1 天前
Node.js使用教程
java
李庆政3701 天前
Reactor-core 响应式编程 spring-boot-starter-webflux
java·spring boot·reactor·响应式编程·reactor-core
是Smoky呢1 天前
springAI+向量数据库+RAG入门案例
java·开发语言·ai编程
huabiangaozhi1 天前
修改表字段属性,SQL总结
java·数据库·sql
请为小H留灯1 天前
一键解决 IDEA 中 Java 项目变橙色的问题!!!
java·ide·maven·intellij-idea·java项目
小文大数据1 天前
python实现HTML转PDF
java·前端·数据库
架构师沉默1 天前
为什么 Dubbo 从 ZooKeeper 转向 Nacos?
java·后端·架构
用户8307196840821 天前
Spring Prototype Bean的四种正确使用方式
java·spring boot·后端
永恒_顺其自然1 天前
Java Web 传统项目异步分块上传系统实现方案
java·开发语言·前端