代码生成的原理是运用的java反射机制,mybatisPlus为我们封装好了一些方法,用于代码生成
public class CodeGen {
/**
* 开始生成代码 运行这个方法
* @param args
*/
public static void main(String[] args) {
generateCode();
}
/**
* <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.isNotEmpty(ipt)) {
return ipt;
}
}
throw new SHException("请输入正确的" + tip + "!");
}
public static void generateCode() {
String moduleName = scanner("请输入模块名称");
String packageName = "com.sihuisoft.sihuiyun.module."+moduleName;
boolean serviceNameStartWithI = true;//user -> UserService, 设置成true: user -> IUserService
generateByTables(serviceNameStartWithI, packageName);
}
private static void generateByTables(boolean serviceNameStartWithI, String packageName) {
GlobalConfig config = new GlobalConfig();
String dbUrl = "jdbc:mysql://10.20.30.100:3306/数据库?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false";
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL)
.setUrl(dbUrl)
.setUsername("root") //数据库用户名
.setPassword("") //密码
.setDriverName("com.mysql.jdbc.Driver"); //数据库引擎
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig
.setCapitalMode(true) // 全局大写命名 ORACLE 注意
.setEntityLombokModel(false)//实体 是否为lombok模型(默认 false)
.setDbColumnUnderline(true) //表名、字段名、是否使用下划线命名
.setNaming(NamingStrategy.underline_to_camel) //下划线转驼峰
.setInclude(scanner("请输入表名"));//修改替换成你需要的表名,多个表名传数组
config.setBaseResultMap(true);
config.setEnableCache(false);// XML 二级缓存
strategyConfig.setSuperEntityClass("com.base.BaseDo");//父类
strategyConfig.setSuperServiceClass("com.base.BaseService");
strategyConfig.setSuperMapperClass("com.base.BaseDao");
strategyConfig.setSuperServiceImplClass("com.base.BaseServiceImpl");
strategyConfig.setSuperControllerClass("com.baseBaseController");
String authorName = scanner("请输入作者名称");
String pathUrl = "E:\\Code"; //生成代码的地址
config.setActiveRecord(false)
.setAuthor(authorName)
.setOutputDir(pathUrl)
.setFileOverride(true);
if (!serviceNameStartWithI) {
config.setServiceName("%sService");
}
new AutoGenerator().setGlobalConfig(config)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(
new PackageConfig()
.setParent(packageName)
.setController("controller")
.setEntity("entity")
).execute();
}
}