pom.xml
<?xml version="1.0" encoding="UTF-8"?>
4.0.0
<groupId>top.lrshuai.plus</groupId>
<artifactId>springboot-mybatisplus</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-mybatisplus</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
启动类
package top.lrshuai.plus.springbootmybatisplus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(“top.lrshuai.plus.springbootmybatisplus.*.mapper”)
public class SpringbootMybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisplusApplication.class, args);
}
}
代码生成工具
package top.lrshuai.plus.springbootmybatisplus;
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 CodeGenerator {
/**
*
* 读取控制台内容
*
*/
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.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException(“请输入正确的” + tip + “!”);
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("jobob");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Hongkong");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("top.lrshuai.plus.springbootmybatisplus");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass(“top.lrshuai.plus.springbootmybatisplus.common.BaseEntity”);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// strategy.setSuperControllerClass(“top.lrshuai.plus.springbootmybatisplus.common.BaseController”);
strategy.setInclude(scanner(“表名”));
strategy.setSuperEntityColumns(“id”);
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + “_”);
String isGeneratorPage = scanner(“是否生成页面:1 – 生成,0 – 不生成,这个模板是我以前用的,现在不适合,要用自己修改模板”);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
public void initMap() {}
};
List focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
public String outputFile(TableInfo tableInfo) {
return projectPath + “/src/main/resources/mapper/” + pc.getModuleName()+ “/” + tableInfo.getEntityName() + “Mapper” + StringPool.DOT_XML;
}
});
//项目相对路径
String projectRelative ="/src/main/java/top/lrshuai/timer/"+modelName;
if("1".equals(isGeneratorPage)){
strategy.setRestControllerStyle(false);
focList.add(new FileOutConfig(pageTemplatesPath) {
@Override
public String outputFile(TableInfo tableInfo) {
return projectPath + projectPageRelativePath +modelName+"/"+tableInfo.getEntityPath()+"_list.html";
}
});
focList.add(new FileOutConfig(controlTemplatesPath) {
@Override
public String outputFile(TableInfo tableInfo) {
return projectPath + projectRelative+"/controller/"+tableInfo.getControllerName()+StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig(serviceImplTemplatesPath) {
@Override
public String outputFile(TableInfo tableInfo) {
return projectPath +projectRelative+"/service/impl/"+tableInfo.getServiceImplName()+StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig(serviceTemplatesPath) {
@Override
public String outputFile(TableInfo tableInfo) {
return projectPath +projectRelative+"/service/"+tableInfo.getServiceName()+StringPool.DOT_JAVA;
}
});
}
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
resource/templetes/codetempleas
package com.lrs.core.
p
a
c
k
a
g
e
.
M
o
d
u
l
e
N
a
m
e
.
c
o
n
t
r
o
l
l
e
r
;
i
m
p
o
r
t
c
o
m
.
l
r
s
.
c
o
m
m
o
n
.
a
n
n
o
t
a
t
i
o
n
.
P
e
r
m
i
s
s
i
o
n
;
i
m
p
o
r
t
c
o
m
.
l
r
s
.
c
o
m
m
o
n
.
a
n
n
o
t
a
t
i
o
n
.
P
e
r
m
i
s
s
i
o
n
T
y
p
e
;
i
m
p
o
r
t
c
o
m
.
l
r
s
.
c
o
r
e
.
{package.ModuleName}.controller; import com.lrs.common.annotation.Permission; import com.lrs.common.annotation.PermissionType; import com.lrs.core.
package.ModuleName.controller;importcom.lrs.common.annotation.Permission;importcom.lrs.common.annotation.PermissionType;importcom.lrs.core.{package.ModuleName}.entity.
t
a
b
l
e
.
e
n
t
i
t
y
N
a
m
e
;
i
m
p
o
r
t
c
o
m
.
l
r
s
.
c
o
r
e
.
{table.entityName}; import com.lrs.core.
table.entityName;importcom.lrs.core.{package.ModuleName}.service.${table.serviceName};
import com.lrs.common.dto.PageDTO;
import com.lrs.core.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
-
-
${table.comment!} 前端控制器
-
@author rstyro
-
@since . n o w ? d a t e ∗ / @ C o n t r o l l e r @ R e q u e s t M a p p i n g ( " / {.now?date} */ @Controller @RequestMapping("/ .now?date∗/@Controller@RequestMapping("/{package.ModuleName}/${table.entityPath}")
public class ${table.controllerName} extends BaseController {private final static String qxurl = “ p a c k a g e . M o d u l e N a m e / {package.ModuleName}/ package.ModuleName/{table.entityPath}/list”;
@Autowired
private ${table.serviceName} ${table.entityPath}Service;@GetMapping("/list")
public String list(Model model, PageDTO dto) throws Exception {
System.out.println(dto);
model.addAttribute(“list”, t a b l e . e n t i t y P a t h S e r v i c e . g e t L i s t ( d t o ) ) ; r e t u r n " p a g e / {table.entityPath}Service.getList(dto)); return "page/ table.entityPathService.getList(dto));return"page/{package.ModuleName}/${table.entityPath}_list";
}@PostMapping(value="/add")
@ResponseBody
@Permission(url = qxurl,type = PermissionType.ADD)
public Object add(${table.entityName} item) throws Exception {
item.setId(null);
return ${table.entityPath}Service.add(item,this.getSession());
}@PostMapping(value="/edit")
@ResponseBody
@Permission(url = qxurl,type = PermissionType.EDIT)
public Object edit(${table.entityName} item) throws Exception {
return ${table.entityPath}Service.edit(item,this.getSession());
}@PostMapping(value="/del")
@ResponseBody
@Permission(url = qxurl,type = PermissionType.DEL)
public Object del(Long id) throws Exception {
return ${table.entityPath}Service.del(id,this.getSession());
}@GetMapping(value="/query")
@ResponseBody
@Permission(url = qxurl,type = PermissionType.QUERY)
public Object query(Long id) throws Exception {
return ${table.entityPath}Service.getDetail(id);
}
}
package ${package.Service};
import
p
a
c
k
a
g
e
.
E
n
t
i
t
y
.
{package.Entity}.
package.Entity.{entity};
import ${superServiceClassPackage};
import com.lrs.common.constant.ResponseModel;
import com.lrs.common.dto.PageDTO;
import javax.servlet.http.HttpSession;
/**
-
- ${table.comment!} 服务类
- @author rstyro
- @since ${.now?date}
*/
public interface ${table.serviceName} extends s u p e r S e r v i c e C l a s s < {superServiceClass}< superServiceClass<{entity}> {
public ResponseModel getList(PageDTO dto) throws Exception;
public ResponseModel add( e n t i t y i t e m , H t t p S e s s i o n s e s s i o n ) t h r o w s E x c e p t i o n ; p u b l i c R e s p o n s e M o d e l e d i t ( {entity} item, HttpSession session) throws Exception; public ResponseModel edit( entityitem,HttpSessionsession)throwsException;publicResponseModeledit({entity} item, HttpSession session) throws Exception;
public ResponseModel del(Long id, HttpSession session) throws Exception;
public ResponseModel getDetail(Long id) throws Exception;
}
package ${package.ServiceImpl};
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lrs.common.constant.ApiResultEnum;
import com.lrs.common.constant.ResponseModel;
import com.lrs.common.dto.PageDTO;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpSession;
import
p
a
c
k
a
g
e
.
E
n
t
i
t
y
.
{package.Entity}.
package.Entity.{entity};
import
p
a
c
k
a
g
e
.
M
a
p
p
e
r
.
{package.Mapper}.
package.Mapper.{table.mapperName};
import
p
a
c
k
a
g
e
.
S
e
r
v
i
c
e
.
{package.Service}.
package.Service.{table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
/**
-
-
${table.comment!} 服务实现类
-
@author ${author}
-
@since ${date}
*/
@Service
public class ${table.serviceImplName} extends s u p e r S e r v i c e I m p l C l a s s < {superServiceImplClass}< superServiceImplClass<{table.mapperName}, ${entity}> implements ${table.serviceName}{@Override
public ResponseModel getList(PageDTO dto) throws Exception {
IPage< e n t i t y > p a g e = n e w P a g e < > ( ) ; i f ( d t o . g e t P a g e N o ( ) ! = n u l l ) p a g e . s e t C u r r e n t ( d t o . g e t P a g e N o ( ) ) ; i f ( d t o . g e t P a g e S i z e ( ) ! = n u l l ) p a g e . s e t S i z e ( d t o . g e t P a g e S i z e ( ) ) ; Q u e r y W r a p p e r < {entity}> page = new Page<>(); if(dto.getPageNo() != null){ page.setCurrent(dto.getPageNo()); } if(dto.getPageSize() != null){ page.setSize(dto.getPageSize()); } QueryWrapper< entity>page=newPage<>();if(dto.getPageNo()!=null)page.setCurrent(dto.getPageNo());if(dto.getPageSize()!=null)page.setSize(dto.getPageSize());QueryWrapper<{entity}> queryWrapper = new QueryWrapper();
// if(!StringUtils.isEmpty(dto.getKeyword())){
// queryWrapper.lambda()
// .like( e n t i t y : : g e t A u t h e r , d t o . g e t K e y w o r d ( ) ) / / . l i k e ( {entity}::getAuther,dto.getKeyword()) // .like( entity::getAuther,dto.getKeyword())//.like({entity}::getContent,dto.getKeyword())
// .like(KaTeX parse error: Expected 'EOF', got '}' at position 50: …)); // }̲ IPage<{entity}> iPage = this.page(page, queryWrapper);
return new ResponseModel(ApiResultEnum.SUCCESS,iPage);
}@Override
public ResponseModel add(${entity} item, HttpSession session) throws Exception {
this.save(item);
return new ResponseModel(ApiResultEnum.SUCCESS,null);
}@Override
public ResponseModel edit(${entity} item, HttpSession session) throws Exception {
this.updateById(item);
return new ResponseModel(ApiResultEnum.SUCCESS,null);
}@Override
public ResponseModel del(Long id, HttpSession session) throws Exception {
this.removeById(id);
return new ResponseModel(ApiResultEnum.SUCCESS,null);
}@Override
public ResponseModel getDetail(Long id) throws Exception {
e n t i t y i t e m = t h i s . g e t O n e ( n e w Q u e r y W r a p p e r < {entity} item = this.getOne(new QueryWrapper< entityitem=this.getOne(newQueryWrapper<{entity}>().lambda().eq(${entity}::getId,id));
return new ResponseModel(ApiResultEnum.SUCCESS,item);
}
}
application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
password: root
username: root
driver-class-name: com.mysql.jdbc.Driver
mybatis-plus:
mapper-locations: classpath*:mapper/*.xml
打印sql 语句
logging:
level:
top.lrshuai.plus.springbootmybatisplus.test.mapper.ShipmentMapper: debug
logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?> %d{yyyy-MM-dd HH:mm:ss} [%level] - %m%n DEBUG ACCEPT ACCEPT log/mybatisplus_info.log %d{yyyy-MM-dd HH:mm:ss} [%class:%line] - %m%n INFO ACCEPT DENY log/mybatisplus_info.%d{yyyy-MM-dd}.log 30 log/mybatisplus_error.log %d{yyyy-MM-dd HH:mm:ss} [%class:%line] - %m%n ERROR ACCEPT DENY log/mybatisplus_error.%d{yyyy-MM-dd}.log 30config
package top.lrshuai.plus.springbootmybatisplus.test.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
@MapperScan(“top.lrshuai.plus.springbootmybatisplus.test.service..mapper”)
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
controller
package top.lrshuai.plus.springbootmybatisplus.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.lrshuai.plus.springbootmybatisplus.test.entity.dto.ListDTO;
import top.lrshuai.plus.springbootmybatisplus.test.entity.dto.TestDTO;
import top.lrshuai.plus.springbootmybatisplus.test.service.IShipmentService;
/**
-
-
前端控制器
-
@author jobob
-
@since 2018-11-07
*/
@RestController
@RequestMapping("/shipment")
public class ShipmentController {
@Autowired
private IShipmentService iShipmentService;@GetMapping("/test")
public Object test(TestDTO dto){
return iShipmentService.getList(dto);
}@GetMapping("/page")
public Object pageTest(ListDTO dto){
return iShipmentService.getListByPage(dto);
}
}
实体类
package top.lrshuai.plus.springbootmybatisplus.test.entity;
import java.io.Serializable;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
-
-
@author jobob
-
@since 2018-11-07
*/
@Data
@Accessors(chain = true)
public class Shipment {private static final long serialVersionUID = 1L;
/**
- 物流单号
*/
private String orderNumber;
/**
- 物流状态:1 – 已揽件,2 – 正在路上,3 — 已签收
*/
private Integer status;
/**
- 物流地址
*/
private String address;
/**
- 接收时间
*/
private LocalDateTime receiveDate;
/**
- 是否已删除
*/
private String isDel;
/**
- 创建时间
*/
private LocalDateTime createTime;
- 物流单号
}
@Data
public class TestDTO {
private String orderName;
}
@Data
public class ListDTO {
private int pageSize;
private int pageNo;
private Integer status;
}
servie
package top.lrshuai.plus.springbootmybatisplus.test.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import top.lrshuai.plus.springbootmybatisplus.test.entity.Shipment;
import com.baomidou.mybatisplus.extension.service.IService;
import top.lrshuai.plus.springbootmybatisplus.test.entity.dto.ListDTO;
import top.lrshuai.plus.springbootmybatisplus.test.entity.dto.TestDTO;
/**
-
-
服务类
-
@author jobob
-
@since 2018-11-07
*/
public interface IShipmentService extends IService {public Object getList(TestDTO dto);
public IPage getListByPage(ListDTO dto);
}
package top.lrshuai.plus.springbootmybatisplus.test.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import top.lrshuai.plus.springbootmybatisplus.test.entity.Shipment;
import top.lrshuai.plus.springbootmybatisplus.test.entity.dto.ListDTO;
import top.lrshuai.plus.springbootmybatisplus.test.entity.dto.TestDTO;
import top.lrshuai.plus.springbootmybatisplus.test.mapper.ShipmentMapper;
import top.lrshuai.plus.springbootmybatisplus.test.service.IShipmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
-
-
服务实现类
-
@author jobob
-
@since 2018-11-07
*/
@Service
public class ShipmentServiceImpl extends ServiceImpl<ShipmentMapper, Shipment> implements IShipmentService {@Autowired
private ShipmentMapper shipmentMapper;@Override
public Object getList(TestDTO dto) {
QueryWrapper queryWrapper = new QueryWrapper();
if(StringUtils.isNotEmpty(dto.getOrderName())){
queryWrapper.eq(“order_number”,dto.getOrderName());
}
return shipmentMapper.selectList(queryWrapper);
}@Override
public IPage getListByPage(ListDTO dto) {
// 不进行 count sql 优化,解决 MP 无法自动优化 SQL 问题,这时候你需要自己查询 count 部分
// page.setOptimizeCountSql(false);
// 当 total 为非 0 时(默认为 0),分页插件不会进行 count 查询
// 要点!! 分页返回的对象与传入的对象是同一个
Page page = new Page<>();
page.setSize(dto.getPageSize());
page.setPages(dto.getPageNo());
return shipmentMapper.getListByPage(page,dto.getStatus());
}
}
mapping接口
package top.lrshuai.plus.springbootmybatisplus.test.mapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
import top.lrshuai.plus.springbootmybatisplus.test.entity.Shipment;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
-
-
Mapper 接口
-
@author jobob
-
@since 2018-11-07
*/
@Component
public interface ShipmentMapper extends BaseMapper {IPage getListByPage(Page page, @Param(“status”) Integer status);
}