当前位置: 首页 > news >正文

在 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=trueusername: rootpassword: your_passworddriver-class-name: com.mysql.cj.jdbc.Drivermybatis:configuration:map-underscore-to-camel-case: truetype-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 Setterspublic 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; }@Overridepublic 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);}@Beanpublic 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 {@Autowiredprivate UserMapper userMapper;@Testvoid testFindAll() {List<User> users = userMapper.findAll();assertThat(users).isNotEmpty();System.out.println("Found users: " + users);}@Testvoid 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

http://www.dtcms.com/a/610403.html

相关文章:

  • 唐山网站建设开发专业网站建设经费申请
  • Java 抽象类
  • 基于Unity YooAsset自动化资源管理框架,附源代码
  • 域名注册要多少钱信阳新网站做seo优化
  • 做网站盈利方式开发一个简单的app需要多少钱
  • RPA 重构财务新生态:自动化驱动的转型革命
  • Kubernetes调度器深度解析:从资源分配到亲和性策略的架构师之路
  • 具身智能-一文详解视觉-语言-动作(VLA)大模型(3
  • 【Linux C/C++开发】libusb库操作-获取USB设备信息
  • LeetCode 刷题【154. 寻找旋转排序数组中的最小值 II】
  • 大视频秒级同步:高性能跨系统视频数据迁移实战方案
  • 手机网站制作哪家公司好wordpress 查件
  • 优化 TDengine IDMP 面板编辑的几种方法​
  • 定制开发AI智能名片S2B2C预约服务小程序的定制开发与优势分析
  • 哪个做网站平台好电子商务与网站建设实践论文
  • 填充每个节点的下一个右侧节点指针(一)
  • 基于RFSOC47DR的射频采集卡
  • 东莞齐诺做网站网站做服装那个平台好一点
  • 长春模板网站建设企业网站开发难吗
  • 国外网站不需要备案吗看wordpress导出文章
  • DeepSeek-OCR私有化部署—从零构建OCR服务环境
  • Navicat 17 连接 SQL Server 后在导航栏中没有显示数据库表对象,如何解决?
  • 官方网站下载手电筒网站设置在哪
  • 如何建设阿里巴巴网站东莞现代建设有限公司
  • 【openGauss】让gsql和sqlplus输出包含有SQL及数据的完全一致的文本文件
  • LingJing(灵境)桌面级靶场平台新增靶机:加密攻防新挑战:encrypt-labs靶场,全面提升安全研究者的实战能力!
  • 高通SMD450 pop音问题回顾
  • 【LeetCode】将 x 减到 0 的最小操作数
  • Spring Boot 2.7.x 至 2.7.18 及更旧的版本,漏洞说明
  • GEO:抢占AI流量新入口,让品牌成为智能问答中的“标准答案”