构建一个 非 Web 的 Spring Boot 项目 ,集成 MyBatis,通过 CommandLineRunner 或 JUnit 测试来验证 MyBatis 项目代码。
一、创建项目(不包含 Spring Web)
使用 Spring Initializr(VS Code 内)
-
在 VS Code 中按
Ctrl+Shift+P,输入:Spring Initializr: Generate a Maven Project -
配置如下:
- 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