通过第四章我们编写了基础开发工具,但是大家会发现我们每开发一个新的模块都要重写一次从dao到xml层的代码,很明显很多都是重复的开发工作,那我们是否可以直接编写一个工具快速生成我们的代码呢?很明显这完全是没有问题的本章我们将实现使用快速生成工具一秒生成我们的所有的代码,该工具是基于从数据库读取表来实现动态生成我们的代码。
首先我们在我们的com.csdn包底下我们新建一个codeUtil包如下所示:
首先我们新建一个我们的列的模型(ColumnModel.java)如下:
/**
* 列模型
*/
public class ColumnModel {
private boolean isPrimaryKey;
private boolean isAutoIncrement;
private String columnName;
private String dataType;
private String typeName;
private String columnClassName;
private String fieldName;
private String fieldType;
private int columnSize;
private String columnDef;
private String remarks;
public boolean isPrimaryKey() {
return isPrimaryKey;
}
public void setPrimaryKey(boolean isPrimaryKey) {
this.isPrimaryKey = isPrimaryKey;
}
public boolean isAutoIncrement() {
return isAutoIncrement;
}
public void setAutoIncrement(boolean isAutoIncrement) {
this.isAutoIncrement = isAutoIncrement;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public int getColumnSize() {
return columnSize;
}
public void setColumnSize(int columnSize) {
this.columnSize = columnSize;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
@Override
public String toString() {
return "ColumnModel [columnName=" + columnName + ", dataType="
+ dataType + ", typeName=" + typeName + ", columnClassName="
+ columnClassName + ", fieldName=" + fieldName + ", fieldType="
+ fieldType + ", columnSize=" + columnSize + ", columnDef="
+ columnDef + ", remarks=" + remarks + "]";
}
public String getColumnDef() {
return columnDef;
}
public void setColumnDef(String columnDef) {
this.columnDef = columnDef;
}
public String getColumnClassName() {
return columnClassName;
}
public void setColumnClassName(String columnClassName) {
this.columnClassName = columnClassName;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldType() {
return fieldType;
}
public void setFieldType(String fieldType) {
this.fieldType = fieldType;
}
}
/**
* 表结构封装
* */
public class TableModel {
//表名
private String tableName;
//主键列
private List primaryKeyColumns;
//列
private List columns;
//需要引入包
private Set imports;
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public List getPrimaryKeyColumns() {
return primaryKeyColumns;
}
public void setPrimaryKeyColumns(List primaryKeyColumns) {
this.primaryKeyColumns = primaryKeyColumns;
}
public List getColumns() {
return columns;
}
public void setColumns(List columns) {
this.columns = columns;
}
public Set getImports() {
return imports;
}
public void setImports(Set imports) {
this.imports = imports;
}
}
在我们新建JdbcUtil.java数据库连接操作类的时候我们首先新建一个(GenCodeUtil.java)我们的操作主类,JdbcUtil的代码如下:
public class JdbcUtil {
private static String properties_file_uri = null;
public static Properties configs;
public static void setPropertiesURL(String uri){
properties_file_uri = uri;
}
/**
* 获取连接
* @return
*/
public static Connection getConnection(){
try {
configs = new Properties();
if(StringUtils.isEmpty(properties_file_uri)){
properties_file_uri = "/genericCoder.properties";
}
String path = GenCodeUtil.class.getResource("/").getPath();
InputStream in = new FileInputStream(new File(path+properties_file_uri));
configs.load(in);
Class.forName(configs.getProperty("spring.datasource.driverClassName"));
Properties properties = new Properties();
properties.put("user", configs.getProperty("spring.datasource.username"));
properties.put("password", configs.getProperty("spring.datasource.password"));
properties.put("remarksReporting","true");//想要获取数据库结构中的注释,这个值是重点
return DriverManager.getConnection(configs.getProperty("spring.datasource.url"), properties);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取表结构
* @param tableName
* @return
*/
public static TableModel getTableStructure(String tableName){
List columnModelList = new ArrayList();
List primaryKeyColumns = new ArrayList();
Set imports = new HashSet();
try {
//TODO 表相关
//ResultSet tableSet = metaData.getTables(null, "%",tableName,new String[]{"TABLE"});
//TODO 字段相关
DatabaseMetaData dbMeta = getConnection().getMetaData();
List primaryKeys = getPrimaryKeys(dbMeta, tableName);
ResultSet columnSet = dbMeta.getColumns(null,"%",tableName,"%");
ColumnModel columnModel = null;
while(columnSet.next()){
columnModel = new ColumnModel();
columnModel.setColumnName(columnSet.getString("COLUMN_NAME"));
columnModel.setColumnSize(columnSet.getInt("COLUMN_SIZE"));
columnModel.setDataType(columnSet.getString("DATA_TYPE"));
columnModel.setRemarks(columnSet.getString("REMARKS"));
columnModel.setTypeName(columnSet.getString("TYPE_NAME"));
columnModel.setAutoIncrement(columnSet.getBoolean("IS_AUTOINCREMENT"));
columnModel.setPrimaryKey(justicPrimaryKey(columnModel.getColumnName(), primaryKeys));
//String columnClassName = ColumnTypeEnum.getColumnTypeEnumByDBType(columnModel.getTypeName());
String columnClassName = sqlType2JavaType(columnModel.getTypeName());
String imp = getImportByJavaType(columnClassName);
if(StringUtils.isNotEmpty(imp))
imports.add(imp);
String fieldName = getFieldName(columnModel.getColumnName());
String fieldType = null;
try{
if(StringUtils.isNotEmpty(columnClassName))
fieldType = Class.forName(columnClassName).getSimpleName();
else
throw new RuntimeException();
}
catch(ClassNotFoundException e){
fieldType = columnClassName;
}
columnModel.setFieldName(fieldName);
columnModel.setColumnClassName(columnClassName);
columnModel.setFieldType(fieldType);
columnModelList.add(columnModel);
if(columnModel.isPrimaryKey())
primaryKeyColumns.add(columnModel);
//System.out.println(columnModel.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
TableModel table = new TableModel();
table.setColumns(columnModelList);
table.setPrimaryKeyColumns(primaryKeyColumns);
table.setImports(imports);
table.setTableName(tableName);
return table;
}
/**
* 将数据库字段转换成bean属性
* @param columnName
* @return
*/
private static String getFieldName(String columnName) {
char[] columnCharArr = columnName.toCharArray();
StringBuffer sb = new StringBuffer();
int ad = -1;
for (int i = 0; i < columnCharArr.length; i++) {
char cur = columnCharArr[i];
if(cur=='_'){
ad = i;
}else{
if((ad+1)==i&&ad!=-1){
sb.append(Character.toUpperCase(cur));
}else{
sb.append(cur);
}
ad=-1;
}
}
return sb.toString();
}
/**
* 获取表主键
* @throws SQLException
* */
private static List getPrimaryKeys(DatabaseMetaData dbMeta, String tableName) throws SQLException{
ResultSet pkRSet = dbMeta.getPrimaryKeys(null, null, tableName);
List primaryKyes = new ArrayList();
while(pkRSet.next()){
primaryKyes.add(pkRSet.getObject("COLUMN_NAME").toString());
}
return primaryKyes;
}
/**
* 判断列是否为主键列
* */
private static boolean justicPrimaryKey(String columnName, List primaryKyes){
for(String key : primaryKyes)
if(key.equals(columnName))
return true;
return false;
}
/**
* 功能:获得列的数据类型
* @param sqlType
* @return
*/
private static String sqlType2JavaType(String sqlType) {
if(sqlType.equalsIgnoreCase("bit")){
return "boolean";
}else if(sqlType.equalsIgnoreCase("tinyint")){
return "byte";
}else if(sqlType.equalsIgnoreCase("smallint")){
return "short";
}else if(sqlType.equalsIgnoreCase("int")){
return "int";
}else if(sqlType.equalsIgnoreCase("bigint")){
return "long";
}else if(sqlType.equalsIgnoreCase("float")){
return "float";
}else if(sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
|| sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
|| sqlType.equalsIgnoreCase("smallmoney")){
return "double";
}else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
|| sqlType.equalsIgnoreCase("text")){
return "String";
}else if(sqlType.equalsIgnoreCase("datetime") || sqlType.equalsIgnoreCase("date")){
return "Date";
}else if(sqlType.equalsIgnoreCase("image")){
return "Blod";
}else if(sqlType.equalsIgnoreCase("timestamp")){
return "Timestamp";
}
return "String";
}
/**
* 根据数据类型获取需要引入的类
* */
private static String getImportByJavaType(String javaType){
switch(javaType){
case "Date": return "java.util.Date";
case "Timestamp": return "java.sql.Timestamp";
case "Blod": return "java.sql.Blod";
}
return null;
}
}
接着我们在生成我们的各层代码的工具类(MyBatisUtil.java)如下:
/**
* mybatis配置文件生成功能
* */
public class MyBatisUtil {
/**
* 从表结构中去生成mybatis配置
* @param table
* @param namespace
* @param beanName
* @param queryModelName
* @return
*/
public static String genMapperConfig(TableModel table,String namespace, String beanName, String queryModelName){
StringBuffer sb = new StringBuffer();
sb.append("\n");
sb.append("\n");
sb.append("\n");
//生成resultMap
String resultMap = beanName.split("\\.")[(beanName.split("\\.").length-1)]+"Map";
sb.append(genResultMap(beanName, resultMap, table));
//生成Get SQL
sb.append(genGETSQL(beanName, resultMap, table));
//生成插入SQL
String dbType = "oracle";
String driver = JdbcUtil.configs.getProperty("spring.datasource.driverClassName");
if(driver.toLowerCase().indexOf("mysql")>0){
dbType = "";
}
if(dbType.equalsIgnoreCase("oracle")){
sb.append(genSAVESQLOfORCL(beanName, table));
}
else{
sb.append(genSAVESQL(beanName, table));
}
//生成修改SQL
sb.append(genUPDATESQL(beanName, table));
//生成删除SQL
sb.append(genDELETESQL(beanName, table));
if(StringUtils.isNotEmpty(queryModelName)){
//生成分页查询
if(dbType.equalsIgnoreCase("oracle")){
sb.append(genFINDBYPAGESQLOfORCL(queryModelName, resultMap, table));
}
else{
sb.append(genFINDBYPAGESQL(queryModelName, resultMap, table));
}
//统计
sb.append(genCOUNTSQL(queryModelName, table));
//查询
sb.append(genQUERYSQL(queryModelName, resultMap, table));
}
sb.append(" ");
return sb.toString();
}
private static String genResultMap(String beanName, String resultMap, TableModel table){
List columnModelList = table.getColumns();
List primaryKeys = table.getPrimaryKeyColumns();
StringBuffer sb = new StringBuffer();
sb.append("\t\n");
if(primaryKeys.size()==1){
ColumnModel primaryKey = primaryKeys.get(0);
sb.append("\t\t\n");
for(ColumnModel cm : columnModelList){
if(!cm.isPrimaryKey())
sb.append("\t\t\n");
}
}
else
for(ColumnModel cm : columnModelList){
sb.append("\t\t\n");
}
sb.append("\t \n\n");
return sb.toString();
}
private static String genGETSQL(String beanName, String resultMap, TableModel table){
List columnModelList = table.getColumns();
List primaryKeys = table.getPrimaryKeyColumns();
StringBuffer sb = new StringBuffer();
sb.append("\t\n");
sb.append("\t
最后我们编写我们主入口生成工具类(GenCodeUtil.java)如下所示:
/*
* 类描述:
* @auther linzf
* @create 2017/12/8 0008
*/
public class GenCodeUtil {
/**
* 从表结构中去生成javabean
* @param author
* @param table
* @param beanName
* @param packagePath
* @return
*/
private static String genJavaBeanFromTableStructure(String author, TableModel table,String beanName, String packagePath){
StringBuffer sb = new StringBuffer();
if(StringUtils.isNotEmpty(packagePath)){
sb.append("package "+packagePath+";\n");
}
for(String imp : table.getImports()){
sb.append("import "+imp+";\n");
}
sb.append("\n");
sb.append("/**\n *@author "+author+"\n **/\n");
List columnModelList = table.getColumns();
try {
sb.append("public class "+toFirstCharUpCase(beanName)+" {\r\n");
for (ColumnModel columnModel : columnModelList) {
if(StringUtils.isNotBlank(columnModel.getRemarks())){
sb.append(" //"+columnModel.getRemarks()+" \r\n");
}
sb.append(" private "+columnModel.getFieldType()+" "+columnModel.getFieldName()+";\r\n");
}
sb.append("\r\n");
//get set
for (ColumnModel columnModel : columnModelList) {
sb.append(
"\tpublic "+columnModel.getColumnClassName()+" get"+toFirstCharUpCase((String) columnModel.getFieldName())+"() {\r\n" +
"\t\treturn "+columnModel.getFieldName()+";\r\n" +
"\t}\r\n" +
"\r\n" +
"\tpublic void set"+toFirstCharUpCase((String) columnModel.getFieldName())+"("+columnModel.getColumnClassName()+" "+columnModel.getFieldName()+") {\r\n" +
"\t\tthis."+columnModel.getFieldName()+" = "+columnModel.getFieldName()+";\r\n" +
"\t}\r\n\r\n");
}
sb.append("}\r\n");
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* 从表结构中去生成查询实体类
* @param author
* @param table
* @param beanName
* @param extendsBasePackage
* @param packagePath
* @return
*/
private static String genQueryModelFromTableStructure(String author, TableModel table,String beanName, String extendsBasePackage, String packagePath){
StringBuffer sb = new StringBuffer();
if(StringUtils.isNotEmpty(packagePath)){
sb.append("package "+packagePath+";\n\n");
}
sb.append("import "+extendsBasePackage+".entity.QueryBase;\n\n");
sb.append("/**\n *@author "+author+"\n **/\n");
try {
sb.append("public class "+toFirstCharUpCase(beanName)+" extends QueryBase {\r\n");
List columns = getQueryFields(table);
for (ColumnModel columnModel : columns) {
if(StringUtils.isNotBlank(columnModel.getRemarks())){
sb.append(" //"+columnModel.getRemarks()+" \r\n");
}
String qFieldType = getQueryModelFieldType(columnModel.getFieldType());
sb.append(" private "+qFieldType+" "+columnModel.getFieldName()+";\r\n");
}
sb.append("\r\n");
//get set
for (ColumnModel columnModel : columns) {
String qFieldType = getQueryModelFieldType(columnModel.getFieldType());
sb.append(
"\tpublic "+qFieldType+" get"+toFirstCharUpCase((String) columnModel.getFieldName())+"() {\r\n" +
"\t\treturn "+columnModel.getFieldName()+";\r\n" +
"\t}\r\n" +
"\r\n" +
"\tpublic void set"+toFirstCharUpCase((String) columnModel.getFieldName())+"("+qFieldType+" "+columnModel.getFieldName()+") {\r\n" +
"\t\tthis."+columnModel.getFieldName()+" = "+columnModel.getFieldName()+";\r\n" +
"\t}\r\n\r\n");
}
sb.append("}\r\n");
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* 生成Dao
* */
private static String genDao(String author, String packagePath, String beanName, String queryModelName,String extendsBasePackage){
StringBuffer sb = new StringBuffer();
if(StringUtils.isNotEmpty(packagePath)){
sb.append("package "+packagePath+";\n\n");
}
String businessPackage = packagePath.substring(0, packagePath.lastIndexOf("."));
String basePackage = businessPackage.substring(0, businessPackage.lastIndexOf("."));
sb.append("import "+extendsBasePackage+".dao.GenericDao;\n\n");
sb.append("import "+businessPackage+".entity."+beanName+";\n");
sb.append("import "+businessPackage+".entity."+queryModelName+";\n\n");
sb.append("/**\n *@author "+author+"\n **/\n");
sb.append("public interface "+beanName+"Dao extends GenericDao<"+beanName+", "+queryModelName+"> {\r\n");
sb.append("\n\t\n}");
return sb.toString();
}
/**
* 生成Service
* */
private static String genService(String author, String packagePath, String beanName, String queryModelName,String extendsBasePackage){
StringBuffer sb = new StringBuffer();
if(StringUtils.isNotEmpty(packagePath)){
sb.append("package "+packagePath+";\n\n");
}
String businessPackage = packagePath.substring(0, packagePath.lastIndexOf("."));
String basePackage = businessPackage.substring(0, businessPackage.lastIndexOf("."));
sb.append("import org.springframework.beans.factory.annotation.Autowired;\n");
sb.append("import org.springframework.stereotype.Service;\n\n");
sb.append("import org.springframework.transaction.annotation.Transactional;\n\n");
sb.append("import "+extendsBasePackage+".service.GenericService;\n");
sb.append("import "+basePackage+".common.base.dao.GenericDao;\n\n");
sb.append("import "+businessPackage+".entity."+beanName+";\n");
sb.append("import "+businessPackage+".entity."+queryModelName+";\n");
sb.append("import "+businessPackage+".dao."+beanName+"Dao;\n\n");
sb.append("/**\n *@author "+author+"\n **/\n");
sb.append("@Service(\""+toFirstCharLowerCase(beanName)+"Service\")\n");
sb.append("@Transactional(rollbackFor={IllegalArgumentException.class})\n");
sb.append("public class "+beanName+"Service extends GenericService<"+beanName+", "+queryModelName+"> {\r\n");
sb.append("\t@Autowired\n");
sb.append("\t@SuppressWarnings(\"SpringJavaAutowiringInspection\")\n");
sb.append("\tprivate "+beanName+"Dao "+toFirstCharLowerCase(beanName)+"Dao;\n");
sb.append("\t@Override\n\tprotected GenericDao<"+beanName+", "+queryModelName+"> getDao() {\n");
sb.append("\t\treturn "+toFirstCharLowerCase(beanName)+"Dao;\n");
sb.append("\t}\n");
sb.append("}");
return sb.toString();
}
/**
* 生成controller
* */
private static String genController(String author, String packagePath, String beanName, String queryModelName,String extendsBasePackage){
StringBuffer sb = new StringBuffer();
if(StringUtils.isNotEmpty(packagePath)){
sb.append("package "+packagePath+";\n\n");
}
String businessPackage = packagePath.substring(0, packagePath.lastIndexOf("."));
String basePackage = businessPackage.substring(0, businessPackage.lastIndexOf("."));
sb.append("import javax.inject.Inject;\n\n");
sb.append("import org.springframework.web.bind.annotation.RequestMapping;\n");
sb.append("import org.springframework.stereotype.Controller;\n");
sb.append("import "+extendsBasePackage+".controller.GenericController;\n");
sb.append("import "+basePackage+".common.base.service.GenericService;\n\n");
sb.append("import "+businessPackage+".entity."+beanName+";\n");
sb.append("import "+businessPackage+".entity."+queryModelName+";\n");
sb.append("import "+businessPackage+".service."+beanName+"Service;\n\n");
sb.append("/**\n *@author "+author+"\n **/\n");
sb.append("@Controller\n");
sb.append("@RequestMapping(\"/"+toFirstCharLowerCase(beanName)+"\")\n");
sb.append("public class "+beanName+"Controller extends GenericController<"+beanName+", "+queryModelName+"> {\r\n");
sb.append("\t@Inject\n");
sb.append("\tprivate "+beanName+"Service "+toFirstCharLowerCase(beanName)+"Service;\n");
sb.append("\t@Override\n\tprotected GenericService<"+beanName+", "+queryModelName+"> getService() {\n");
sb.append("\t\treturn "+toFirstCharLowerCase(beanName)+"Service;\n");
sb.append("\t}\n");
sb.append("}");
return sb.toString();
}
/**
* 将首字母变大写
* @param str
* @return
*/
private static String toFirstCharUpCase(String str){
char[] columnCharArr = str.toCharArray();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < columnCharArr.length; i++) {
char cur = columnCharArr[i];
if(i==0){
sb.append(Character.toUpperCase(cur));
}else{
sb.append(cur);
}
}
return sb.toString();
}
/**
* 将首字母变小写
* @param str
* @return
*/
public static String toFirstCharLowerCase(String str){
char[] columnCharArr = str.toCharArray();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < columnCharArr.length; i++) {
char cur = columnCharArr[i];
if(i==0){
sb.append(Character.toLowerCase(cur));
}else{
sb.append(cur);
}
}
return sb.toString();
}
/**
* 获取查询实体类的字段类型
* */
private static String getQueryModelFieldType(String javaType){
switch(javaType){
case "byte": return "Byte";
case "short": return "Short";
case "int": return "Integer";
case "float": return "Float";
case "double": return "Double";
case "long": return "Long";
}
return "String";
}
/**
* 获取查询字段
* */
public static List getQueryFields(TableModel table){
if(table.getPrimaryKeyColumns().size()==1 && table.getPrimaryKeyColumns().get(0).isAutoIncrement()){
List columns = new ArrayList();
for(ColumnModel cm : table.getColumns()){
if(!cm.isPrimaryKey())
columns.add(cm);
}
return columns;
}
return table.getColumns();
}
/**
* 创建文件夹,防止文件路径不存在
* */
private static String createFloder(String src, String packagePath) throws IOException{
String path = GenCodeUtil.class.getResource("/").getPath();
File pf = new File(path);
pf = pf.getParentFile().getParentFile();
pf = new File(pf.getAbsolutePath()+"/"+src);
String[] subF = packagePath.split("/");
for(String sf : subF){
pf = new File(pf.getPath()+"/"+sf);
if(!pf.exists()){
pf.mkdirs();
}
}
return pf.getAbsolutePath();
}
/**
* 创建文件夹,防止文件路径不存在
* */
private static String createFloder(String basePath) throws IOException{
String path = GenCodeUtil.class.getResource("/").getPath();
File pf = new File(path);
pf = pf.getParentFile().getParentFile();
String[] subF = basePath.split("/");
for(String sf : subF){
if(StringUtils.isNotEmpty(sf)){
pf = new File(pf.getPath()+"/"+sf);
if(!pf.exists()){
pf.mkdirs();
}
}
}
return pf.getAbsolutePath();
}
/**
* @param author 作者
* @param tableName 表名
* @param extendsBasePackage 继承框架类包的基础路径
* @param basePackage 生成文件的包的基础路径
* @param mybatisBasePath mybatis配置文件夹路径
* @param beanName 实体类名称
* @param queryModelName 查询类名称
* @since properties keys include 'db.driver'、'db.username'、'db.password' and 'db.url'
* */
public static void genFiles(String author, String tableName, String extendsBasePackage, String basePackage, String mybatisBasePath, String beanName, String queryModelName, String properitesUri) throws IOException {
String packagePath = basePackage.replaceAll("\\.", "/");
JdbcUtil.setPropertiesURL(properitesUri);
TableModel table = JdbcUtil.getTableStructure(tableName);
String entityPath = createFloder("src/main/java", packagePath+"/entity");
//生成实体类文件
File fEntity = new File(entityPath+"/"+beanName+".java");
if(fEntity.exists()){
fEntity.delete();
}
FileOutputStream fos = new FileOutputStream(fEntity);
fos.write(genJavaBeanFromTableStructure(author, table, beanName, basePackage+".entity").getBytes());
fos.close();
//生成查询实体类文件
if(StringUtils.isNotEmpty(queryModelName)){
File fQEntity = new File(entityPath+"/"+queryModelName+".java");
if(fQEntity.exists()){
fQEntity.delete();
}
fos = new FileOutputStream(fQEntity);
fos.write(genQueryModelFromTableStructure(author, table, queryModelName, extendsBasePackage, basePackage+".entity").getBytes());
fos.close();
}
//生成mybatis配置文件
String mybatisPath = createFloder("/src/main"+mybatisBasePath);
fos = new FileOutputStream(mybatisPath+"/mybatis_"+toFirstCharLowerCase(beanName)+".xml");
fos.write(MyBatisUtil.genMapperConfig(table, basePackage+".dao."+beanName+"Dao", basePackage+".entity."+beanName, basePackage+".entity."+queryModelName).getBytes());
fos.close();
//生成Dao
String daoPath = createFloder("src/main/java", packagePath+"/dao");
File fDao = new File(daoPath+"/"+beanName+"Dao.java");
fos = new FileOutputStream(fDao);
fos.write(genDao(author, basePackage+".dao", beanName, queryModelName,extendsBasePackage).getBytes());
fos.close();
//生成Service
String servicePath = createFloder("src/main/java", packagePath+"/service");
File fService = new File(servicePath+"/"+beanName+"Service.java");
fos = new FileOutputStream(fService);
fos.write(genService(author, basePackage+".service", beanName, queryModelName,extendsBasePackage).getBytes());
fos.close();
// 生成controller
String controllerPath = createFloder("src/main/java", packagePath+"/controller");
File fController = new File(controllerPath+"/"+beanName+"Controller.java");
fos = new FileOutputStream(fController);
fos.write(genController(author, basePackage+".controller", beanName, queryModelName,extendsBasePackage).getBytes());
fos.close();
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
genFiles("linzf", "t_dining_table", "com.dinner.snqjf.common.base","com.dinner.snqjf.back", "/resources/mybatis/mapper","DiningTable", "QueryDiningTable", "application-dev.properties");
}
}
接着我们在数据执行生成我们的dict表的数据库字典脚本,然后我们在GenCodeUtil的main方法中执行我们的快速生成代码如下:
通过上图我们可以很明显的看到我们的代码已经生成成功了,那么接下来我们重新加载下我们的项目我们访问下我们的swagger2接口我们会发现我们的生成的代码已经生效了:
到此处我们很明显的发现我们生成的代码已经生效了,那么以后我们每当有一个新的模块的开发那么我们只要设计好数据库,后续我们就可以快速的生成代码,大大简化我们的开发工作,下一章将讲解如何集成bootsrap。
本章的代码GitHub地址:https://github.com/185594-5-27/csdndemo/tree/base-druid-swagger-tool-two
上一篇文章地址:基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【四】【编写基础开发工具】
下一篇文章地址:基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【六】【引入bootstrap前端框架】
QQ交流群:578746866