【快速上手】使用SpringBoot 2.X + Mybatis-Plus 轻松实现CRUD

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第15天,点击查看活动详情


最近在做一个公司的内部使用的工具,主要负责后端接口层的开发,公司里面的项目都是大数据相关的开发,导致后端开发的技术有点遗忘,借此机会对后端技术进行一次回顾,选择了目前较为流行的Spring BootMybatis - plus两个快速、轻便的开发框架,接下来就对这两个框架整合实现CRUD进行一次总结输出。

环境准备

在开始开发之前,我们需要准备一些环境配置:

  • jdk 1.8 或其他更高版本
  • 开发工具 IDEA
  • 数据库 Mysql
  • 管理依赖 Maven
  • MybatisX插件(可选)

在IDEA中安装MybatisX插件

打开 IDEA,进入 File -> Settings -> Plugins -> Marketplace,输入 mybatisx 搜索并安装,安装成功后如下图:

在这里插入图片描述

创建元数据

进入到Mysql中创建一个数据库名为test,然后创建一张User表:

		CREATE DATABASE test;
		USE test;
		
		DROP TABLE IF EXISTS USER;
		
		CREATE TABLE USER
		(
		    id BIGINT(20) NOT NULL COMMENT '主键ID',
		    NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
		    age INT(11) NULL DEFAULT NULL COMMENT '年龄',
		    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
		    phone VARCHAR(50) NULL DEFAULT NULL COMMENT '电话',
		    PRIMARY KEY (id)
		);
复制代码

User表中添加一些数据:

INSERT INTO USER (id, NAME, age, email,phone) VALUES
(1, 'Jone', 18, '[email protected]',13726732387),
(2, 'Jack', 20, '[email protected]',18390293849),
(3, 'Tom', 28, '[email protected]',17832783209),
(4, 'Sandy', 21, '[email protected]',13290763478),
(5, 'Billie', 24, '[email protected]',18934309874);
复制代码

初始化工程

打开idea -> file -> Nwe -> Project ,如图

在这里插入图片描述

勾选团写相关的配置信息:

在这里插入图片描述

选择初始的依赖配置:

在这里插入图片描述

引入Mybatis - Plus依赖,demo项目所有依赖如下:

	 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--mybatis - plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
    </dependencies>
复制代码

至此,整个demo所需要i的环境、依赖、工程初始化完成。

配置数据库

application.yml 配置文件中添加 Mysql 数据库的相关配置:(注意Url路径

# 数据库连接配置
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
    username: root
    password: xxxxxx
复制代码

Spring Boot 启动类中添加 @MapperScan 注解,扫描 dao文件夹:

@SpringBootApplication
@MapperScan("com.zhao.demo.dao")
public class DemoApplication {

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

编写代码

编写实体类User,使用lombok简化实体类代码:

	@Data
	@AllArgsConstructor
	@NoArgsConstructor
	public class User {
	    private Integer id;
	    private String name;
	    private Integer age;
	    private String email;
	    private String phone;
	}

复制代码

编写UserDao接口,需要继承自BaseMapper<> 接口:

public interface UserDao extends BaseMapper<User> {

}
复制代码

编写service层的接口以及实现类:

public interface UserService {

    List<User> getUserList();

    User getUserById(Integer id);

    int addUser(User user);

    int updateUser(User user);

    int deleteUser(Integer id);
}

复制代码
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> getUserList() {
        return userDao.selectList(null);
    }

    @Override
    public User getUserById(Integer id){
        return userDao.selectById(id);
    }

    @Override
    public int addUser(User user){
        return  userDao.insert(user);
    }

    @Override
    public int updateUser(User user){
        return  userDao.updateById(user);
    }

    @Override
    public int deleteUser(Integer id){
        return  userDao.deleteById(id);
    }

}

复制代码

编写controller层后端接口,使用ApiPost进行接口的测试:

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user")
    public List<User> getUsers() {
        List<User> userList = userService.getUserList();
        return userList;
    }

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

    @GetMapping("/addUser")
    public void addUser(@RequestParam("id") Integer id,
                        @RequestParam("name") String name,
                        @RequestParam("age") Integer age,
                        @RequestParam("email") String email,
                        @RequestParam("phone") String phone) {

        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setAge(age);
        user.setEmail(email);
        user.setPhone(phone);

        int result = userService.addUser(user);
        if (result > 0) {
            System.out.println("添加成功");
            getUserById(user.getId());
        } else {
            System.out.println("添加失败");
        }
    }
}
复制代码

测试输出

编写一个测试类测试CRUD:

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    private UserDao userDao;
	
	// 查询所有用户
    @Test
    public void getUsers() {
        List<User> users = userDao.selectList(null);
        for (User user : users) {
            System.out.println(user);
        }
    }
	// 根据 id查找用户
    @Test
    public void getUserById(){
        User user = userDao.selectById(1);
        System.out.println(user);
    }

    @Test
    public void getUserById(Integer id){
        User user = userDao.selectById(id);
        System.out.println(user);
    }
    
	// 添加用户
    @Test
    public void insertUser(){
        User user = new User(7,"李四",14,"[email protected]","16723238975");
        int result = userDao.insert(user);
        if (result > 0){
            System.out.println("添加成功");
            getUserById(user.getId());
        }else{
            System.out.println("添加失败");
        }
    }
	
	// 修改用户
    @Test
    public void updateUser(){
        User user = new User(7,"李四",16,"[email protected]","16723238975");
        int result = userDao.updateById(user);
        if (result > 0){
            System.out.println("修改成功");
            getUserById(user.getId());
        }else{
            System.out.println("修改失败");
        }
    }
	
	// 删除用户
    @Test
    public void deleteUser(){
        int result = userDao.deleteById(7);
        if (result > 0){
            System.out.println("删除成功");
            getUsers();
        }else{
            System.out.println("删除失败");
        }
    }
}

复制代码

使用ApiPost进行接口测试:(以"/user"接口为例)请求地址:http://localhost:8888/user 响应结果:

[
	{
		"id": 1,
		"name": "Jone",
		"age": 18,
		"email": "[email protected]",
		"phone": "13726732387"
	},
	{
		"id": 2,
		"name": "Jack",
		"age": 20,
		"email": "[email protected]",
		"phone": "18390293849"
	},
	{
		"id": 3,
		"name": "Tom",
		"age": 28,
		"email": "[email protected]",
		"phone": "17832783209"
	},
	{
		"id": 4,
		"name": "Sandy",
		"age": 21,
		"email": "[email protected]",
		"phone": "13290763478"
	},
	{
		"id": 5,
		"name": "Billie",
		"age": 24,
		"email": "[email protected]",
		"phone": "18934309874"
	},
	{
		"id": 6,
		"name": "李四",
		"age": 14,
		"email": "[email protected]",
		"phone": "16723238975"
	},
	{
		"id": 562139137,
		"name": null,
		"age": null,
		"email": null,
		"phone": null
	}
]
复制代码

接口测试成功!!

在这里插入图片描述

本次分享的内容到这里就结束了,希望对大家有所帮助!!!

猜你喜欢

转载自juejin.im/post/7130807058076565540