MybatisPlus搭建項目環(huán)境及分頁插件
一、搭建項目環(huán)境
1.1 創(chuàng)建項目




1.2 配置環(huán)境
導入分頁依賴
<!--用于生存代碼-->
<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下創(chuàng)建項目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>
* 讀取控制臺內(nèi)容
* </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")指工作區(qū)間 如我們工作期間名是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.數(shù)據(jù)源配置
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<>();
// 自定義配置會被優(yōu)先輸出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸出文件名 , 如果你 Entity 設置了前后綴、此處注意 xml 的名稱會跟著發(fā)生變化!!
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();
// 表名生成策略(下劃線轉(zhuǎn)駝峰命名)
strategy.setNaming(NamingStrategy.underline_to_camel);
// 列名生成策略(下劃線轉(zhuǎn)駝峰命名)
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實現(xiàn)類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);
//表名前綴(可變參數(shù)):“t_”或”“t_模塊名”,例如:t_user或t_sys_user
strategy.setTablePrefix("t_", "t_sys_");
//strategy.setTablePrefix(scanner("請輸入表前綴"));
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 執(zhí)行
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.model1.4 編寫controller層
因為自動生成代碼注解是==@RestController==,等價于@Controller + @ResponseBody。但是@ResponseBody表示方法的返回值直接以指定的格式寫入Http response body中,而不是解析為跳轉(zhuǎn)路徑。所以我們要把注解改為==@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代表數(shù)據(jù)庫自段 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
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 創(chuàng)建插件配置類
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的過濾器鏈中添加分頁攔截器,需要設置數(shù)據(jù)庫類型(主要用于分頁方言)
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,下面也要改。但是還是推薦官網(wǎng)上面的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);
}
總結(jié)
到此這篇關于MybatisPlus搭建項目環(huán)境及分頁插件的文章就介紹到這了,更多相關MybatisPlus搭建項目內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javaweb啟動時啟動socket服務端代碼實現(xiàn)
這篇文章主要介紹了javaweb啟動時啟動socket服務端代碼實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11
Spring?Boot實現(xiàn)文件上傳的兩種方式總結(jié)
應用開發(fā)過程中,文件上傳是一個基礎的擴展功能,它的目的就是讓大家共享我們上傳的文件資源,下面這篇文章主要給大家總結(jié)介紹了關于Spring?Boot實現(xiàn)文件上傳的兩種方式,需要的朋友可以參考下2023-05-05
詳解spring cloud hystrix請求緩存(request cache)
這篇文章主要介紹了詳解spring cloud hystrix請求緩存(request cache),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
Java報錯:FileNotFoundException的解決方案
在Java編程中,FileNotFoundException 是一種常見的受檢異常,通常發(fā)生在試圖打開一個不存在的文件或文件路徑錯誤時,本文將詳細探討FileNotFoundException的成因、解決方案以及預防措施,幫助開發(fā)者理解和避免此類問題,需要的朋友可以參考下2024-06-06
Java使用Spring發(fā)送郵件的實現(xiàn)代碼
本篇文章主要介紹了使用Spring發(fā)送郵件的實現(xiàn)代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03
使用mybatis-plus-generator進行代碼自動生成的方法
這篇文章主要介紹了使用mybatis-plus-generator進行代碼自動生成的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06

