首頁 > 軟體

MybatisPlus搭建專案環境及分頁外掛

2022-11-07 14:00:43

一、搭建專案環境

1.1 建立專案

1.2 設定環境

匯入分頁依賴

 <!--用於生存程式碼-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
        </dependency>

修改MySQL的版本

1.1.1 自動生成程式碼

首先在resources下建立專案mappers

修改application.yml

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

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 {

    /**
     * <p>
     * 讀取控制檯內容
     * </p>
     */
    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<FileOutConfig> 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();
    }
}

執行生成程式碼

1.1.2 設定SpringbootassetsApplication

SpringbootassetsApplication

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

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;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lky
 * @since 2022-11-01
 */
@Controller
@RequestMapping("/book")
public class MvcBookController {
    @Autowired
    private MvcBookService mvcBookService;

    //查詢單個
    @GetMapping("/list")
    public List<MvcBook> list(){
        return mvcBookService.list();
    }

    //按條件查詢
    @GetMapping("/listByCondition")
    public List<MvcBook> 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<Map> userRole(String uname){
        Map map = new HashMap();
        map.put("username",uname);
        List<Map> maps = mvcBookService.queryUserRole(map);
        return maps;
    }
}

1.5 編寫前臺程式碼

目錄

headd.ftl

<#--區域性變數-->
<#assign ctx>
    ${springMacroRequestContext.contextPath}
</#assign>

<#--全域性變數-->
<#global ctx2>
    ${springMacroRequestContext.contextPath}
</#global>

clzEdit.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>部落格的編輯介面</title>
</head>
<body>
<#include '/headd.ftl' />
<#if b??>
   <#-- 修改-->
    <form action="${ctx }/clz/edit">
       
        cname:<input type="text" name="cname" value="${b.cname !}">
        cteacher:<input type="text" name="cteacher" value="${b.cteacher !}">
        pic:<input type="text" name="pic" value="${b.pic !}">
        <input type="submit">
    </form>
    <#else>
        <#-- 新增 -->
        <form action="${ctx }/clz/add" method="post">
            
            cname:<input type="text" name="cname" value="">
            cteacher:<input type="text" name="cteacher" value="">
            pic:<input type="text" name="pic" value="">
            <input type="submit">
        </form>
    </#if>

</body>
</html>

clzList.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link
            href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
            rel="stylesheet">
    <script
            src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
    <title>部落格列表</title>
    <style type="text/css">
        .page-item input {
            padding: 0;
            width: 40px;
            height: 100%;
            text-align: center;
            margin: 0 6px;
        }

        .page-item input, .page-item b {
            line-height: 38px;
            float: left;
            font-weight: 400;
        }

        .page-item.go-input {
            margin: 0 10px;
        }
    </style>
</head>
<body>
<#include '/headd.ftl' />
<#-- 查詢條件框  -->
<form class="form-inline"
      action="${ctx}/clz/list" method="post">
    <div class="form-group mb-2">
        <input type="text" class="form-control-plaintext" name="cname"
               placeholder="請輸入班級名稱">
    </div>
    <button type="submit" class="btn btn-primary mb-2">查詢</button>
    <a class="btn btn-primary mb-2" href="${ctx}/clz/toEdit">新增</a>
</form>
<table class="table table-striped bg-success">
    <thead>
    <tr>
        <th scope="col">ID</th>
        <th scope="col">班級名稱</th>
        <th scope="col">指導老師</th>
        <th scope="col">班級相簿</th>
        <th scope="col">操作</th>
    </tr>
    </thead>
    <tbody>
    <#list lst as b>
        <tr>
            <td>${b.cid !}</td>
            <td>${b.cname !}</td>
            <td>${b.cteacher !}</td>
            <td>${b.pic !}</td>
            <td>
                <a href="${ctx }/clz/toEdit?cid=${b.cid}">修改</a>
                <a href="${ctx }/clz/del?cid=${b.cid}">刪除</a>
            </td>
        </tr>
    </#list>
    </tbody>
</table>
</body>
</html>

1.6 測試

1.6.1 查詢

1.6.2 新增

1.6.3 修改

1.6.4 刪除

二、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

<select id="selectPageVo" resultType="com.xlb.springbootassets.bj.model.StrutsClass">
        select cid,cname,cteacher,pic FROM t_struts_class WHERE cname=#{cname}
    </select>

2.3 mapper層

//親測這裡最前面使用Ipage和Page是一樣的,如果這裡使用的是Page,下面也要改。但是還是推薦官網上面的Ipage,不改最好。
    IPage<StrutsClass> selectPageVo(Page<StrutsClass> page,String clazz);

2.4 service層

StrutsClassService

//分頁方法
    IPage<StrutsClass> selectPageVo(Page<StrutsClass> page,String clazz);

StrutsClassServiceImpl

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

2.5 controller 層

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

總結

到此這篇關於MybatisPlus搭建專案環境及分頁外掛的文章就介紹到這了,更多相關MybatisPlus搭建專案內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com