自动生成代码:
1、新建spring boot项目;
2、在pom.xml文件中添加对mybatis和mysql的依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.1</version>
</dependency>
3、在application.properties文件中配置数据库连接:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/数据库名?serverTimezone=GMT&2b8&useSSL=false
spring.datasource.username=用户名
spring.datasource.password=密码
4、新建AutoGenerator类,内容如下:
public class MyBatisPlusGenerator {
public static void main(String[] args) {
AutoGenerator gen = new AutoGenerator();
// 数据库配置
String driverName = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/数据库名?serverTimezone=GMT&2b8&useSSL=false";
String username = 用户名;
String password = 密码;
gen.setDataSource(new DataSourceConfig()
.setDbType(DbType.MYSQL)
.setDriverName(driverName)
.setUrl(url)
.setUsername(username)
.setPassword(password));
// 全局配置
String projectPath = System.getProperty("user.dir");
String authorName ="authorName";
gen.setGlobalConfig(new GlobalConfig()
.setOutputDir(projectPath + "/src/main/java") // 输出目录
.setFileOverride(true) // 是否覆盖文件
.setBaseResultMap(true) // XML ResultMap
.setBaseColumnList(true) // XML columnList
.setOpen(false) //生成后打开文件夹
.setAuthor(authorName)
.setMapperName("%sMapper")
.setXmlName("%sMapper")
.setServiceName("%sService")
.setServiceImplName("%sServiceImpl")
.setControllerName("%sController")
);
// 策略配置
String prefix = "t_";
// 要生成的表名, 为空时默认指定库的所有表
String[] tables = {};
gen.setStrategy(new StrategyConfig()
.setTablePrefix(prefix) // 表前缀
.setNaming(NamingStrategy.underline_to_camel) // 表名生成策略
.setInclude(tables) // 需要生成的表
.setRestControllerStyle(true)
.setEntityLombokModel(true) // lombok 模型
.setLogicDeleteFieldName("is_deleted") // 逻辑删除字段名
.setEntityBooleanColumnRemoveIsPrefix(true) // 去掉布尔值的is_前缀
);
// 包配置
gen.setPackageInfo(new PackageConfig()
.setParent("com.example.test")
.setController("controller")
.setEntity("entity")
.setMapper("dao")
.setService("service")
.setServiceImpl("service.impl")
.setXml("mapper")
);
// 执行生成
gen.execute();
}
}
6、运行 MyBatisPlusGenerator.main(),完成。
分页实现
1、创建 Mybatis Plus 配置类:
@Configuration
@MapperScan("com.example.test.dao")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
2、分页代码:
service.page(new Page<>(page, size)).getRecords();