实战六:SpringBoot集成mybatis-plus和swagger

目录

一、集成mybatis-plus

1、引入依赖

2、日志启动

3、实体类与表、主键、字段对应关系

4、配置类

二、集成swagger

1、依赖

2、配置类

3、报错

三、mybatis-plus实现增删改查

1、entity

 2、interface

 3、service

 4、mapper.xml

5、controller


一、集成mybatis-plus

1、引入依赖



com.baomidou
mybatis-plus-boot-starter
3.5.1

2、日志启动

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3、实体类与表、主键、字段对应关系

package com.example.demo.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import java.util.Date;
import java.util.List;

@Data
@TableName(value = "user")
public class User {
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    private String username;
    @JsonIgnore
    private String password;
    private String nickname;
    private String email;
    private String phone;
    private String address;
    private String avatarUrl;
    private Date createTime;
    private String role;
    @TableField(exist = false)
    private List courses;
    @TableField(exist = false)
    private List stuCourses;
}

4、配置类

package com.example.demo.config;

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

@Configuration
@MapperScan("com.example.demo.mapper")
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

}

mybatis-plus 官网:简介 | MyBatis-Plus

二、集成swagger

1、依赖



    io.springfox
    springfox-swagger2
    2.9.2


    io.springfox
    springfox-swagger-ui
    2.9.2

2、配置类

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2public 
class SwaggerConfig {
        @Bean        
        public Docket restApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .groupName("标准接口")
                    .apiInfo(apiInfo("Springboot使用Swagger2构建Restful APIs","1.0"))
                    .useDefaultResponseMessages(true)
                    .forCodeGeneration(false)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }

        private ApiInfo apiInfo(String title,String version) {
            return new ApiInfoBuilder()
                    .title(title)
                    .description("swagger实战")
                    .termsOfServiceUrl("")
                    .version("1.0")
                    .build();
        }
}

3、报错

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.22.jar:5.3.22]
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.22.jar:5.3.22]
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.22.jar:5.3.22]
    at java.lang.Iterable.forEach(Iterable.java:75) ~[na:1.8.0_231]
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.22.jar:5.3.22]
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.22.jar:5.3.22]
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.22.jar:5.3.22]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.22.jar:5.3.22]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.3.jar:2.7.3]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) [spring-boot-2.7.3.jar:2.7.3]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) [spring-boot-2.7.3.jar:2.7.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) [spring-boot-2.7.3.jar:2.7.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) [spring-boot-2.7.3.jar:2.7.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) [spring-boot-2.7.3.jar:2.7.3]
    at com.czh.swagger.SwaggerDemoApplication.main(SwaggerDemoApplication.java:12) [classes/:na]
Caused by: java.lang.NullPointerException: null
    at springfox.documentation.spi.service.contexts.Orderings$8.compare(Orderings.java:112) ~[springfox-spi-2.9.2.jar:null]
    at springfox.documentation.spi.service.contexts.Orderings$8.compare(Orderings.java:109) ~[springfox-spi-2.9.2.jar:null]
    at com.google.common.collect.ComparatorOrdering.compare(ComparatorOrdering.java:37) ~[guava-20.0.jar:na]
    at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) ~[na:1.8.0_231]
    at java.util.TimSort.sort(TimSort.java:220) ~[na:1.8.0_231]
    at java.util.Arrays.sort(Arrays.java:1438) ~[na:1.8.0_231]
    at com.google.common.collect.Ordering.sortedCopy(Ordering.java:855) ~[guava-20.0.jar:na]
    at springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider.requestHandlers(WebMvcRequestHandlerProvider.java:57) ~[springfox-spring-web-2.9.2.jar:null]
    at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper$2.apply(DocumentationPluginsBootstrapper.java:138) ~[springfox-spring-web-2.9.2.jar:null]
    at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper$2.apply(DocumentationPluginsBootstrapper.java:135) ~[springfox-spring-web-2.9.2.jar:null]
    at com.google.common.collect.Iterators$7.transform(Iterators.java:750) ~[guava-20.0.jar:na]
    at com.google.common.collect.TransformedIterator.next(TransformedIterator.java:47) ~[guava-20.0.jar:na]
    at com.google.common.collect.TransformedIterator.next(TransformedIterator.java:47) ~[guava-20.0.jar:na]
    at com.google.common.collect.MultitransformedIterator.hasNext(MultitransformedIterator.java:52) ~[guava-20.0.jar:na]
    at com.google.common.collect.MultitransformedIterator.hasNext(MultitransformedIterator.java:50) ~[guava-20.0.jar:na]
    at com.google.common.collect.ImmutableList.copyOf(ImmutableList.java:249) ~[guava-20.0.jar:na]
    at com.google.common.collect.ImmutableList.copyOf(ImmutableList.java:209) ~[guava-20.0.jar:na]
    at com.google.common.collect.FluentIterable.toList(FluentIterable.java:614) ~[guava-20.0.jar:na]
    at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.defaultContextBuilder(DocumentationPluginsBootstrapper.java:111) ~[springfox-spring-web-2.9.2.jar:null]
    at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.buildContext(DocumentationPluginsBootstrapper.java:96) ~[springfox-spring-web-2.9.2.jar:null]
    at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:167) ~[springfox-spring-web-2.9.2.jar:null]
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.22.jar:5.3.22]
    ... 14 common frames omitted

