MybatisPlus搭建项目环境及分页插件

一、搭建项目环境

1.1 创建项目

MybatisPlus搭建项目环境及分页插件_第1张图片

MybatisPlus搭建项目环境及分页插件_第2张图片

MybatisPlus搭建项目环境及分页插件_第3张图片

MybatisPlus搭建项目环境及分页插件_第4张图片

1.2 配置环境

导入分页依赖

 
        
            com.baomidou
            mybatis-plus-generator
            3.4.1
        
        
            org.freemarker
            freemarker
            2.3.31
        

修改MySQL的版本

MybatisPlus搭建项目环境及分页插件_第5张图片

1.1.1 自动生成代码

首先在resources下创建项目mappers

MybatisPlus搭建项目环境及分页插件_第6张图片

修改application.yml

MybatisPlus搭建项目环境及分页插件_第7张图片

server:
    port: 8080
spring:
    application:
        name: springbootxm
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        name: defaultDataSource
        password: 123456
        url: jdbc:mysql://localhost:3306/y101?useUnicode=true&characterEncoding=UTF-8
        username: root
    freemarker:
        cache: false
        charset: utf-8
        expose-request-attributes: true
        expose-session-attributes: true
        suffix: .ftl
        template-loader-path: classpath:/templates/
#    resources:
#        static-locations: classpath:/static/# 应用服务 WEB 访问端口
    mvc:
        static-path-pattern: /static/**
#打印SQL语句
logging:
    level:
        com.xlb.springbootassets: debug
#配置映射
mybatis-plus:
    mapper-locations: classpath:mappers/**/*.xml
    type-aliases-package: com.xlb.springbootxm.bj.model

引入生成代码类

MPGenerator

MybatisPlus搭建项目环境及分页插件_第8张图片

MybatisPlus搭建项目环境及分页插件_第9张图片

MybatisPlus搭建项目环境及分页插件_第10张图片

package com.xlb.springbootxm.mp;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * mybatis-plus代码生成
 */
public class MPGenerator {

