MybatisPlus搭建项目环境及分页插件
短信预约 -IT技能 免费直播动态提醒
一、搭建项目环境
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*.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;
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 + "/class="lazy" data-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 + "/class="lazy" data-src/main/resources/mappers/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
} else {
return projectPath + "/class="lazy" data-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*.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;
@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
class="lazy" data-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 {
//从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搭建项目内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341