需要在application.properties添加

spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

项目启动后,swagger地址:http://localhost:9090/swagger-ui.html#/

三、mybatis-plus实现增删改查

1、entity

package com.example.demo.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import java.util.Date;
import java.util.List;

@Data
@TableName(value = "user")
public class User {
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    private String username;
    @JsonIgnore
    private String password;
    private String nickname;
    private String email;
    private String phone;
    private String address;
    private String avatarUrl;
    private Date createTime;
    private String role;
    @TableField(exist = false)
    private List courses;
    @TableField(exist = false)
    private List stuCourses;
}

 2、interface

package com.example.demo.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.dto.UserDto;
import com.example.demo.dto.UserPasswordDTO;
import com.example.demo.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * 

* 服务类 *

* * @author cizhu * @since 2023-11-12 */ public interface IUserService extends IService { UserDto login(UserDto userDto); User register(UserDto userDto); Page findPage(IPage page, String username, String email, String address); void updatePassword(UserPasswordDTO userPasswordDTO); }

 3、service

package com.example.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Constants;
import com.example.demo.dto.UserDto;
import com.example.demo.dto.UserPasswordDTO;
import com.example.demo.entity.Menu;
import com.example.demo.entity.User;
import com.example.demo.exception.ServiceException;
import com.example.demo.mapper.RoleMapper;
import com.example.demo.mapper.RoleMenuMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.IMenuService;
import com.example.demo.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 

* 服务实现类 *

