创建一个空的Maven项目就行了
将项目结构整成这个样子【这个我也就不写教程了,反正不管怎么整,要整成这个结构】
pom文件里面加上基础依赖
<parent>
<artifactId>spring-boot-starter-parentartifactId>
<groupId>org.springframework.bootgroupId>
<version>2.4.12version>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
<version>2.4.12version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
dependencies>
启动类的编写XXXApplication【类名是自定义的】
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MybatisplusApplication
{
public static void main(String[] args)
{
SpringApplication.run(MybatisplusApplication.class,args);
}
}
创建表 + 插入一些数据【如果没有数据库,还需要创建数据库】
application.yml基础配置
# 如果密码为纯数据 如:123456,项目可能读取不到这个数字密码,最好用''括起来 如:'123456'
# mysql://127.0.0.1:3306/数据库名称?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/数据库名字?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
username: 你自己的用户名awa
password: 你自己的密码awa
mvc:
format:
date: yyyy-MM-dd
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
# 设置spring boot项目的端口,也可以不设,不设默认的是8080
server:
servlet:
encoding:
charset: utf-8
port: 8888
mybatis:
mapper-locations: classpath:/mybatis/mapper/*.xml, classpath:/mybatis/mapper/extend/*.xml
# 这个可以查看数据库SQL语句,方便调试
logging:
level:
com.example.mybatisplus.mapper: debug
file-upload-path: ./file
IDEA中连接数据库【这个就不用写教程了】
Mybatis-plus官方文档
注意!!!
使用这个方法逆向生成代码要求 所有表的主键为 id,类型为 Long Int,也就是 Big Int
使用这个方法逆向生成代码要求 所有表的主键为 id,类型为 Long Int,也就是 Big Int
使用这个方法逆向生成代码要求 所有表的主键为 id,类型为 Long Int,也就是 Big Int
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class CodeGenerator {
/**
* Project package
*/
private static String projectPackage;
/**
* controller package
*/
private static String controllerPackage;
/**
* entity package
*/
private static String entityPackage;
/**
* author
*/
private static String author;
/**
* Database url
*/
private static String url;
/**
* Database username
*/
private static String username;
/**
* Database password
*/
private static String password;
/**
* Database driver class
*/
private static String driverClass;
/**
* 文件名后缀
*/
private static String fileSuffix = ".java";
/**
* Init database information
*/
static {
Properties properties = new Properties();
// 这个文件对应逆向工程配置文件
InputStream i = CodeGenerator.class.getResourceAsStream("/mybatis-plus.properties");
try {
properties.load(i);
projectPackage = properties.getProperty("generator.parent.package");
controllerPackage = properties.getProperty("controller.package");
entityPackage = properties.getProperty("entity.package");
url = properties.getProperty("generator.jdbc.url");
username = properties.getProperty("generator.jdbc.username");
password = properties.getProperty("generator.jdbc.password");
driverClass = properties.getProperty("generator.jdbc.driverClass");
author = properties.getProperty("author");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* main method, execute code generator
*/
public static void main(String[] args) {
String projectPath = System.getProperty("user.dir");
String javaPath = projectPackage.replaceAll("\\.", "/");
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(projectPath + "/src/main/java"); // 输出文件目录
gc.setFileOverride(true); // 是否覆盖已有文件
gc.setOpen(false); // 是否打开输出目录
gc.setAuthor(author);
gc.setSwagger2(true); // 实体属性 Swagger2 注解
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setBaseResultMap(true); // mapper.xml中生成BaseResultMap
gc.setActiveRecord(true);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(url);
dsc.setUsername(username);
dsc.setPassword(password);
dsc.setDriverName(driverClass);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(projectPackage);
pc.setController(controllerPackage);
pc.setEntity(entityPackage);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
// 如果模板引擎是 freemarker
String entityPath = "/templates/entity.java.ftl";
// 自定义配置会被优先输出
focList.add(new FileOutConfig(entityPath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/java/" + javaPath + "/model/domain/" + tableInfo.getEntityName() + fileSuffix;
}
});
// 如果模板引擎是 freemarker
String controllerPath = "/templates/controller.java.ftl";
// 自定义配置会被优先输出
focList.add(new FileOutConfig(controllerPath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/java/" + javaPath + "/web/controller/" + tableInfo.getEntityName() + "Controller" + fileSuffix;
}
});
cfg.setFileOutConfigList(focList);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setController(null);
templateConfig.setEntity(null);
templateConfig.setXml(null);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setRestControllerStyle(true);
// 注意这个设置的BaseController文件,这个文件在启动类目录的common目录下
// 之后的controller层文件会引这个地方的包
strategy.setSuperControllerClass("com.example.mybatisplus.common.BaseController");
strategy.setEntityLombokModel(true);//启用lombok注解
strategy.setChainModel(true);//启用lombok链式注解
// 这里声明要自动生成代码的表是哪些
strategy.setInclude("emp","dept");
//strategy.setTablePrefix("前缀");//去表前缀配置
mpg.setGlobalConfig(gc);
mpg.setDataSource(dsc);
mpg.setPackageInfo(pc);
mpg.setCfg(cfg);
mpg.setTemplate(templateConfig);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
# 作者 不要用中文,中文会乱码
author=muhuai
# 启动类所在的包名
generator.parent.package=com.muhuai.mybatis_plus
# 声明controller和实体domain所在的包名
controller.package=web.controller
entity.package=model.domain
# 数据库连接
generator.jdbc.driverClass = com.mysql.jdbc.Driver
generator.jdbc.url=jdbc:mysql://127.0.0.1:3306/数据库名字?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
generator.jdbc.username=数据库用户名
generator.jdbc.password=数据库密码
之后直接运行CodeGenerator就行了
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class BaseController<S extends IService<T>,T>{
protected S service;
/**
* 描述:条件列表 查询
*
*/
@ApiOperation(value = "列表查询,若参数存在,则分页查询;若参数不存在,则全量查询" )
@RequestMapping(value = "/list", method = RequestMethod.POST)
public JsonResponse list(Wrapper<T> wrapper,Integer pageNo,Integer pageSize) {
List<T> resultList = null;
if( pageNo > 0 && pageSize> 0) {
Page page = new Page<>();
page.setCurrent(pageNo).setSize(pageSize);
resultList = service.page(page,wrapper).getRecords();
}else{
resultList = service.list(wrapper);
}
return JsonResponse.success(resultList);
}
/**
* 保存实体对象,TableId 注解存在更新记录,否者插入一条记录
*
*/
@ApiOperation(value = "保存实体对象,TableId 注解存在更新记录,否者插入一条记录" )
@RequestMapping(value = "/save", method = RequestMethod.POST)
public JsonResponse save(@RequestBody T model) {
service.saveOrUpdate(model);
return JsonResponse.success("保存成功");
}
/**
* 根据Id查询
*
*/
@ApiOperation(value = "根据Id查询" )
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public JsonResponse findById(@PathVariable("id") Long id) {
T model = service.getById(id);
return JsonResponse.success(model);
}
/**
* 根据Id删除
*
*/
@ApiOperation(value = "根据Id删除" )
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
public JsonResponse deleteById(@PathVariable("id") Long id) {
service.removeById(id);
return JsonResponse.success("删除成功");
}
}
其中需要同目录的一个JsonResponse文件,文件设置响应信息
因为 BaseController 类引用了这个类,所以放在这里
package com.muhuai.mybatis_plus.common;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class JsonResponse<R> implements Serializable {
private static final long serialVersionUID = 7574078101944305355L;
private boolean status;
private int code;
private String message;
private R data;
private Map<String, Object> otherData = new HashMap();
public JsonResponse() {
}
public static <R> JsonResponse<R> success(R data) {
JsonResponse<R> response = new JsonResponse();
response.status = true;
response.data = data;
return response;
}
public static <R> JsonResponse<R> success(R data, String message) {
JsonResponse<R> response = new JsonResponse();
response.status = true;
response.data = data;
response.message = message;
return response;
}
public static <R> JsonResponse<R> successMessage(String message) {
return message(true, message);
}
public static <R> JsonResponse<R> message(boolean status, String message) {
JsonResponse<R> response = new JsonResponse();
response.status = status;
response.message = message;
return response;
}
public static <R> JsonResponse<R> failure(String message) {
return message(false, message);
}
public JsonResponse<R> setOtherData(Map<String, Object> otherData) {
this.otherData = otherData;
return this;
}
public JsonResponse<R> addOtherData(String key, Object value) {
this.otherData.put(key, value);
return this;
}
public JsonResponse<R> removeOtherData(String key) {
this.otherData.remove(key);
return this;
}
public JsonResponse<R> setStatus(boolean status) {
this.status = status;
return this;
}
public JsonResponse<R> setCode(int code) {
this.code = code;
return this;
}
public JsonResponse<R> setMessage(String message) {
this.message = message;
return this;
}
public JsonResponse<R> setData(R data) {
this.data = data;
return this;
}
public JsonResponse<R> setException(Exception e) {
this.addOtherData("exception", e.getClass().getName());
return this;
}
public JsonResponse<R> removeException() {
this.removeOtherData("exception");
return this;
}
public boolean isStatus() {
return this.status;
}
public int getCode() {
return this.code;
}
public String getMessage() {
return this.message;
}
public R getData() {
return this.data;
}
public Map<String, Object> getOtherData() {
return this.otherData;
}
}
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.4version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.0.8version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-cryptoartifactId>
<version>5.2.1.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-freemarkerartifactId>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.3.2version>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocity-engine-coreartifactId>
<version>2.3version>
dependency>
<dependency>
<groupId>commons-langgroupId>
<artifactId>commons-langartifactId>
<version>2.6version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.3.2version>
dependency>
<dependency>
<groupId>io.swaggergroupId>
<artifactId>swagger-annotationsartifactId>
<version>1.5.13version>
dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
exclude>
excludes>
configuration>
plugin>
plugins>
build>