在 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
相关推荐
皮皮林5516 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河7 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
桦说编程9 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
躺平大鹅11 小时前
Java面向对象入门(类与对象,新手秒懂)
java
初次攀爬者12 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺12 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart13 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
NE_STOP14 小时前
MyBatis-mybatis入门与增删改查
java
孟陬18 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端