java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot MybatisPlus实现CRUD

SpringBoot整合Mybatis Plus实现基本CRUD的示例代码

作者:JK凯

Mybatis Plus是在Mybatis的基础上的增强,使得我们对一些基本的CRUD使用起来更方便,本文主要介绍了SpringBoot整合Mybatis Plus实现基本CRUD的示例代码,具有一定的参考价值,感兴趣的可以了解一下

对数据库的操作是我们公司中必不可少的功能,Mybatis Plus是在Mybatis的基础上的增强,使得我们对一些基本的CRUD使用起来更方便等,这篇文章主要讲讲SpringBoot如何去整合Mybatis Plus,并实现基本的CRUD功能。

一、引入相应的依赖

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.5.3.1</version>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.32</version>
</dependency>

引入mybatis-plus的依赖和mysql驱动的依赖。

二、进行配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb?characterEncoding=utf-8&serverTimeZone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      id-type: auto
      logic-delete-field: deleted
      logic-delete-value: 1
      logic-not-delete-value: 0

spring.datasource是对数据库的链接信息的配置

mybatis-plus:

三、新建数据库表

这里我新建一张简单的user表

sql如下:

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `age` int(3) NOT NULL,
  `create_time` datetime DEFAULT NULL,
  `update_time` datetime DEFAULT NULL,
  `deleted` int(1) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

可以看到表中有一些建表必须的字段create_timeupdate_timedeleted,前两个字段我们需要在项目中配置一下Mybatis Plus让他在我们新增数据,更新数据时自动插入值,deleted逻辑删除字段因为我们已经在yml中配置了,后续我们都不需要再处理。

四、配置 Mybatis Plus 自动填充

配置 Mybatis Plus 自动填充来实现对create_timeupdate_time的值自动插入和更新。

具体代码实现如下:

handler.mybatisplus.MyMetaObjectHandler:

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import java.util.Date;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        setFieldValByName("createTime", new Date(), metaObject);
        setFieldValByName("updateTime", new Date(), metaObject);
    }
    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("updateTime", new Date(), metaObject);
    }
}

五、实现User实体类、UserMapper、UserService

domain.entity.User:

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@TableName("user")
public class User {
    @TableId
    private Long id;
    private String username;
    private Integer age;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
    private Integer deleted;
}

@TableName:指定实体类对应的表名

@TableId:指定为主键,我们配置的是auto,即主键自增策略

@TableField:指定该值使用我们的自动填充策略,INSERT为插入时填充,INSERT_UPDATE为插入和更新时填充

mapper.UserMapper:

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jk.domain.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}

继承Mybatis Plus提供的BaseMapper,已经实现了一些基本的CRUD接口

service.UserService:

public interface UserService {
}

service.impl.UserServiceImpl:

import com.jk.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
}

先把对应的service建好,后面实现controller时再一并实现。

六、使用Restful风格实现CRUD功能

因为我们需要在查列表时需要使用分页功能,需要配置一下Mybatis Plus分页插件

config.MybatisPlus:

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 MybatisPlus {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}

另外因为我们需要在新增和更新时是不需要全部的实体字段,需要创建对应的DTO来接收前端数据,返回时也不需要全部字段,需要对应的Vo对返回前端所需字段

domain.dto.AddUserDto:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AddUserDto {
    private String username;
    private Integer age;
}

domain.dto.UpdateUserDto:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UpdateUserDto {
    private Long id;
    private String username;
    private Integer age;
}

domain.vo.UserVo:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserVo {
    private Long id;
    private String username;
    private Integer age;
    private Date createTime;
}

domain.vo.PageVo:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageVo {
    private List result;
    private Long total;
}

PageVo用来处理所有需要分页数据的响应

关于统一响应大家可以看 SpringBoot 中统一响应格式及统一异常处理,你应该这样做

关于Bean拷贝大家可以看SpringBoot 项目中 Bean 拷贝及工具类封装

controller.UserController:

import com.jk.domain.dto.AddUserDto;
import com.jk.domain.dto.UpdateUserDto;
import com.jk.service.UserService;
import com.jk.domain.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping
    public ResponseResult addUser(@RequestBody AddUserDto addUserDto) {
        return userService.addUser(addUserDto);
    }
    @PutMapping
    public ResponseResult updateUser(@RequestBody UpdateUserDto updateUserDto) {
        return userService.updateUser(updateUserDto);
    }
    @DeleteMapping("/{id}")
    public ResponseResult deleteUser(@PathVariable("id") Long id) {
        return userService.deleteUser(id);
    }
    @GetMapping
    public ResponseResult getUser(@RequestParam(defaultValue = "1") Integer pageNum,
                                  @RequestParam(defaultValue = "10") Integer pageSize) {
        return userService.getUser(pageNum, pageSize);
    }
}

service.UserService:

import com.jk.domain.dto.AddUserDto;
import com.jk.domain.dto.UpdateUserDto;
import com.jk.domain.vo.ResponseResult;
public interface UserService {
    ResponseResult addUser(AddUserDto addUserDto);
    ResponseResult updateUser(UpdateUserDto updateUserDto);
    ResponseResult deleteUser(Long id);
    ResponseResult getUser(Integer pageNum, Integer pageSize);
}

service.impl.UserServiceImpl:

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jk.domain.dto.AddUserDto;
import com.jk.domain.dto.UpdateUserDto;
import com.jk.domain.entity.User;
import com.jk.domain.vo.UserVo;
import com.jk.mapper.UserMapper;
import com.jk.service.UserService;
import com.jk.domain.vo.PageVo;
import com.jk.domain.vo.ResponseResult;
import com.jk.utils.BeanCopyUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public ResponseResult addUser(AddUserDto addUserDto) {
        User user = BeanCopyUtils.copyBean(addUserDto, User.class);
        userMapper.insert(user);
        return ResponseResult.okResult();
    }
    @Override
    public ResponseResult updateUser(UpdateUserDto updateUserDto) {
        User user = new User();
        BeanUtils.copyProperties(updateUserDto, user);
        userMapper.updateById(user);
        return ResponseResult.okResult();
    }
    @Override
    public ResponseResult deleteUser(Long id) {
        userMapper.deleteById(id);
        return ResponseResult.okResult();
    }
    @Override
    public ResponseResult getUser(Integer pageNum, Integer pageSize) {
        Page<User> userPage = new Page<>(pageNum, pageSize);
        userMapper.selectPage(userPage, null);
        List<UserVo> userVos = BeanCopyUtils.copyBeanList(userPage.getRecords(), UserVo.class);
        PageVo pageVo = new PageVo(userVos, userPage.getTotal());
        return ResponseResult.okResult(pageVo);
    }
}

到此这篇关于SpringBoot整合Mybatis Plus实现基本CRUD的示例代码的文章就介绍到这了,更多相关SpringBoot MybatisPlus实现CRUD内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文