SQL腳本:
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主鍵ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年齡',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱',
PRIMARY KEY (id)
);
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
生成的數(shù)據(jù)庫(kù)結(jié)構(gòu):

user表
Maven依賴配置
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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.3.1.tmp</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<!-- Velocity(默認(rèn))-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!-- Freemarker-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
<!-- Beetl-->
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
</dependencies>
Tips:懶癌患者直接復(fù)制,建議按需添加
配置代碼生成器
public class CodeGenerator {
/**
* <p>
* 讀取控制臺(tái)內(nèi)容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("請(qǐng)輸入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請(qǐng)輸入正確的" + 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);
// gc.setSwagger2(true); 實(shí)體屬性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 數(shù)據(jù)源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://120.55.167.13:3306/demo1?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("賬號(hào)");
dsc.setPassword("密碼");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模塊名"));
pc.setParent("com.zz.mybatisplusdemo");
mpg.setPackageInfo(pc);
// 自定義配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定義輸出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定義配置會(huì)被優(yōu)先輸出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱會(huì)跟著發(fā)生變化??!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判斷自定義文件夾是否需要?jiǎng)?chuàng)建
checkDir("調(diào)用默認(rèn)方法創(chuàng)建的目錄");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定義輸出模板
//指定自定義模板路徑,注意不要帶上.ftl/.vm, 會(huì)根據(jù)使用的模板引擎自動(dòng)識(shí)別
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("你自己的父類實(shí)體,沒(méi)有就不用設(shè)置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父類
// strategy.setSuperControllerClass("你自己的父類控制器,沒(méi)有就不用設(shè)置!");
// 寫于父類中的公共字段
// strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多個(gè)英文逗號(hào)分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
Tips:注意對(duì)數(shù)據(jù)源配置,目錄名等關(guān)鍵字段進(jìn)行修改
生成的目錄結(jié)構(gòu):

目錄結(jié)構(gòu)
編寫分頁(yè)參數(shù)封裝類:
@Data
public class BaseRequestUtils implements Serializable {
private static final long serialVersionUID = -7308084942201756448L;
/*分頁(yè)頁(yè)號(hào)*/
private Integer pageIndex;
/*分頁(yè)大小*/
private Integer pageSize;
/*模糊查詢內(nèi)容*/
private String context;
/*額外參數(shù)*/
private Map<String, Object> map;
}
編寫結(jié)果返回集:
public class Result<T> {
public static final Integer SUCCESS = 200; //成功
public static final Integer FAILD = 500;//失敗
public static final Integer BAD_REQUEST = 400;//錯(cuò)誤請(qǐng)求
//狀態(tài)碼
private Integer status;
//消息提示
private String msg;
//數(shù)據(jù)
private T data;
//分頁(yè)數(shù)據(jù)
private List<T> rows;
//分頁(yè)數(shù)據(jù)總量
private Number total;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}
public Number getTotal() {
return total;
}
public void setTotal(Number total) {
this.total = total;
}
/**
* 判斷請(qǐng)求是否成功
* @return
*/
public Boolean isSuccess(){
return this.status.intValue() == SUCCESS.intValue();
}
}
編寫Service層代碼:
接口:
public interface IUserService extends IService<User> {
//分頁(yè)顯示記錄
IPage<User> getUserByPage(BaseRequestUtils baseRequestUtils);
}
實(shí)現(xiàn)類:
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Resource
private UserMapper userMapper;
@Override
public IPage<User> getUserByPage(BaseRequestUtils baseRequestUtils) {
//默認(rèn)配置為第0頁(yè),展示十條記錄
Long pageIndex = Long.valueOf(0);
Long pageSize = Long.valueOf(10);
if (baseRequestUtils.getPageIndex() != null && baseRequestUtils.getPageSize() != null) {
pageIndex = Long.valueOf(baseRequestUtils.getPageIndex());
pageSize = Long.valueOf(baseRequestUtils.getPageSize());
}
IPage<User> page = new Page<>(pageIndex, pageSize);
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class);
if (baseRequestUtils.getMap() != null) {
if (StringUtils.isNotBlank(baseRequestUtils.getMap().get("name").toString())) {
wrapper.eq(User::getName, baseRequestUtils.getMap().get("name"));
}
}
return userMapper.selectPage(page, wrapper);
}
}
編寫Controller層代碼:
@RestController
@RequestMapping("api")
public class UserController {
@Resource
private IUserService userService;
@PostMapping("query")
public ResponseEntity<IPage<User>> testQuery(@RequestBody BaseRequestUtils baseRequestUtils) {
IPage<User> result = userService.getUserByPage(baseRequestUtils);
return ResponseEntity.ok(result);
}
}
PostMan測(cè)試:

請(qǐng)求參數(shù)

調(diào)用結(jié)果
同時(shí)可以通過(guò)Map傳入條件做條件查詢(代碼中只加入了name字段,可以自行添加其他字段):

請(qǐng)求參數(shù)

調(diào)用結(jié)果