快速搭建SpringBoot项目并整合MyBatis-Plus

1、Spring Boot 核心内容

1.1 特性

  • 自动配置:根据项目的依赖自动配置相关的 Bean

  • 内嵌服务器:Spring Boot 默认提供嵌入式服务器(如 Tomcat、Jetty 或 Undertow),可以直接运行应用

1.2 常用注解

  1. @SpringBootApplication 注解:一个组合注解,包含以下三个注解:
  • @Configuration:声明这是一个配置类,Spring 容器会扫描并处理该类中的配置。
  • @EnableAutoConfiguration:启用 Spring Boot 的自动配置功能。
  • @ComponentScan:启用组件扫描,查找并注册所有带有 @Component、@Service、@Repository 等注解的 Bean
  1. @RestController:简化 @Controller 和 @ResponseBody 的使用,用于定义 RESTful API 控制器。
  2. @Value:用于从配置文件中获取值并注入到类中
  3. @Autowired:自动注入 Bean,Spring 会根据类型自动装配依赖。

2、创建Spring Boot项目并整合MyBatis-Plus

2.1 修改pom.xml,添加MuBatis-Plus依赖

xml 复制代码
<!-- Spring Boot Web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- MyBatis-Plus Starter -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.3.1</version>
</dependency>

2.2 配置application.yml

yml 复制代码
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/example_db?useSSL=false&serverTimezone=UTC&characterEncoding=utf8
    username: root
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver
    # HikariCP连接池配置
    hikari:
      maximum-pool-size: 10
      minimum-idle: 5
      connection-timeout: 30000

# MyBatis-Plus配置
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  # 打印SQL日志
    map-underscore-to-camel-case: true                      # 驼峰映射
  global-config:
    db-config:
      id-type: auto                                          # 主键自增
      logic-delete-field: deleted                            # 逻辑删除字段
      logic-delete-value: 1
      logic-not-delete-value: 0
  mapper-locations: classpath:/mapper/*.xml                  # mapper.xml位置
  type-aliases-package: com.example.entity                  # 实体类包

2.3 创建实体类entity和Mapper接口

java 复制代码
package com.example.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.util.Date;

@Data  // Lombok自动生成getter/setter/toString等
@TableName("user")
public class User {
    @TableId(type = IdType.AUTO)
    private Integer id;
    private String username;
    private String password;
    @TableField("real_name")
    private String realName;
    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private Date createTime;
}
java 复制代码
package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

2.4 创建Service层和Controller层

java 复制代码
package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {
    //添加自定义的方法
    User login(String username, String password);
    boolean register(User user);
}
java 复制代码
package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * POST /api/users/login
     * Body: { "username": "admin", "password": "123456" }
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginInfo) {
        String username = loginInfo.get("username");
        String password = loginInfo.get("password");
        User user = userService.login(username, password);
        Map<String, Object> result = new HashMap<>();
        if (user != null) {
            result.put("code", 200);
            result.put("message", "登录成功");
            result.put("data", user);
        } else {
            result.put("code", 401);
            result.put("message", "用户名或密码错误");
        }
        return result;
    }

    /**
     * 用户注册
     * POST /api/users/register
     * Body: { "username": "test", "password": "123", "realName": "测试" }
     */
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        boolean success = userService.register(user);
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("message", "注册成功");
        } else {
            result.put("code", 400);
            result.put("message", "用户名已存在");
        }
        return result;
    }
}

2.5 完善Spring Boot启动类

java 复制代码
package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.mapper")  // 扫描Mapper接口
public class HospitalSystemApplication {
    public static void main(String[] args) {
        SpringApplication.run(HospitalSystemApplication.class, args);
    }
}

3、完善基础架构(统一返回格式 + 全局异常处理 + MyBatis-Plus分页插件)

3.1 统一返回格式

定义统一返回结果类

java 复制代码
package com.example.common;

import lombok.Data;

@Data
public class Result<T> {
    private Integer code;
    private String message;
    private T data;

    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setCode(200);
        result.setMessage("success");
        result.setData(data);
        return result;
    }

    public static <T> Result<T> error(Integer code, String message) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        return result;
    }
}

修改Controller使用统一返回格式

java 复制代码
@PostMapping("/login")
public Result<User> login(@RequestBody Map<String, String> loginInfo) {
    String username = loginInfo.get("username");
    String password = loginInfo.get("password");
    User user = userService.login(username, password);
    if (user != null) {
        return Result.success(user);
    } else {
        return Result.error(401, "用户名或密码错误");
    }
}

@PostMapping("/register")
public Result<User> register(@RequestBody User user){
    boolean success = userService.register(user);

    if(success) {
        return Result.success(user);
    } else {
        return Result.error(400,"用户名已存在,注册失败");
    }
}

3.2 全局异常处理

java 复制代码
package com.example.common;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public Result<String> handleRuntimeException(RuntimeException e) {
        e.printStackTrace();
        return Result.error(500, e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e) {
        e.printStackTrace();
        return Result.error(500, "系统错误:" + e.getMessage());
    }
}

3.3 MyBatis-Plus分页插件配置

java 复制代码
package com.example.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
相关推荐
星如雨グッ!(๑•̀ㅂ•́)و✧2 小时前
WebFlux onErrorContinue 和 onErrorResume使用详解
java·人工智能
电商API&Tina2 小时前
电商数据采集API接口||合规优先、稳定高效、数据精准
java·javascript·数据库·python·json
zjjsctcdl2 小时前
springBoot发布https服务及调用
spring boot·后端·https
观测云2 小时前
SpringBootAI 接入观测云 MCP 最佳实践
spring boot·观测云·mcp
zdl6863 小时前
Spring Boot文件上传
java·spring boot·后端
世界哪有真情3 小时前
哇!绝了!原来这么简单!我的 Java 项目代码终于被 “拯救” 了!
java·后端
RMB Player3 小时前
Spring Boot 集成飞书推送超详细教程:文本消息、签名校验、封装工具类一篇搞定
java·网络·spring boot·后端·spring·飞书
重庆小透明3 小时前
【搞定面试之mysql】第三篇 mysql的锁
java·后端·mysql·面试·职场和发展
RuoyiOffice3 小时前
企业请假销假系统设计实战:一张表、一套流程、两段生命周期——BPM节点驱动的表单变形术
java·spring·uni-app·vue·产品运营·ruoyi·anti-design-vue