Mybatis-Plus前后端分离多表联查模糊查询分页

数据准备

数据库配置:

/*
 Navicat Premium Data Transfer

 Source Server         : localhost_3306
 Source Server Type    : MySQL
 Source Server Version : 80100 (8.1.0)
 Source Host           : localhost:3306
 Source Schema         : test01

 Target Server Type    : MySQL
 Target Server Version : 80100 (8.1.0)
 File Encoding         : 65001

 Date: 07/11/2023 16:23:00
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for dept
-- ----------------------------
DROP TABLE IF EXISTS `dept`;
CREATE TABLE `dept`  (
  `deptno` int NOT NULL AUTO_INCREMENT,
  `dname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  PRIMARY KEY (`deptno`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of dept
-- ----------------------------
INSERT INTO `dept` VALUES (1, '管理');
INSERT INTO `dept` VALUES (2, '人事');
INSERT INTO `dept` VALUES (3, '财务');
INSERT INTO `dept` VALUES (4, '销售');

-- ----------------------------
-- Table structure for emp
-- ----------------------------
DROP TABLE IF EXISTS `emp`;
CREATE TABLE `emp`  (
  `id` int NOT NULL AUTO_INCREMENT COMMENT '员工ID',
  `ename` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '员工姓名',
  `birthday` date NULL DEFAULT NULL COMMENT '出生日期',
  `hobby` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '爱好',
  `sex` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '性别',
  `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '住址',
  `deptno` int NULL DEFAULT NULL COMMENT '部部门id',
  `delid` int NULL DEFAULT 0 COMMENT '0正常1删除',
  PRIMARY KEY (`id`, `ename`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of emp
-- ----------------------------
INSERT INTO `emp` VALUES (1, '张三', '2000-08-06', '音乐,篮球', '男', '河南省, 郑州市', 1, 0);
INSERT INTO `emp` VALUES (2, '李四', '2001-07-06', '吃饭,睡觉', '男', '河南省, 郑州市', 2, 0);
INSERT INTO `emp` VALUES (3, '王五', '2002-09-20', NULL, '男', '河南省, 郑州市', 3, 0);
INSERT INTO `emp` VALUES (4, '老六', '2002-08-16', '睡觉', '男', '河南省, 郑州市', 4, 0);
INSERT INTO `emp` VALUES (5, '老七', '2001-06-15', NULL, '男', '河南省, 郑州市', 1, 0);
INSERT INTO `emp` VALUES (6, '梨树华', '1999-07-08', '睡觉,音乐,吃饭', '男', '河南省,洛阳市,涧西区', 4, 0);
INSERT INTO `emp` VALUES (7, '林森', '2002-03-06', '睡觉,音乐', '男', '河南省,洛阳市,涧西区', 3, 0);
INSERT INTO `emp` VALUES (8, '小娜', '2002-03-01', '音乐,睡觉', '女', '河北省,秦皇岛市,海港区', 2, 0);

SET FOREIGN_KEY_CHECKS = 1;

前端vue+elementui+router+axios

Mybatis-Plus前后端分离多表联查模糊查询分页_第1张图片

基于vue2 路由的版本不要太高了 < @4

main.js 文件(跨域配置,响应拦截器)

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from "axios";
// 引入全局组件
import pageCom from '@/components/PageComponent.vue'
Vue.component("myPage",pageCom)

Vue.use(ElementUI);

const instance = axios.create({
  baseURL: 'http://localhost:8080/'
})
instance.interceptors.response.use(responce => {
  if (responce.data.code == 500) {
    router.push({path: "/err404"});
  }
  return responce.data.t;
}, error => {
  return Promise.reject(error)
})
Vue.prototype.$axios = instance


Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

后端配置mybatis-plus+springboot

跨域

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CrossConfig {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
//        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*"); // 允许所有的头
        corsConfiguration.addAllowedOrigin("*"); // 允许所有的请求源
        corsConfiguration.addAllowedMethod("*");  // 所欲的方法   get post delete put
        source.registerCorsConfiguration("/**", corsConfiguration); // 所有的路径都允许跨域
        return new CorsFilter(source);
    }

}

分页

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
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(DbType.MYSQL));
        return interceptor;
    }
}

swagger(可用可不用,api文档)

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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.web.controller"))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("服务:发布为daocke镜像,权限管理,用户管理,页面管理,日志 后台 APIs")
                .description("服务:发布为daocke镜像,权限管理,用户管理,页面管理,日志 后台")
                .termsOfServiceUrl("https://www.baidu.com") //代码的路径
                .contact(new Contact("hp",null,null))
                .version("1.0")
                .build();
    }
}

application.yml(全局配置文件)

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///test01?serverTimezone=UTC
    password: root
    username: root
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    serialization:
      write-date-keys-as-timestamps: false
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath:/mapper/*.xml
  global-config:
    db-config:
      logic-not-delete-value: 1
      logic-delete-value: 0
  type-aliases-package: com.web.entity

pom.xml (项目依赖)



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.7.17
         
    
    com.web
    web
    0.0.1-SNAPSHOT
    web
    web
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            com.mysql
            mysql-connector-j
            runtime
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.5.3
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.5.3
        
        
            org.apache.velocity
            velocity-engine-core
            2.3
        

        
            org.freemarker
            freemarker
        
        
            com.github.pagehelper
            pagehelper-spring-boot-starter
            1.4.6
        
        
            io.springfox
            springfox-swagger2
            3.0.0
        





        
            com.github.xiaoymin
            swagger-bootstrap-ui
            1.9.6
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    


代码书写

后端

创建基本架构

Mybatis-Plus前后端分离多表联查模糊查询分页_第2张图片

ResuUtil 类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResuUtil {
    Integer code;
    String msg;
    T t;
    public static  ResuUtil success (T t) {
        return new ResuUtil<>(200,"成功",t);
    }
    public static  ResuUtil fail (T t) {
        return new ResuUtil<>(500,"失败",t);
    }
}
pageUtil类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageUtil {
    private Integer pageIndex = 1;
    private Integer pageSize = 3;
}
MP (mybatis-plus 官网代码快速生成)
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.fill.Column;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MP {
    public static void main(String[] args) {
        FastAutoGenerator.create("jdbc:mysql:///test01","root","root")
                // 全局配置
                .globalConfig((scanner, builder) -> builder
                        .author("hp")
                        .outputDir("D:\\Idea-web-vue2\\v2demo03\\web\\src\\main\\java\\")
                )
                // 包配置
                .packageConfig(
                        (scanner, builder) ->
                                builder
                                        .parent("com.web")
                                        .pathInfo(Collections.singletonMap(OutputFile.xml, "D:\\Idea-web-vue2\\v2demo03\\web\\src\\main\\resources\\mapper")))
                // 策略配置
                .strategyConfig((scanner, builder) -> builder.addInclude(getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
                        .controllerBuilder().enableRestStyle().enableHyphenStyle()
                        .entityBuilder().enableLombok().addTableFills(
                                new Column("create_time", FieldFill.INSERT)
                        ).build())
                /*
                    模板引擎配置,默认 Velocity 可选模板引擎 Beetl 或 Freemarker
                   .templateEngine(new BeetlTemplateEngine())
                   .templateEngine(new FreemarkerTemplateEngine())
                 */
                .execute();