    /**
     * 

* 读取控制台内容 *

*/ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输入" + tip); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotBlank(ipt)) { if ("quit".equals(ipt)) return ""; return ipt; } } throw new MybatisPlusException("请输入正确的" + tip + "!"); } public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 1.全局配置 GlobalConfig gc = new GlobalConfig(); //System.getProperty("user.dir")指工作区间 如我们工作期间名是iderr String projectPath = System.getProperty("user.dir") + "/springbootxm"; System.out.println(projectPath); gc.setOutputDir(projectPath + "/src/main/java"); gc.setOpen(false); gc.setBaseResultMap(true);//生成BaseResultMap gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(true);// XML columList //gc.setSwagger2(true); //实体属性 Swagger2 注解 gc.setAuthor("小谢"); // 自定义文件命名,注意 %s 会自动填充表实体属性! gc.setMapperName("%sMapper"); gc.setXmlName("%sMapper"); gc.setServiceName("%sService"); gc.setServiceImplName("%sServiceImpl"); gc.setControllerName("%sController"); gc.setIdType(IdType.AUTO); mpg.setGlobalConfig(gc); // 2.数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setUrl("jdbc:mysql://localhost:3306/y101?useUnicode=true&characterEncoding=UTF-8"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); mpg.setDataSource(dsc); // 3.包配置 PackageConfig pc = new PackageConfig(); String moduleName = scanner("模块名(quit退出,表示没有模块名)"); if (StringUtils.isNotBlank(moduleName)) { pc.setModuleName(moduleName); } //设置父包 pc.setParent("com.xlb.springbootxm") .setMapper("mapper") .setService("service") .setController("controller") .setEntity("model"); mpg.setPackageInfo(pc); // 4.自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 自定义输出配置 List focList = new ArrayList<>(); // 自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! if (StringUtils.isNotBlank(pc.getModuleName())) { return projectPath + "/src/main/resources/mappers/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } else { return projectPath + "/src/main/resources/mappers/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 5.策略配置 StrategyConfig strategy = new StrategyConfig(); // 表名生成策略(下划线转驼峰命名) strategy.setNaming(NamingStrategy.underline_to_camel); // 列名生成策略(下划线转驼峰命名) strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 是否启动Lombok配置 strategy.setEntityLombokModel(true); // 是否启动REST风格配置 strategy.setRestControllerStyle(true); // 自定义实体父类strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model"); // 自定义service父接口strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService"); // 自定义service实现类strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl"); // 自定义mapper接口strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper"); strategy.setSuperEntityColumns("id"); // 写于父类中的公共字段plus strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); strategy.setControllerMappingHyphenStyle(true); //表名前缀(可变参数):“t_”或”“t_模块名”,例如:t_user或t_sys_user strategy.setTablePrefix("t_", "t_sys_"); //strategy.setTablePrefix(scanner("请输入表前缀")); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 执行 mpg.execute(); } }

运行生成代码

MybatisPlus搭建项目环境及分页插件_第11张图片

1.1.2 配置SpringbootassetsApplication

SpringbootassetsApplication

MybatisPlus搭建项目环境及分页插件_第12张图片

package com.xlb.springbootxm;

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


//完成对mapper接口的扫描
@MapperScan("com.xlb.springbootxm.bj.mapper")
//开启事务管理
@EnableTransactionManagement
@SpringBootApplication
public class SpringbootxmApplication {

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

1.3 配置application.yml

MybatisPlus搭建项目环境及分页插件_第13张图片

server:
    port: 8080
spring:
    application:
        name: springbootxm
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        name: defaultDataSource
        password: 123456
        url: jdbc:mysql://localhost:3306/y101?useUnicode=true&characterEncoding=UTF-8
        username: root
    freemarker:
        cache: false
        charset: utf-8
        expose-request-attributes: true
        expose-session-attributes: true
        suffix: .ftl
#        template-loader-path: classpath:/templates/
#    resources:
#        static-locations: classpath:/static/# 应用服务 WEB 访问端口
    mvc:
        static-path-pattern: /static/**
#打印SQL语句
logging:
    level:
        com.xlb.springbootassets: debug
#配置映射
mybatis-plus:
    mapper-locations: classpath:mappers/**/*.xml
    type-aliases-package: com.xlb.springbootxm.bj.model

1.4 编写controller层

因为自动生成代码注解是==@RestController==,等价于@Controller + @ResponseBody。但是@ResponseBody表示方法的返回值直接以指定的格式写入Http response body中,而不是解析为跳转路径。所以我们要把注解改为==@Controller==

StrutsClassController

package com.xlb.springbootmp.book.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xlb.springbootmp.book.model.MvcBook;
import com.xlb.springbootmp.book.service.MvcBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 

* 前端控制器 *

* * @author lky * @since 2022-11-01 */ @Controller @RequestMapping("/book") public class MvcBookController { @Autowired private MvcBookService mvcBookService; //查询单个 @GetMapping("/list") public List list(){ return mvcBookService.list(); } //按条件查询 @GetMapping("/listByCondition") public List listByCondition(MvcBook mvcBook){ QueryWrapper qw = new QueryWrapper(); //key代表数据库自段 value代表查询的值 like代表模糊查询 qw.like("bname", mvcBook.getBname()); return mvcBookService.list(qw); } //查询单个 @GetMapping("/get") public MvcBook get(MvcBook mvcBook){ return mvcBookService.getById(mvcBook.getBid()); } //增加 @PutMapping("/add") public boolean add(MvcBook mvcBook){ boolean save = mvcBookService.save(mvcBook); return save; } //删除 @DeleteMapping("/del") public boolean del(MvcBook mvcBook){ return mvcBookService.removeById(mvcBook.getBid()); } //修改 @PostMapping("/edit") public boolean edit(MvcBook mvcBook){ return mvcBookService.saveOrUpdate(mvcBook); } // 连表查询 @GetMapping("/userRole") public List userRole(String uname){ Map map = new HashMap(); map.put("username",uname); List maps = mvcBookService.queryUserRole(map); return maps; } }

1.5 编写前台代码

目录

MybatisPlus搭建项目环境及分页插件_第14张图片

headd.ftl

<#--局部变量-->
<#assign ctx>
    ${springMacroRequestContext.contextPath}


<#--全局变量-->
<#global ctx2>
    ${springMacroRequestContext.contextPath}

clzEdit.ftl




    
    博客的编辑界面


<#include '/headd.ftl' />
<#if b??>
   <#-- 修改-->
    
cname: cteacher: pic:
<#else> <#-- 新增 -->
cname: cteacher: pic:

clzList.ftl




    
    
    
    博客列表
    


<#include '/headd.ftl' />
<#-- 查询条件框  -->
新增
<#list lst as b>
ID 班级名称 指导老师 班级相册 操作
${b.cid !} ${b.cname !} ${b.cteacher !} ${b.pic !} 修改 删除

1.6 测试

1.6.1 查询

MybatisPlus搭建项目环境及分页插件_第15张图片

1.6.2 新增

MybatisPlus搭建项目环境及分页插件_第16张图片

MybatisPlus搭建项目环境及分页插件_第17张图片

1.6.3 修改

MybatisPlus搭建项目环境及分页插件_第18张图片

MybatisPlus搭建项目环境及分页插件_第19张图片

MybatisPlus搭建项目环境及分页插件_第20张图片

1.6.4 删除

MybatisPlus搭建项目环境及分页插件_第21张图片

MybatisPlus搭建项目环境及分页插件_第22张图片

二、MyBatis-Plus分页插件

2.1 创建插件配置类

MybatisPlusConfig

package com.xlb.springbootassets.bj.config;

import com.baomidou.mybatisplus.annotation.DbType;
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 {

    /**
     * 分页插件配置
     *
     * @return
     */
    //从MyBatis-Plus 3.4.0开始,不再使用旧版本的PaginationInterceptor ,而是使用MybatisPlusInterceptor。
    //使用分页插件需要配置MybatisPlusInterceptor,将分页拦截器添加进来:
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 向MyBatis-Plus的过滤器链中添加分页拦截器,需要设置数据库类型(主要用于分页方言)
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

2.2 编写SQL

StrutsClassMapper.xml

2.3 mapper层

//亲测这里最前面使用Ipage和Page是一样的,如果这里使用的是Page,下面也要改。但是还是推荐官网上面的Ipage,不改最好。
    IPage selectPageVo(Page page,String clazz);

2.4 service层

StrutsClassService

//分页方法
    IPage selectPageVo(Page page,String clazz);

StrutsClassServiceImpl

@Override
    public IPage selectPageVo(Page page,String clazz) {
        return strutsClassMapper.selectPageVo(page,clazz);
    }

2.5 controller 层

//分页方法
    @RequestMapping("/pagelist")
    public IPage pagelist(@RequestBody String clazz){
        Page page1 = new Page<>();
        Page page = new Page<>(1,10);
        return strutsClassService.selectPageVo(page,clazz);
    }

总结

到此这篇关于MybatisPlus搭建项目环境及分页插件的文章就介绍到这了,更多相关MybatisPlus搭建项目内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(MybatisPlus搭建项目环境及分页插件)