【Java】springBoot + spring mvc + mybatisPlus 结合使用完整示例

这里是一个使用 Spring Boot 和 MyBatis-Plus 的完整示例,展示如何集成 MyBatis-Plus 并实现基本的 CRUD 操作。本示例将包括项目结构、数据库配置、实体类、Mapper 接口、Service 层、Controller 层,以及 MyBatis-Plus 的一些常用功能。

项目结构

在开始之前,让我们看看项目的目录结构:

springboot-mybatisplus-demo/
│
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           └── demo/
│   │   │               ├── config/       // 配置类
│   │   │               │   └── MybatisPlusConfig.java
│   │   │               ├── controller/   // 控制器
│   │   │               │   └── UserController.java
│   │   │               ├── mapper/       // Mapper 接口
│   │   │               │   └── UserMapper.java
│   │   │               ├── model/        // 实体类
│   │   │               │   └── User.java
│   │   │               ├── service/      // 服务接口
│   │   │               │   ├── UserService.java
│   │   │               │   └── impl/
│   │   │               │       └── UserServiceImpl.java
│   │   │               └── DemoApplication.java
│   │   └── resources/
│   │       ├── application.yml   // 配置文件
│   │       └── mapper/           // MyBatis-Plus XML 映射文件
│   │           └── UserMapper.xml
└── pom.xml       // Maven 配置文件

步骤一:准备工作

1. 创建 Spring Boot 项目

可以使用 Spring Initializr 创建项目,也可以手动配置 pom.xml

Maven 配置 (pom.xml):

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>springboot-mybatisplus-demo</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <!-- Spring Boot Web Starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Data JPA -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- Spring Boot Test Starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- MySQL Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

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

        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Spring Boot Maven Plugin -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
2. 数据库配置

创建一个名为 demo 的 MySQL 数据库,并在其中创建 user 表。

CREATE DATABASE demo;

USE demo;

CREATE TABLE `user` (
    `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(50) NOT NULL,
    `age` INT(11),
    `email` VARCHAR(100),
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
3. 配置文件 (application.yml)
server:
  port: 8080

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC
    username: root
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver

  mybatis-plus:
    mapper-locations: classpath:/mapper/*.xml
    configuration:
      log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

步骤二:代码实现

1. 实体类 (User.java)

com.example.demo.model 包下创建 User 实体类,并使用 Lombok 简化代码。

package com.example.demo.model;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName("user") // 指定对应的表名
public class User {

    @TableId // 指定主键
    private Long id;

    private String name;
    private Integer age;
    private String email;
}
2. Mapper 接口 (UserMapper.java)

com.example.demo.mapper 包下创建 UserMapper 接口,并继承 BaseMapper

package com.example.demo.mapper;

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

@Mapper
public interface UserMapper extends BaseMapper<User> {
    // 自定义 SQL 查询可以在此处添加
}
3. Service 接口 (UserService.java)

com.example.demo.service 包下创建 UserService 接口,并继承 IService

package com.example.demo.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.model.User;

public interface UserService extends IService<User> {
    // 自定义业务逻辑可以在此处添加
}
4. Service 实现类 (UserServiceImpl.java)

com.example.demo.service.impl 包下创建 UserServiceImpl 类,并继承 ServiceImpl

package com.example.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 自定义业务逻辑可以在此处实现
}
5. 控制器 (UserController.java)

com.example.demo.controller 包下创建 UserController 控制器。

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 添加用户
    @PostMapping("/add")
    public boolean addUser(@RequestBody User user) {
        return userService.save(user);
    }

    // 根据 ID 删除用户
    @DeleteMapping("/delete/{id}")
    public boolean deleteUser(@PathVariable Long id) {
        return userService.removeById(id);
    }

    // 更新用户信息
    @PutMapping("/update")
    public boolean updateUser(@RequestBody User user) {
        return userService.updateById(user);
    }

    // 根据 ID 查询用户
    @GetMapping("/get/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getById(id);
    }

    // 查询所有用户
    @GetMapping("/list")
    public List<User> listUsers() {
        return userService.list();
    }

    // 分页查询用户
    @GetMapping("/page")
    public Page<User> pageUsers(@RequestParam int current, @RequestParam int size) {
        Page<User> page = new Page<>(current, size);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return userService.page(page, queryWrapper);
    }


}
6. XML 映射文件 (UserMapper.xml)

src/main/resources/mapper 目录下创建 UserMapper.xml 文件。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.demo.mapper.UserMapper">

    <!-- 自定义 SQL 语句可以在此处添加 -->

</mapper>
7. MyBatis-Plus 配置类 (MybatisPlusConfig.java)

com.example.demo.config 包下创建 MybatisPlusConfig 类,用于配置 MyBatis-Plus 插件。

package com.example.demo.config;

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());
        return interceptor;
    }
}
8. 主应用类 (DemoApplication.java)

com.example.demo 包下创建 DemoApplication 类。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.demo.mapper") // 指定扫描的 Mapper 包路径
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

步骤三:运行项目

在 IDE 中运行 DemoApplication,项目启动后,可以通过以下方式进行测试:

  1. 添加用户

    POST http://localhost:8080/user/add
    Content-Type: application/json
    
    {
        "name": "Tom",
        "age": 25,
        "email": "tom@example.com"
    }
    
  2. 查询所有用户

    GET http://localhost:8080/user/list
    
  3. 根据 ID 查询用户

    GET http://localhost:8080/user/get/1
    
  4. 更新用户信息

    PUT http://localhost:8080/user/update
    Content-Type: application/json
    
    {
        "id": 1,
        "name": "Tom",
        "age": 26,
        "email": "tom@example.com"
    }
    
  5. 根据 ID 删除用户

    DELETE http://localhost:8080/user/delete/1
    
  6. 分页查询用户

    GET http://localhost:8080/user/page?current=1&size=10
    

总结

本示例展示了如何在 Spring Boot 项目中集成 MyBatis-Plus,并实现基本的 CRUD 操作、分页查询等功能。MyBatis-Plus 提供了强大的插件支持,简化了常见数据库操作的实现过程。在实际应用中,可以根据业务需求进一步扩展和优化。

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值