* * @author cizhu * @since 2023-11-12 */ @Service public class UserServiceImpl extends ServiceImpl implements IUserService { @Resource private RoleMapper roleMapper; @Resource private RoleMenuMapper roleMenuMapper; @Resource private UserMapper userMapper; @Autowired private IMenuService iMenuService; @Override public UserDto login(UserDto userDto) { User one = getUserInfo(userDto); if (one != null) { BeanUtil.copyProperties(one, userDto, true); String token = TokenUtils.genToken(one.getId().toString(), one.getPassword()); userDto.setToken(token); String flag = one.getRole(); //获取当前角色的菜单 List
roleMenus = getRoleMenus(flag); userDto.setMenus(roleMenus); return userDto; } else { throw new ServiceException(Constants.CODE_600, "用户名或密码错误"); //自定义异常 } } // List list = list(queryWrapper); // return list.size()!=0 ; // } @Override public User register(UserDto userDto) { User one = getUserInfo(userDto); if (one == null) { one = new User(); BeanUtil.copyProperties(userDto, one, true); save(one); } else { throw new ServiceException(Constants.CODE_600, "用户已存在"); } return one; } @Override public Page findPage(IPage page, String username, String email, String address) { return userMapper.findPage(page, username, email, address); } @Override public void updatePassword(UserPasswordDTO userPasswordDTO) { int update = userMapper.updatePassword(userPasswordDTO); if (update < 1) { throw new ServiceException(Constants.CODE_600, "密码错误"); } return; } private User getUserInfo(UserDto userDto) { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("username", userDto.getUsername()); queryWrapper.eq("password", userDto.getPassword()); User one; try { one = getOne(queryWrapper); } catch (Exception e) { throw new ServiceException(Constants.CODE_500, "系统异常"); //自定义异常 } return one; } /** * 当前角色的菜单列表 * * @param flag 角色标签 * @return */ private List getRoleMenus(String flag) { Integer roleId = roleMapper.selectByFlag(flag); //当前角色的所有菜单 List menuIds = roleMenuMapper.selectByRoleId(roleId); //筛选完成之后的list List roleMenus = new ArrayList<>(); // 查询所有菜单 List menus = iMenuService.findMenus(""); //筛选当前用户菜单 for (Menu menu : menus) { if (menuIds.contains(menu.getId())) { roleMenus.add(menu); } List children = menu.getChildren(); //移除children里面不在menuIds集合中的元素 children.removeIf(child -> !menuIds.contains(child.getId())); } ; return roleMenus; } }

 4、mapper.xml




    
        
        
        
        
        
        
        
        
        
            
            
            
        
        
            
            
        
    
    


5、controller

package com.example.demo.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Constants;
import com.example.demo.common.Result;
import com.example.demo.dto.UserDto;
import com.example.demo.dto.UserPasswordDTO;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.IUserService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;


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

//
//    @Autowired
//    private UserMapper userMapper;


    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto){
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        if (StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        return Result.success(userService.login(userDto));
    }

    @GetMapping
    public Result findAll(){
        return Result.success(userService.list());
    }

    @GetMapping("/role/{role}")
    public Result findUserByRole(@PathVariable String role){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("role",role);
        return Result.success(userService.list(queryWrapper));
    }

//    @GetMapping("/page")
//    public Map findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam String username){
//        pageNum = (pageNum -1)*pageSize;
//        Integer total = userMapper.selectTotal(username);
//        username = '%'+username+'%';
//        List data =userMapper.selectPage(pageNum,pageSize,username);
//        Map  res = new HashMap<>();
//        res.put("data",data);
//        res.put("total",total);
//        return res;
//    }

//    @PostMapping
//    public Integer save(@RequestBody User user) {
//        return userService.save(user);
//    }
    @PostMapping("/register")
    public Result register(@RequestBody UserDto userDto) {
        String username = userDto.getUsername();
        String password = userDto.getPassword();

        if (StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }

        return Result.success(userService.register(userDto));
    }


    @GetMapping("/username/{username}")
    public Result findOne(@PathVariable String username){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return Result.success(userService.getOne(queryWrapper));
    }
    @PostMapping
    public Result save(@RequestBody User user) {
        String username = user.getUsername();
        if (StrUtil.isBlank(username)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        if (user.getId()!=null){
            user.setPassword(null);
        }else {
            user.setNickname(user.getUsername());
            if (user.getPassword()==null){
                user.setPassword("123");
            }
        }
        return Result.success(userService.saveOrUpdate(user));
    }

    @PostMapping("/password")
    public Result password(@RequestBody UserPasswordDTO userPasswordDTO) {
        userService.updatePassword(userPasswordDTO);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
//        return userMapper.deleteById(id);
        return Result.success(userService.removeById(id));
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List ids){
        return Result.success(userService.removeBatchByIds(ids));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,
                                @RequestParam String username,@RequestParam String address,@RequestParam String email){
        IPage page = new Page<>(pageNum,pageSize);
//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        if (!"".equals(username)){
//            queryWrapper.like("username",username);
//        }
//        if (!"".equals(address)) {
//            queryWrapper.like("address",address);
//        }
//        if (!"".equals(email)) {
//            queryWrapper.like("email",email);
//        }
//        queryWrapper.orderByDesc("create_time");
        return Result.success(userService.findPage(page,username,email,address));
    }
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        List list = userService.list();
        //通过工具类创建writer,写出到磁盘路径
        //ExportWriter writer = ExcelUtil.getWriter(filesuploadPath + "/用户信息.xlsx")
        //在内存操作,写出到浏览器
        // 通过工具类创建writer,默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        //自定义标题别名
//        writer.addHeaderAlias("username","用户名");
//        writer.addHeaderAlias("password","密码");
//        writer.addHeaderAlias("nickname","昵称");
//        writer.addHeaderAlias("email","邮箱");
//        writer.addHeaderAlias("phone","电话");
//        writer.addHeaderAlias("address","地址");
//        writer.addHeaderAlias("createTime","创建时间");
//        writer.addHeaderAlias("avatarUrl","头像");
        // 一次性写出内容,使用默认样式,强制输出标题
        writer.write(list, true);
        //设置浏览器响应格式
       //response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.preadsheetml;charset=utf-8");
       //fileName是弹出下载对话框的文件名,不能为中文,中文请自行编码
        String fileName = URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xls");
        ServletOutputStream out=response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer,释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
//       通过JavaBean的方式读取Excel内的对象,要求表头是英文,跟Javabean属性对应起来
//        List list = reader.readAll(User.class);
        //忽略表头的中文
        List>list = reader.read(1);
        List users = CollUtil.newArrayList();
        for (List row: list){
            User user = new User();
            user.setUsername(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setNickname(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setAddress(row.get(5).toString());
            user.setAvatarUrl(row.get(6).toString());
            users.add(user);
        }
        userService.saveBatch(users);
        return Result.success(true);
    }


}
 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(权限后台系统I,spring,boot,mybatis,java)