首先在pom.xml中导入一下包
注spring的版本为2.5.5 不然会报错
UserDao 接口(pojo entity)
UserDaoImpl 实现类
UserService 业务接口
UserServiceImpl 业务实现类
org.springframework.boot
spring-boot-devtools
runtime
true
com.baomidou
mybatis-plus-boot-starter
3.4.0
com.baomidou
mybatis-plus-generator
3.4.0
org.springframework.boot
spring-boot-starter-freemarker
org.apache.velocity
velocity-engine-core
2.2
org.springframework.boot
spring-boot-starter-thymeleaf
io.springfox
springfox-swagger2
2.7.0
io.springfox
springfox-swagger-ui
2.7.0
org.apache.shiro
shiro-spring
1.4.0
junit
junit
test
javax.servlet
javax.servlet-api
4.0.1
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
在application中配置
spring.profiles.active=dev
#dev 开发环境 pro运行
server.port=8088
#数据源
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#修改连接的数据库database
spring.datasource.url=jdbc:mysql:///database ?createDatabaseIfNotExist=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=
#mp的数据日志输出
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#json的时间格式配置:在返回json给前端时json的时区要设置
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.main.allow-bean-definition-overriding=true
创建一个config包
创建一个mybatisConfig类
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = ("com.blog.demo.mapper*"))//mapper路径
public class MpConfig { // 注册乐观锁插件
@Bean
public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor(){return new OptimisticLockerInnerInterceptor();}
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
创建swaggerConfig类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2);
}
}
代码生成器(可以使用自定义生成模板,可以生成crud代码)
引用于:
https://blog.csdn.net/jjj___jjj/article/details/117172161
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
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.TableFill;
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.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
class Generation {
//这部分需要根据实际情况更改
private static final String dbName = "smbms";
private static final String basePackageName = "com.blog.demo";
private static final String driverClassName = "com.mysql.cj.jdbc.Driver";
// private static final String driverClassName = "com.mysql.jdbc.Driver";
private static final String dbUrl = "jdbc:mysql://127.0.0.1:3306/" + dbName + "?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8";
private static final String dbUsername = "root";
private static final String dbPassword = "";
private static final String author = "YH";
// 是否开启swagger日志
private static final boolean useSwagger =true;
// 是否覆盖
private static final boolean isOverride = true;
/**
* 获取某个数据库中的所有表名
* @param dbName
* @return
* @throws Exception
*/
private static String[] getTables(String dbName) throws Exception {
List tables = new ArrayList<>();
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
Class.forName(driverClassName);
connection = DriverManager.getConnection(dbUrl,dbUsername,dbPassword);
String sql = "select table_name from information_schema.tables where table_schema=?";
ps = connection.prepareStatement(sql);
ps.setString(1,dbName);
resultSet = ps.executeQuery();
while (resultSet.next()) {
tables.add(resultSet.getString("table_name"));
}
String[] result = tables.toArray(new String[tables.size()]);
return result;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
throw new Exception("数据库连接异常!");
}
/**
* 直接获取数据库中的所有表名然后自动生成
* 自动生成entity、mapper、service、controller的代码
* @throws Exception
*/
private static void generateAllInfo() throws Exception {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor(author);
gc.setOpen(false);
gc.setSwagger2(useSwagger); //实体属性 Swagger2 注解
gc.setFileOverride(isOverride); // 是否覆盖
gc.setServiceName("%sService"); //去Service的I前缀
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(dbUrl);
dsc.setDriverName(driverClassName);
dsc.setUsername(dbUsername);
dsc.setPassword(dbPassword);
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(null);
pc.setParent(basePackageName);
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {}
};
// 如果模板引擎是 freemarker
// String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List focList = new ArrayList<>();
// 自定义配置会被优先输出 不同的模板用用不同的文件 ftl vm
// focList.add(new FileOutConfig("/templates/controller.java.vm") {
// @Override
// public String outputFile(TableInfo tableInfo) {
// // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
// return projectPath + "/src/main/resources/mapper/" +
// "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
// }
// });
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setInclude(getTables(dbName));
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// strategy.setLogicDeleteFieldName("deleted"); //逻辑删除
// //自动填充配置
// TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT); //创建时间,新增时自动填充
// TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE); //修改时间,新增和修改时自动填充
// ArrayList tableFills = new ArrayList<>();
// tableFills.add(gmtCreate);
// tableFills.add(gmtModified);
// strategy.setTableFillList(tableFills);
//
// //乐观锁配置
// strategy.setVersionFieldName("version");
mpg.execute();
}
public static void main(String[] args) {
try {
generateAllInfo();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
String serverPort = context.getEnvironment().getProperty("server.port");
log.info("SENS started at http://localhost:" + serverPort);
运行代码生成器
启动项目后访问localhost:port/swagger-ui.html即可
进入swagger的UI界面