// 处理 all 情况

    }

    protected static List getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }
}
EmpMapper
public interface EmpMapper extends BaseMapper {
    Page getAllsPage(Page page, Emp emp, Dept dept);

    @Select("select * from emp where ename = #{ename}")
    Integer getListByName(String ename);
    @Select("update emp set delid=#{delid} where id=#{id} ")
    Integer upDid(Integer delid,Integer id);
}
EmpMapper.xml



    
        
        
            
        
    
    

IEmpService
public interface IEmpService extends IService {
    Page getAllPage(PageUtil pageUtil, Emp emp, Dept dept);

    Integer getListByName(String ename);
    Integer upDid(Integer delid,Integer id);
}
EmpServiceImpl
@Service
public class EmpServiceImpl extends ServiceImpl implements IEmpService {
    @Resource
    EmpMapper em;

    @Override
    public Page getAllPage(PageUtil pageUtil, Emp emp, Dept dept) {
        Page page = new Page(pageUtil.getPageIndex(),pageUtil.getPageSize());
        return em.getAllsPage(page, emp, dept);
    }

    @Override
    public Integer getListByName(String ename) {
        return em.getListByName(ename);
    }

    @Override
    public Integer upDid(Integer delid, Integer id) {
        return em.upDid(delid, id);
    }
}
EmpController
@RestController
@RequestMapping("/emp")
@Api(tags = "员工信息")
public class EmpController {
    @Resource
    IEmpService ies;

    @GetMapping("/page")
    @ApiOperation("查询员工全部信息并分页")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "页数页码",name = "pageUtil",paramType = "query"),
            @ApiImplicitParam(value = "员工姓名模糊查对象",name = "emp",paramType = "query"),
            @ApiImplicitParam(value = "部门名称模糊查对象",name = "dept",paramType = "query")
    })
    public ResuUtil getAllPage(PageUtil pageUtil, Emp emp, Dept dept) {
        System.out.println(emp);
        System.out.println(dept);
        return ResuUtil.success(ies.getAllPage(pageUtil,emp,dept));
    }
    @PostMapping("addOne")
    @ApiOperation("添加员工")
    @ApiImplicitParam(value = "员工信息",name = "emp",paramType = "body")
    public ResuUtil addEmp(@RequestBody Emp emp) {return ResuUtil.success(ies.saveOrUpdate(emp));}
    @GetMapping("/ename")
    @ApiOperation("判断重名")
    @ApiImplicitParam(value = "员工姓名",name = "ename",paramType = "query")
    public ResuUtil enameXX(String ename) {
        return ResuUtil.success(ies.getListByName(ename));
    }
    @PutMapping("/delid/{delid}/{id}")
    @ApiOperation("逻辑删除")
    public ResuUtil upDid(@PathVariable Integer delid,@PathVariable Integer id) {
        return ResuUtil.success(ies.upDid(delid, id));
    }
}
DeptController
@RestController
@RequestMapping("/dept")
@Api(tags = "部门信息")
public class DeptController {
    @Resource
    IDeptService ids;
    @GetMapping()
    @ApiOperation("部门数据")
    public ResuUtil getAll() {return ResuUtil.success(ids.list());}

}

前端

分页组件






HomeView






你可能感兴趣的:(JAVA,web开发,mybatis,java,spring)