Springboot整合MybatisPlus的基本CRUD

目录

  • 前言
  • 1. 搭建项目
  • 2. 基本的CRUD

前言

发现项目框架是MybatisPlus的,由于个人使用该框架的CRUD比较少
对此学习过程中,从零到有开始搭建学习还是比较重要的,感悟会比较多

关于各个类的使用,可看如下文章:

  1. 剖析Java中的Entity、service、serviceImpl、Mapper以及Controller层之间的关系(代码诠释)
  2. 区分JAVA项目中的ENTITY,VO,DTO,BO

1. 搭建项目

为了更好展示
在数据库中设计一张表,并且在表格中添加数据(数据和表格名称具体看个人实操):

其中主键id需要设置自增!

Springboot整合MybatisPlus的基本CRUD_第1张图片

其内容具体如下所示:

Springboot整合MybatisPlus的基本CRUD_第2张图片

在代码模块中,搭建基本的spring项目(由于现有的springboot模块比较新,不好兼容,对此需要对pom文件进行修改):


<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.6.15version>
        <relativePath/> 
    parent>
    <groupId>com.examplegroupId>
    <artifactId>demoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>demoname>
    <description>demodescription>
    <properties>
        <java.version>21java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.3.0version>
        dependency>

        <dependency>
            <groupId>com.mysqlgroupId>
            <artifactId>mysql-connector-jartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starter-testartifactId>
            <version>2.3.0version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.3.1version>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <image>
                        <builder>paketobuildpacks/builder-jammy-base:latestbuilder>
                    image>
                configuration>
            plugin>
        plugins>


        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>

    build>


project>

并且配置好数据库文件:

server.port=8081
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/blade_test?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&tinyInt1isBit=false&allowMultiQueries=true&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root

主体的项目文件如下所示:

Springboot整合MybatisPlus的基本CRUD_第3张图片

启动类如下所示:

package com.example.demo;

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

@MapperScan("com.example.demo.mapper")
@SpringBootApplication
public class DemoApplication {

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

}

其中User实体类如下所示:

package com.example.demo.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


@Data
//@AllArgsConstructor
//@NoArgsConstructor
@TableName("test_user")
public class User {
    @TableId(type = IdType.AUTO)
    private int id;
    private String username;
    private String password;
    // 其他字段...
}

对应的Mapper类如下所示:

package com.example.demo.mapper;

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

@Mapper
public interface UserMapper extends BaseMapper<User> {
    // 这里可以自定义一些查询方法
}

其Service类如下所示:

package com.example.demo.service;

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

public interface UserService extends IService<User> {
    // 这里可以自定义一些业务方法
}

Serviceimpl类如下所示:

package com.example.demo.service.impl;

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

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 这里可以实现自定义的业务方法
}

为了方便测试可以写一个Springboot的测试类:(其包名一定要对应一致):

package com.example.demo;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)

class DemoApplicationTests {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserService userService;

2. 基本的CRUD

可以再controller中写入方法,并测试其接口。也可直接再测试类中输入,有可观的输出

类似Controller类中:

package com.example.demo.controller;

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

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

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/select")
    public User getUserById() {
        User user = userMapper.selectById(1);
        return user;
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable int id) {
        return userService.getById(id);
    }

    @PostMapping("/add")
    public String addUser(@RequestBody User user) {
        userService.save(user);
        return "User added successfully!";
    }

    @PutMapping("/update")
    public String updateUser(@RequestBody User user) {
        userService.updateById(user);
        return "User updated successfully!";
    }

    @DeleteMapping("/delete/{id}")
    public String deleteUser(@PathVariable int id) {
        userService.removeById(id);
        return "User deleted successfully!";
    }
}

通过接口进行测试,具体如下:

Springboot整合MybatisPlus的基本CRUD_第4张图片

或者直接再测试类:

    @Test
    public void TestSelectById(){
        User user = userMapper.selectById(1);
        System.out.println(user);
    }

结果如下:

在这里插入图片描述

又比如测试类中的这些CRUD方法:(诸如其他,各位博友可自行尝试):

    @Test
    public void getUserById() {

        List<User> one = userMapper.selectList(Wrappers.<User>lambdaQuery().eq(User::getUsername,"manong"));
        System.out.println(one);
    }

截图如下:

在这里插入图片描述

其中service以及mapper都有其各自的方法进行CRUD

你可能感兴趣的:(java,spring,boot,后端,java)