mven依赖
<!--mybatis-plus 依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
mybatis-plus-generator逆向工程代码自动生成
官网:https://baomidou.com/pages/d357af/#%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B
新建一个springboot项目:
maven依赖:
<!--web 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-plus 依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<!--mybatis-plus 代码生成器依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<!--freemarker 模板引擎依赖-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<!--mysql 依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
创建目录:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jAK7SwpJ-1647345224327)(mybatis-plus-generator.assets/1647325600390.png)]
导入代码:
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
/**
* <p>
* 读取控制台内容
* </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)) {
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 + "/yeb-generator/src/main/java");
gc.setAuthor("crabin");
gc.setOpen(false);
//实体属性 Swagger2 注解
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/yeb?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("lpb062700");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.crabin")
.setEntity("pojo")
.setMapper("mapper")
.setService("service")
.setServiceImpl("service.impl")
.setController("controller");
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<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/yeb-generator/src/main/resources/mapper/"
+ tableInfo.getEntityName() + "Mapper"
+ StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录,自定义目录用");
if (fileType == FileType.MAPPER) {
// 已经生成 mapper 文件判断存在,不想重新生成返回 false
return !new File(filePath).exists();
}
// 允许生成模板文件
return true;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// 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.no_change);
// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
//lombok模型
strategy.setEntityLombokModel(true);
//生成 @RestController 控制器
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
//表前缀
strategy.setTablePrefix("t_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
生成:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9k5DPRQA-1647345224328)(mybatis-plus-generator.assets/1647325736879.png)]
MybatisPlus设置分页
在配置文件中:MybatisPlusConfig 开启mybatis-plusMybatis分页配置
/**
* Mybatis分页配置
*/
@EnableTransactionManagement // 开启事务管理
@MapperScan("com.abin.mapper") // 扫描mapper接口
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
分页返回类 RespPageBean
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RespPageBean implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 总条数
*/
private Long total;
/**
* 数据List
*/
private List<?> data;
}
controller
//currentPage:当前页,size:每页大小
@GetMapping("/")
public RespPageBean employeePage(@RequestParam(defaultValue = "1") Integer currentPage,
@RequestParam(defaultValue = "10") Integer size,
) {
return employeeService.getEmployeePage(currentPage, size );
}
serviceImpl
@Override
public RespPageBean getEmployeePage(
Integer currentPage, Integer size ) {
Page<Employee> page = new Page<>(currentPage,size);
IPage<Employee> employeeIPage = employeeMapper.getEmployeeByPage(page);
RespPageBean respPageBean= new RespPageBean(employeeIPage.getTotal(),employeeIPage.getRecords());
return respPageBean;
}
Mapper
//可以传入Employee进行查询并返回
IPage<Employee> getEmployeeByPage(Page<Employee> page);
****Mapper.xml
<select id="getEmployeeByPage" resultMap="EmployeeMap">
SELECT e.*,n.id as nid,n.`name` as nname, p.id as pid,p.`name` as pname,
d.id as did,d.`name` as dname,j.id as jid,j.`name` as jname,pos.id as posid,
pos.`name` as posname
FROM
t_employee e,t_nation n,t_politics_status p,
t_department d,t_joblevel j,t_position pos
WHERE
e.nationId = n.id
AND e.politicId = p.id
AND e.departmentId = d.id
AND e.jobLevelId = j.id
AND e.posId = pos.id
ORDER BY e.id
</select>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BG51uC1e-1647345224329)(mybatis-plus-generator.assets/1647334694255.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7VqXKm3g-1647345224329)(mybatis-plus-generator.assets/1647334661203.png)]
E
e.nationId = n.id
AND e.politicId = p.id
AND e.departmentId = d.id
AND e.jobLevelId = j.id
AND e.posId = pos.id
ORDER BY e.id
</select>
[外链图片转存中...(img-BG51uC1e-1647345224329)]
[外链图片转存中...(img-7VqXKm3g-1647345224329)]