1、config.properties
## 数据库连接参数 jdbc.driverClass = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/wshop jdbc.username = root jdbc.password = 123456 ##项目路径 projectPath = D:/generator/ ##是否生成Bean实体类 beanFlag=true ## 生成Bean实体类的包名 beanPackage=com.hwf.bean ##是否生成Dao接口 daoFlag=true ##生成Dao接口的包名 daoPackage=com.hwf.dao ##是否生成Mapper.xml mapperXmlFlag=true ##生成Mapper.xml的包名 mapperXmlPackage=com.hwf.daoImpl ##是否生成Service接口 serviceFlag=true ##生成Service接口的包名 servicePackage=com.hwf.service ##是否生成ServiceImpl实现类 serviceImplFlag=true ##生成ServiceImpl实现类的包名 serviceImplPackage=com.hwf.serviceImpl
2、com.hwf.auto.bean包
package com.hwf.auto.bean; /** * 数据表的列结构 * @author * */ public class ColumnStruct { private String columnName;//字段名称 private String dataType;//字段类型 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 ColumnStruct(String columnName, String dataType) { super(); this.columnName = columnName; this.dataType = dataType; } public ColumnStruct() { super(); } @Override public String toString() { return "ColumnStruct [columnName=" + columnName + ", dataType=" + dataType + "]"; } }
package com.hwf.auto.bean; import java.util.List; /** * 数据表的表结构 * @author * */ public class TableStruct { private String tableName;//表名 private List Columns;//所有的列 public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public List getColumns() { return Columns; } public void setColumns(List columns) { Columns = columns; } public TableStruct(String tableName, List columns) { super(); this.tableName = tableName; Columns = columns; } public TableStruct() { super(); } @Override public String toString() { return "TableStruct [tableName=" + tableName + ", Columns=" + Columns + "]"; } }
3、com.hwf.auto.dao包
package com.hwf.auto.dao; /** * 生成Bean实体类的dao层接口 * @author * */ public interface BeanAutoDao { //通过表名、字段名称、字段类型创建Bean实体 public boolean createBean(); }
package com.hwf.auto.dao; /** * 生成Dao接口的dao层接口 * @author * */ public interface DaoAutoDao { //通过表名、字段名称、字段类型创建Dao接口 public boolean createDao(); }
package com.hwf.auto.dao; import java.util.List; /** * 获取数据表及其结构的dao层接口 * @author * */ public interface GetTablesDao { //获得数据库的所有表名 public List getTablesName(); //获得数据表中的字段名称、字段类型 public List getTablesStruct(); }
package com.hwf.auto.dao; /** * 生成Mapper.xml的dao层接口 * @author * */ public interface MapperXmlAutoDao { //通过表名、字段名称、字段类型创建Mapper.xml public boolean createMapperXml(); }
package com.hwf.auto.dao; /** * 生成Service接口的dao层接口 * @author * */ public interface ServiceAutoDao { //通过表名、字段名称、字段类型创建Service接口 public boolean createService(); }
package com.hwf.auto.dao; /** * 生成ServiceImpl实现类的dao层接口 * @author * */ public interface ServiceImplAutoDao { //通过表名、字段名称、字段类型创建ServiceImpl实现类 public boolean createServiceImpl(); }
4、com.hwf.auto.daoImpl包
package com.hwf.auto.daoImpl; import com.hwf.auto.bean.ColumnStruct; import com.hwf.auto.bean.TableStruct; import com.hwf.auto.dao.BeanAutoDao; import com.hwf.auto.dao.GetTablesDao; import com.hwf.auto.util.ConfigUtil; import com.hwf.auto.util.DataTypeUtil; import com.hwf.auto.util.FileUtil; import com.hwf.auto.util.NameUtil; import java.util.List; /** * 生成Bean实体类的dao层实现类 * @author * */ public class BeanAutoDaoImpl implements BeanAutoDao { //从GetTablesDaoImpl中获得装有所有表结构的List GetTablesDao getTables = new GetTablesDaoImpl(); List<TableStruct> list = getTables.getTablesStruct(); //通过表名、字段名称、字段类型创建Bean实体 @Override public boolean createBean() { //获得配置文件的参数 //项目路径 String projectPath = ConfigUtil.projectPath; //是否生成实体类 String beanFalg=ConfigUtil.beanFlag; //Bean实体类的包名 String beanPackage=ConfigUtil.beanPackage; //判断是否生成实体类 if("true".equals(beanFalg) ){ //将包名com.xxx.xxx形式,替换成com/xxx/xxx形成 String beanPath=beanPackage.replace(".", "/"); //Bean实体类的路径 String path =projectPath+"/src/"+beanPath; //遍历装有所有表结构的List for (int i = 0; i < list.size(); i++) { //文件名 String fileName=NameUtil.fileName(list.get(i).getTableName())+"Bean"; //获得每个表的所有列结构 List<ColumnStruct> columns =list.get(i).getColumns(); //(实体类)文件内容 String packageCon ="package "+beanPackage+";\n\n"; StringBuffer importCon=new StringBuffer(); String className ="public class "+fileName+"{\n\n"; StringBuffer classCon =new StringBuffer(); StringBuffer gettersCon = new StringBuffer(); StringBuffer settersCon = new StringBuffer(); StringBuffer noneConstructor =new StringBuffer(); StringBuffer constructor =new StringBuffer(); String constructorParam=""; StringBuffer constructorCon=new StringBuffer(); //遍历List,将字段名称和字段类型写进文件 for (int j = 0; j < columns.size(); j++) { //变量名(属性名) String columnName =NameUtil.columnName(columns.get(j).getColumnName()); //获得数据类型 String type = columns.get(j).getDataType(); //将mysql数据类型转换为java数据类型 String dateType =DataTypeUtil.getType(type); //有date类型的数据需导包 if("Date".equals(dateType)){ importCon.append("import java.util.Date;\n\n"); } //有Timestamp类型的数据需导包 if("Timestamp".equals(dateType)){ importCon.append("import java.sql.Timestamp;\n\n"); } //生成属性 classCon.append("\t"+"private"+"\t"+dateType+"\t"+columnName+";\n"); //get、set的方法名 String getSetName=columnName.substring(0,1).toUpperCase()+columnName.substring(1); //生成get方法 gettersCon.append("\t"+"public"+"\t"+dateType+"\t"+"get"+getSetName+"(){\n"+ "\t\t"+"return"+"\t"+columnName+";\n"+ "\t"+"}\n"); //生成set方法 settersCon.append("\t"+"public void"+"\t"+"set"+getSetName+"("+dateType+" "+columnName+"){\n"+ "\t\t"+"this."+columnName+" = "+columnName+";\n"+ "\t"+"}\n"); //获得有参构造器参数 if(constructorParam==null||"".equals(constructorParam)){ constructorParam=dateType+" "+columnName; }else{ constructorParam+=","+dateType+" "+columnName; } //获得有参构造器的内容 constructorCon.append("\t\t"+"this."+columnName+" = "+columnName+";\n"); } //生成无参构造器 noneConstructor.append("\t"+"public"+"\t"+fileName+"(){\n"+ "\t\t"+"super();\n"+ "\t"+"}\n"); //生成有参构造 constructor.append("\t"+"public"+" "+fileName+"("+constructorParam+"){\n"+ "\t\t"+"super();\n"+constructorCon+ "\t"+"}\n"); //拼接(实体类)文件内容 StringBuffer content=new StringBuffer(); content.append(packageCon); content.append(importCon.toString()); content.append(className); content.append(classCon.toString()); content.append(gettersCon.toString()); content.append(settersCon.toString()); content.append(noneConstructor.toString()); content.append(constructor.toString()); content.append("}"); FileUtil.createFileAtPath(path+"/", fileName+".java", content.toString()); } return true; } return false; } }
package com.hwf.auto.daoImpl; import com.hwf.auto.bean.ColumnStruct; import com.hwf.auto.bean.TableStruct; import com.hwf.auto.dao.DaoAutoDao; import com.hwf.auto.dao.GetTablesDao; import com.hwf.auto.util.ConfigUtil; import com.hwf.auto.util.DataTypeUtil; import com.hwf.auto.util.FileUtil; import com.hwf.auto.util.NameUtil; import java.util.List; /** * 生成Dao接口的dao层实现类 * @author * */ public class DaoAutoDaoImpl implements DaoAutoDao { //从GetTablesDaoImpl中获得装有所有表结构的List GetTablesDao getTables = new GetTablesDaoImpl(); List<TableStruct> list = getTables.getTablesStruct(); //通过表名、字段名称、字段类型创建Dao接口 @Override public boolean createDao() { //获得配置文件的参数 //项目路径 String projectPath = ConfigUtil.projectPath; //是否生成Dao String daoFalg=ConfigUtil.daoFlag; //Dao接口的包名 String daoPackage=ConfigUtil.daoPackage; //Bean实体类的包名 String beanPackage=ConfigUtil.beanPackage; if("true".equals(daoFalg) ){ //将包名com.xxx.xxx形式,替换成com/xxx/xxx形成 String daoPath=daoPackage.replace(".", "/"); //Dao接口的路径 String path =projectPath+"/src/"+daoPath; //遍历装有所有表结构的List for (int i = 0; i < list.size(); i++) { //文件名 String fileName=NameUtil.fileName(list.get(i).getTableName())+"Dao"; String beanName =NameUtil.fileName(list.get(i).getTableName())+"Bean"; //获得每个表的所有列结构 List<ColumnStruct> columns =list.get(i).getColumns(); //变量名(属性名) String columnName =NameUtil.columnName(columns.get(0).getColumnName()); //获得数据类型 String type = columns.get(0).getDataType(); //将mysql数据类型转换为java数据类型 String dateType =DataTypeUtil.getType(type); //(Dao接口)文件内容 String packageCon ="package "+daoPackage+";\n\n"; StringBuffer importCon=new StringBuffer(); String className ="public interface "+fileName+"{\n\n"; StringBuffer classCon = new StringBuffer(); //生成导包内容 importCon.append("import"+"\t"+beanPackage+"."+beanName+";\n\n"); //有date类型的数据需导包 if("Date".equals(dateType)){ importCon.append("import java.util.Date;\n\n"); } //有Timestamp类型的数据需导包 if("Timestamp".equals(dateType)){ importCon.append("import java.sql.Timestamp;\n\n"); } importCon.append("import java.util.List;\n\n"); //生成接口方法 classCon.append("\t"+"public int insertRecord("+beanName+" record);//添加一条完整记录\n\n"); classCon.append("\t"+"public int insertSelective("+beanName+" record);//添加指定列的数据\n\n"); classCon.append("\t"+"public int deleteById("+dateType+" "+columnName+");//通过Id(主键)删除一条记录\n\n"); classCon.append("\t"+"public int updateByIdSelective("+beanName+" record);//按Id(主键)修改指定列的值\n\n"); classCon.append("\t"+"public int updateById("+beanName+" record);//按Id(主键)修改指定列的值\n\n"); classCon.append("\t"+"public int countRecord();//计算表中的总记录数\n\n"); classCon.append("\t"+"public int countSelective("+beanName+" record);//根据条件计算记录条数\n\n"); classCon.append("\t"+"public int maxId();//获得表中的最大Id\n\n"); classCon.append("\t"+"public"+"\t"+beanName+"\t"+"selectById("+dateType+"\t"+columnName+");//通过Id(主键)查询一条记录\n\n"); classCon.append("\t"+"public List selectAll();//查询所有记录\n\n"); //拼接(Dao接口)文件内容 StringBuffer content=new StringBuffer(); content.append(packageCon); content.append(importCon.toString()); content.append(className); content.append(classCon.toString()); content.append("\n}"); FileUtil.createFileAtPath(path+"/", fileName+".java", content.toString()); } return true; } return false; } }
package com.hwf.auto.daoImpl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.hwf.auto.bean.ColumnStruct; import com.hwf.auto.bean.TableStruct; import com.hwf.auto.dao.GetTablesDao; import com.hwf.auto.util.DataSourceUtil; /** * 获取数据表及其结构的dao层实现类 * @author * */ public class GetTablesDaoImpl extends DataSourceUtil implements GetTablesDao { //获得数据库的所有表名 @Override public List getTablesName() { List tables = new ArrayList(); String sql="show tables"; ResultSet rs=this.query(sql); try { while(rs.next()){ //将获得的所有表名装进List tables.add(rs.getString(1)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return tables; } //获得数据表中的字段名称、字段类型 @Override public List getTablesStruct() { //获得装有所有表名的List List tables =this.getTablesName(); String sqls =null; //装所有的表结构(表名+字段名称+字段类型) List tablesStruct = new ArrayList(); for (int i = 0; i < tables.size(); i++) { sqls="show columns from "+tables.get(i).toString(); ResultSet rs=this.query(sqls); //装所有的列结构(字段名称+字段类型) List list =new ArrayList(); try { while(rs.next()){ ColumnStruct cs = new ColumnStruct(rs.getString(1),rs.getString(2)); //找到一列装进List list.add(cs); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //遍历完一张表,封装成对象 TableStruct ts = new TableStruct(tables.get(i).toString(),list); //将对象(一张表)装进集合 tablesStruct.add(ts); } return tablesStruct; } }
package com.hwf.auto.daoImpl; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.hwf.auto.bean.ColumnStruct; import com.hwf.auto.bean.TableStruct; import com.hwf.auto.dao.GetTablesDao; import com.hwf.auto.dao.MapperXmlAutoDao; import com.hwf.auto.util.ConfigUtil; import com.hwf.auto.util.DataTypeUtil; import com.hwf.auto.util.FileUtil; import com.hwf.auto.util.JdbcTypeUtil; import com.hwf.auto.util.NameUtil; import com.hwf.auto.util.ParamTypeUtil; /** * 生成Mapper.xml的dao层实现类 * @author * */ public class MapperXmlAutoDaoImpl implements MapperXmlAutoDao { //从GetTablesDaoImpl中获得装有所有表结构的List GetTablesDao getTables = new GetTablesDaoImpl(); List<TableStruct> list = getTables.getTablesStruct(); //通过表名、字段名称、字段类型创建Mapper.xml @Override public boolean createMapperXml() { //获得配置文件的参数 //项目路径 String projectPath = ConfigUtil.projectPath; //是否生成Mapper.xml String mapperXmlFalg=ConfigUtil.mapperXmlFlag; //Mapper.xml的包名 String mapperXmlPackage=ConfigUtil.mapperXmlPackage; //Bean实体类的包名 String beanPackage=ConfigUtil.beanPackage; //Dao接口的包名 String daoPackage=ConfigUtil.daoPackage; if("true".equals(mapperXmlFalg) ){ //将包名com.xxx.xxx形式,替换成com/xxx/xxx形成 String mapperXmlPath=mapperXmlPackage.replace(".", "/"); //Mapper.xml的路径 String path =projectPath+"/src/"+mapperXmlPath; //遍历装有所有表结构的List for (int i = 0; i < list.size(); i++) { //表名 String tableName =list.get(i).getTableName(); //文件名 String fileName=NameUtil.fileName(tableName)+"Mapper"; String beanName =NameUtil.fileName(tableName)+"Bean"; String daoName =NameUtil.fileName(tableName)+"Dao"; //获得每个表的所有列结构 List<ColumnStruct> columns =list.get(i).getColumns(); //主键名 String beanIdName=NameUtil.columnName(columns.get(0).getColumnName()); String IdName = columns.get(0).getColumnName(); //主键类型 String IdType = DataTypeUtil.getType(columns.get(0).getDataType()); String IdParamType =ParamTypeUtil.getParamType(IdType); String IdJdbcType = JdbcTypeUtil.getJdbcType(IdType); if(IdJdbcType=="INT"||"INT".equals(IdJdbcType)){ IdJdbcType="INTEGER"; } //(Mapper.xml)文件内容 StringBuffer headCon = new StringBuffer(); headCon.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); headCon.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n"); headCon.append("<mapper namespace=\""+daoPackage+"."+daoName+"\">\n"); StringBuffer resultMapCon = new StringBuffer(); resultMapCon.append("\t"+"<resultMap id=\"BaseResultMap\" type=\""+beanPackage+"."+beanName+"\">\n"); StringBuffer baseColCon = new StringBuffer(); baseColCon.append("\t"+"<sql id=\"Base_Column_List\">\n"); StringBuffer insertRecordCon = new StringBuffer(); insertRecordCon.append("\t"+"<insert id=\"insertRecord\" parameterType=\""+beanPackage+"."+beanName+"\">\n"); insertRecordCon.append("\t\t"+"insert into "+tableName+"("); StringBuffer insertRecordCons = new StringBuffer(); insertRecordCons.append("\t\t"+"values ("); StringBuffer insertSelCon = new StringBuffer(); insertSelCon.append("\t"+"<insert id=\"insertSelective\" parameterType=\""+beanPackage+"."+beanName+"\">\n"); insertSelCon.append("\t\t"+"insert into "+tableName+"\n"); insertSelCon.append("\t\t"+"<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\" >\n"); StringBuffer insertSelCons = new StringBuffer(); StringBuffer delByIdCon = new StringBuffer(); delByIdCon.append("\t"+"<delete id=\"deleteById\" parameterType=\""+IdParamType+"\">\n"); delByIdCon.append("\t\t"+"delete from "+tableName+" where "+IdName+"= #{"+beanIdName+",jdbcType="+IdJdbcType+"}\n"); delByIdCon.append("\t"+"</delete>\n"); StringBuffer updateByIdSelCon = new StringBuffer(); updateByIdSelCon.append("\t"+"<update id=\"updateByIdSelective\" parameterType=\""+beanPackage+"."+beanName+"\">\n"); updateByIdSelCon.append("\t\t"+"update "+tableName+"\n"+"\t\t"+"<set>\n"); StringBuffer updateByIdCon = new StringBuffer(); updateByIdCon.append("\t"+"<update id=\"updateById\" parameterType=\""+beanPackage+"."+beanName+"\">\n"); updateByIdCon.append("\t\t"+"update "+tableName+" set\n"); StringBuffer countRecordCon = new StringBuffer(); countRecordCon.append("\t"+"<select id=\"countRecord\" resultType=\"java.lang.Integer\">\n"); countRecordCon.append("\t\t"+"select count(*) from "+tableName+"\n"); countRecordCon.append("\t"+"</select>\n"); StringBuffer countSelCon = new StringBuffer(); countSelCon.append("\t"+"<select id=\"countSelective\" parameterType=\""+beanPackage+"."+beanName+"\" resultType=\"java.lang.Integer\">\n"); countSelCon.append("\t\t"+"select count(*) from "+tableName+" where 1=1\n"); StringBuffer maxIdCon = new StringBuffer(); maxIdCon.append("\t"+"<select id=\"maxId\" resultType=\"java.lang.Integer\">\n"); maxIdCon.append("\t\t"+"select max("+IdName+") from "+tableName+"\n"); maxIdCon.append("\t"+"</select>\n"); StringBuffer selectByIdCon = new StringBuffer(); selectByIdCon.append("\t"+"<select id=\"selectById\" parameterType=\""+IdParamType+"\" resultMap=\"BaseResultMap\">\n"); selectByIdCon.append("\t\t"+"select\n"+"\t\t"+"<include refid=\"Base_Column_List\"/>\n"); selectByIdCon.append("\t\t"+"from "+tableName+"\n"+"\t\t"+"where "+IdName+"= #{"+beanIdName+",jdbcType="+IdJdbcType+"}\n"); selectByIdCon.append("\t"+"</select>\n"); StringBuffer selectAllCon=new StringBuffer(); selectAllCon.append("\t"+"<select id=\"selectAll\" resultMap=\"BaseResultMap\">\n"); selectAllCon.append("\t\t"+"select * from "+tableName+"\n"); selectAllCon.append("\t"+"</select>\n"); //遍历List,将字段名称和字段类型、属性名写进文件 for (int j = 0; j <columns.size(); j++) { //字段名 String columnName =columns.get(j).getColumnName(); //属性(变量)名 String attrName =NameUtil.columnName(columns.get(j).getColumnName()); //字段类型 String type=DataTypeUtil.getType(columns.get(j).getDataType());; String jdbcType =JdbcTypeUtil.getJdbcType(type); if(jdbcType=="INT"||"INT".equals(jdbcType)){ jdbcType="INTEGER"; } if(j==0){ resultMapCon.append("\t\t"+"<id column=\""+columnName+"\" property=\""+attrName+"\" jdbcType=\""+jdbcType+"\"/>\n"); baseColCon.append("\t\t"+columnName); insertRecordCon.append(columnName); insertRecordCons.append("#{"+attrName+",jdbcType="+jdbcType+"}"); }else{ resultMapCon.append("\t\t"+"<result column=\""+columnName+"\" property=\""+attrName+"\" jdbcType=\""+jdbcType+"\"/>\n"); baseColCon.append(","+columnName); insertRecordCon.append(",\n"+"\t\t\t"+columnName); insertRecordCons.append(",\n"+"\t\t\t"+"#{"+attrName+",jdbcType="+jdbcType+"}"); updateByIdSelCon.append("\t\t\t"+"<if test=\""+attrName+" != null\" >\n"+"\t\t\t\t"+columnName+"="+"#{"+attrName+",jdbcType="+jdbcType+"},\n"+"\t\t\t"+"</if>\n"); if(j==columns.size()-1){ updateByIdCon.append("\t\t\t"+columnName+"="+"#{"+attrName+",jdbcType="+jdbcType+"}\n"); }else{ updateByIdCon.append("\t\t\t"+columnName+"="+"#{"+attrName+",jdbcType="+jdbcType+"},\n"); } } insertSelCon.append("\t\t\t"+"<if test=\""+attrName+" != null\" >\n"+"\t\t\t\t"+columnName+",\n"+"\t\t\t"+"</if>\n"); insertSelCons.append("\t\t\t"+"<if test=\""+attrName+" != null\" >\n"+"\t\t\t\t"+"#{"+attrName+",jdbcType="+jdbcType+"}"+",\n"+"\t\t\t"+"</if>\n"); countSelCon.append("\t\t"+"<if test=\""+attrName+" != null\" >\n"+"\t\t\t"+"and "+columnName+"="+"#{"+attrName+",jdbcType="+jdbcType+"}\n"+"\t\t"+"</if>\n"); } resultMapCon.append("\t"+"</resultMap>\n"); baseColCon.append("\n\t"+"</sql>\n"); insertRecordCon.append(")\n"); insertRecordCons.append(")\n"+" "+"</insert>\n"); insertSelCon.append("\t\t"+"</trim>\n"); insertSelCon.append("\t\t"+"<trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\">\n"); insertSelCons.append("\t\t"+"</trim>\n"); insertSelCons.append("\t"+"</insert>\n"); updateByIdSelCon.append("\t\t"+"</set>\n"+"\t\t"+"where "+IdName+"= #{"+beanIdName+",jdbcType="+IdJdbcType+"}\n"+"\t"+"</update>\n"); updateByIdCon.append("\t\t"+"where "+IdName+"= #{"+beanIdName+",jdbcType="+IdJdbcType+"}\n"+"\t"+"</update>\n"); countSelCon.append("\t"+"</select>\n"); //拼接(Mapper.xml)文件内容 StringBuffer content=new StringBuffer(); content.append(headCon); content.append(resultMapCon); content.append(baseColCon); content.append(insertRecordCon); content.append(insertRecordCons); content.append(insertSelCon); content.append(insertSelCons); content.append(delByIdCon); content.append(updateByIdSelCon); content.append(updateByIdCon); content.append(countRecordCon); content.append(countSelCon); content.append(maxIdCon); content.append(selectByIdCon); content.append(selectAllCon); content.append("</mapper>"); FileUtil.createFileAtPath(path+"/", fileName+".xml", content.toString()); } return true; } return false; } }
package com.hwf.auto.daoImpl; import java.util.List; import com.hwf.auto.bean.ColumnStruct; import com.hwf.auto.bean.TableStruct; import com.hwf.auto.dao.GetTablesDao; import com.hwf.auto.dao.ServiceAutoDao; import com.hwf.auto.util.ConfigUtil; import com.hwf.auto.util.DataTypeUtil; import com.hwf.auto.util.FileUtil; import com.hwf.auto.util.NameUtil; /** * 生成Service接口的dao层实现类 * @author * */ public class ServiceAutoDaoImpl implements ServiceAutoDao { //从GetTablesDaoImpl中获得装有所有表结构的List GetTablesDao getTables = new GetTablesDaoImpl(); List<TableStruct> list = getTables.getTablesStruct(); //通过表名、字段名称、字段类型创建Service接口 @Override public boolean createService() { //获得配置文件的参数 //项目路径 String projectPath = ConfigUtil.projectPath; //是否生成Service String serviceFalg=ConfigUtil.serviceFlag; //Service接口的包名 String servicePackage=ConfigUtil.servicePackage; //Bean实体类的包名 String beanPackage=ConfigUtil.beanPackage; if("true".equals(serviceFalg) ){ //将包名com.xxx.xxx形式,替换成com/xxx/xxx形成 String servicePath=servicePackage.replace(".", "/"); //Service接口的路径 String path =projectPath+"/src/"+servicePath; //遍历装有所有表结构的List for (int i = 0; i < list.size(); i++) { //文件名 String fileName=NameUtil.fileName(list.get(i).getTableName())+"Service"; String beanName =NameUtil.fileName(list.get(i).getTableName())+"Bean"; //获得每个表的所有列结构 List<ColumnStruct> columns =list.get(i).getColumns(); //主键变量名(属性名) String columnName =NameUtil.columnName(columns.get(0).getColumnName()); //获得主键数据类型 String type = columns.get(0).getDataType(); //将mysql数据类型转换为java数据类型 String dateType =DataTypeUtil.getType(type); //(Service接口)文件内容 String packageCon ="package "+servicePackage+";\n\n"; StringBuffer importCon=new StringBuffer(); String className ="public interface "+fileName+"{\n\n"; StringBuffer classCon = new StringBuffer(); //生成导包内容 importCon.append("import"+" "+beanPackage+"."+beanName+";\n\n"); //有date类型的数据需导包 if("Date".equals(dateType)){ importCon.append("import java.util.Date;\n\n"); } //有Timestamp类型的数据需导包 if("Timestamp".equals(dateType)){ importCon.append("import java.sql.Timestamp;\n\n"); } importCon.append("import java.util.List;\n\n"); //生成接口方法 classCon.append("\t"+"public int insertRecord("+beanName+" record);//添加一条完整记录\n\n"); classCon.append("\t"+"public int insertSelective("+beanName+" record);//添加指定列的数据\n\n"); classCon.append("\t"+"public int deleteById("+dateType+" "+columnName+");//通过Id(主键)删除一条记录\n\n"); classCon.append("\t"+"public int updateByIdSelective("+beanName+" record);//按Id(主键)修改指定列的值\n\n"); classCon.append("\t"+"public int updateById("+beanName+" record);//按Id(主键)修改指定列的值\n\n"); classCon.append("\t"+"public int countRecord();//计算表中的总记录数\n\n"); classCon.append("\t"+"public int countSelective("+beanName+" record);//根据条件计算记录条数\n\n"); classCon.append("\t"+"public int maxId();//获得表中的最大Id\n\n"); classCon.append("\t"+"public"+"\t"+beanName+"\t"+"selectById("+dateType+"\t"+columnName+");//通过Id(主键)查询一条记录\n\n"); classCon.append("\t"+"public List selectAll();//查询所有记录\n\n"); //拼接(Service接口)文件内容 StringBuffer content=new StringBuffer(); content.append(packageCon); content.append(importCon.toString()); content.append(className); content.append(classCon.toString()); content.append("\n}"); FileUtil.createFileAtPath(path+"/", fileName+".java", content.toString()); } return true; } return false; } }
package com.hwf.auto.daoImpl; import java.util.List; import com.hwf.auto.bean.ColumnStruct; import com.hwf.auto.bean.TableStruct; import com.hwf.auto.dao.GetTablesDao; import com.hwf.auto.dao.ServiceImplAutoDao; import com.hwf.auto.util.ConfigUtil; import com.hwf.auto.util.DataTypeUtil; import com.hwf.auto.util.FileUtil; import com.hwf.auto.util.NameUtil; /** * 生成ServiceImpl实现类的dao层实现类 * @author */ public class ServiceImplAutoDaoImpl implements ServiceImplAutoDao { //从GetTablesDaoImpl中获得装有所有表结构的List GetTablesDao getTables = new GetTablesDaoImpl(); List<TableStruct> list = getTables.getTablesStruct(); //通过表名、字段名称、字段类型创建ServiceImpl实现类 @Override public boolean createServiceImpl() { //获得配置文件的参数 //项目路径 String projectPath = ConfigUtil.projectPath; //是否生成Service String serviceImplFalg=ConfigUtil.serviceImplFlag; //Service接口的包名 String serviceImplPackage=ConfigUtil.serviceImplPackage; //Bean实体类的包名 String beanPackage=ConfigUtil.beanPackage; //Service接口的包名 String servicePackage=ConfigUtil.servicePackage; //Dao接口的包名 String daoPackage=ConfigUtil.daoPackage; if("true".equals(serviceImplFalg) ){ //将包名com.xxx.xxx形式,替换成com/xxx/xxx形成 String serviceImplPath=serviceImplPackage.replace(".", "/"); //Service接口的路径 String path =projectPath+"/src/"+serviceImplPath; //遍历装有所有表结构的List for (int i = 0; i < list.size(); i++) { //文件名 String fileName=NameUtil.fileName(list.get(i).getTableName())+"ServiceImpl"; String serviceName=NameUtil.fileName(list.get(i).getTableName())+"Service"; String beanName =NameUtil.fileName(list.get(i).getTableName())+"Bean"; String daoName=NameUtil.fileName(list.get(i).getTableName())+"Dao"; //获得每个表的所有列结构 List<ColumnStruct> columns =list.get(i).getColumns(); //主键变量名(属性名) String columnName =NameUtil.columnName(columns.get(0).getColumnName()); //获得主键数据类型 String type = columns.get(0).getDataType(); //将mysql数据类型转换为java数据类型 String dateType =DataTypeUtil.getType(type); //(ServiceImpl实现类)文件内容 String packageCon ="package "+serviceImplPackage+";\n\n"; StringBuffer importCon=new StringBuffer(); String className ="public class "+fileName+"\timplements "+serviceName+"{\n\n"; StringBuffer classCon = new StringBuffer(); //生成导包内容 importCon.append("import "+servicePackage+"."+serviceName+";\n\n"); importCon.append("import"+" "+beanPackage+"."+beanName+";\n\n"); importCon.append("import"+" "+daoPackage+"."+daoName+";\n\n"); //有date类型的数据需导包 if("Date".equals(dateType)){ importCon.append("import java.util.Date;\n\n"); } //有Timestamp类型的数据需导包 if("Timestamp".equals(dateType)){ importCon.append("import java.sql.Timestamp;\n\n"); } importCon.append("import java.util.List;\n\n"); //生成Dao属性 classCon.append("\tprivate "+daoName+"\t"+ daoName+";\n\n"); classCon.append("\tpublic "+daoName+" get"+ daoName+"(){\n\t\treturn\t"+daoName+";\n\t}\n\n"); classCon.append("\tpublic "+daoName+" set"+ daoName+"("+daoName+" "+daoName+"){\n\t\treturn this."+daoName+"="+daoName+";\n\t}\n\n"); //生成实现方法 classCon.append("\t//添加一条完整记录\n"+"\tpublic int insertRecord("+beanName+" record){\n\t\treturn\t"+daoName+".insertRecord(record);\n\t}\n\n"); classCon.append("\t//添加指定列的数据\n"+"\tpublic int insertSelective("+beanName+" record){\n\t\treturn\t"+daoName+".insertSelective(record);\n\t}\n\n"); classCon.append("\t//通过Id(主键)删除一条记录\n"+"\tpublic int deleteById("+dateType+" "+columnName+"){\n\t\treturn\t"+daoName+".deleteById("+columnName+");\n\t}\n\n"); classCon.append("\t//按Id(主键)修改指定列的值\n"+"\tpublic int updateByIdSelective("+beanName+" record){\n\t\treturn\t"+daoName+".updateByIdSelective(record);\n\t}\n\n"); classCon.append("\t//按Id(主键)修改指定列的值\n"+"\tpublic int updateById("+beanName+" record){\n\t\treturn\t"+daoName+".updateById(record);\n\t}\n\n"); classCon.append("\t//计算表中的总记录数\n"+"\tpublic int countRecord(){\n\t\treturn\t"+daoName+".countRecord();\n\t}\n\n"); classCon.append("\t//根据条件计算记录条数\n"+"\tpublic int countSelective("+beanName+" record){\n\t\treturn\t"+daoName+".countSelective(record);\n\t}\n\n"); classCon.append("\t//获得表中的最大Id\n"+"\tpublic int maxId(){\n\t\treturn\t"+daoName+".maxId();\n\t}\n\n"); classCon.append("\t//通过Id(主键)查询一条记录\n"+"\tpublic"+"\t"+beanName+"\t"+"selectById("+dateType+"\t"+columnName+"){\n\t\treturn\t"+daoName+".selectById("+columnName+");\n\t}\n\n"); classCon.append("\t//查询所有记录\n"+"\tpublic List selectAll(){\n\t\treturn\t"+daoName+".selectAll();\n\t}\n\n"); //拼接(ServiceImpl实现类)文件内容 StringBuffer content=new StringBuffer(); content.append(packageCon); content.append(importCon.toString()); content.append(className); content.append(classCon.toString()); content.append("\n}"); FileUtil.createFileAtPath(path+"/", fileName+".java", content.toString()); } return true; } return false; } }
4、com.hwf.auto.util包
package com.hwf.auto.util; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * 获得properties配置文件的参数工具类 * @author * */ public class ConfigUtil { //项目路径的参数 public static String projectPath; //生成Bean实体类的参数 public static String beanFlag; public static String beanPackage; //生成Dao接口的参数 public static String daoFlag; public static String daoPackage; //生成Service接口的参数 public static String serviceFlag; public static String servicePackage; //生成Mapper.xml的参数 public static String mapperXmlFlag; public static String mapperXmlPackage; //生成ServiceImpl实现类的参数 public static String serviceImplFlag; public static String serviceImplPackage; //获取配置文件参数并加载驱动 static{ try { //得到配置文件的流信息 InputStream in = DataSourceUtil.class.getClassLoader().getResourceAsStream("config.properties"); //加载properties文件的工具类 Properties pro = new Properties(); //工具类去解析配置文件的流信息 pro.load(in); //将文件得到的信息,赋值到全局变量 projectPath = pro.getProperty("projectPath"); beanFlag =pro.getProperty("beanFlag"); beanPackage = pro.getProperty("beanPackage"); daoFlag =pro.getProperty("daoFlag"); daoPackage = pro.getProperty("daoPackage"); serviceFlag=pro.getProperty("serviceFlag"); servicePackage=pro.getProperty("servicePackage"); mapperXmlFlag =pro.getProperty("mapperXmlFlag"); mapperXmlPackage = pro.getProperty("mapperXmlPackage"); serviceImplFlag=pro.getProperty("serviceImplFlag"); serviceImplPackage=pro.getProperty("serviceImplPackage"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.hwf.auto.util; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; import javax.activation.DataSource; /** * 获得数据源工具类 * @author * */ public class DataSourceUtil { //链接数据库的参数 private static String driver; private static String url; private static String userName; private static String userPs; //操作数据库的对象 private Connection con; private Statement sta; private ResultSet rs; //获取配置文件参数并加载驱动 static{ try { //得到配置文件的流信息 InputStream in = DataSourceUtil.class.getClassLoader().getResourceAsStream("config.properties"); //加载properties文件的工具类 Properties pro = new Properties(); //工具类去解析配置文件的流信息 pro.load(in); //将文件得到的信息,赋值到全局变量 driver = pro.getProperty("jdbc.driverClass"); url = pro.getProperty("jdbc.url"); userName = pro.getProperty("jdbc.username"); userPs = pro.getProperty("jdbc.password"); //加载驱动 Class.forName(driver); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获得链接 */ private void getConnection(){ try { con=DriverManager.getConnection(url,userName,userPs); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 创建一个状态通道 */ private void createStatement(){ //获得链接的方法 this.getConnection(); try { sta =con.createStatement(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 基于状态通道的 查询方法 * @param sql * @return */ public ResultSet query(String sql){ this.createStatement(); try { rs = sta.executeQuery(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return rs; } /** * 关闭资源方法 */ public void closeRes(){ if(rs !=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(sta != null){ try { sta.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(con != null){ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package com.hwf.auto.util; import java.util.Date; import org.apache.commons.lang3.StringUtils; /** * mysql数据类型处理工具类 * @author * */ public class DataTypeUtil { public static String getType(String dataType){ String type=""; if("tinyint".equals(StringUtils.substringBefore(dataType, "("))){ type="Byte"; } if("smallint".equals(StringUtils.substringBefore(dataType, "("))){ type="Short"; } if("mediumint".equals(StringUtils.substringBefore(dataType, "("))){ type="Integer"; } if("int".equals(StringUtils.substringBefore(dataType, "("))){ type="Integer"; } if("integer".equals(StringUtils.substringBefore(dataType, "("))){ type="Integer"; } if("bigint".equals(StringUtils.substringBefore(dataType, "("))){ type="Long"; } if("bit".equals(StringUtils.substringBefore(dataType, "("))){ type="Boolean"; } if("double".equals(StringUtils.substringBefore(dataType, "("))){ type="Double"; } if("float".equals(StringUtils.substringBefore(dataType, "("))){ type="Float"; } if("decimal".equals(StringUtils.substringBefore(dataType, "("))){ type="Long"; } if("char".equals(StringUtils.substringBefore(dataType, "("))){ type="String"; } if("varchar".equals(StringUtils.substringBefore(dataType, "("))){ type="String"; } if("date".equals(StringUtils.substringBefore(dataType, "("))){ type="Date"; } if("time".equals(StringUtils.substringBefore(dataType, "("))){ type="Date"; } if("year".equals(StringUtils.substringBefore(dataType, "("))){ type="Date"; } if("timestamp".equals(StringUtils.substringBefore(dataType, "("))){ type="Timestamp"; } if("datetime".equals(StringUtils.substringBefore(dataType, "("))){ type="Timestamp"; } if("tinytext".equals(StringUtils.substringBefore(dataType, "("))){ type="String"; } if("enum".equals(StringUtils.substringBefore(dataType, "("))){ type="String"; } if("set".equals(StringUtils.substringBefore(dataType, "("))){ type="String"; } if("text".equals(StringUtils.substringBefore(dataType, "("))){ type="String"; } if("mediumtext".equals(StringUtils.substringBefore(dataType, "("))){ type="String"; } if("longtext".equals(StringUtils.substringBefore(dataType, "("))){ type="String"; } return type; } }
package com.hwf.auto.util; import java.io.*; /** * 文件读写操作工具类 * @author * */ public class FileUtil { /** *创建目录 * @param dirName 目录的路径 */ public static boolean createDir(String dirName){ File file=new File(dirName); if(!file.exists()){ if(file.mkdirs()){ return true; } } return false; } /** * 将内容写进文件 * @param filepath * @param content * @return */ public static boolean writeFileContent(String filepath,String content){ Boolean isok = false; File file =new File(filepath); if(file.exists()){ try { //以写入的方式打开文件 FileWriter fw = new FileWriter(filepath); //文件内容写入 BufferedWriter bw = new BufferedWriter(fw); bw.write(content);//向文件里面写入内容 bw.close(); fw.close(); isok=true; } catch (IOException e) { e.printStackTrace(); } } return isok; } /** *创建带内容的文件 * @param fileName 文件名 */ public static boolean createFile(String fileName,String content){ File file=new File(fileName); if(!file.exists()){ try { //创建文件并写入内容 file.createNewFile(); writeFileContent(fileName,content); return true; } catch (IOException e) { e.printStackTrace(); } } return false; } /** * 指定路径下创建带内容的文件 * @param path 路径 * @param fileName 文件名 */ public static boolean createFileAtPath(String path,String fileName,String content){ //路径不存在先创建 if(createDir(path)==true){ StringBuffer bf =new StringBuffer(path); bf.append(fileName); File file = new File(bf.toString()); if(!file.exists()){ try { //创建文件并写入内容 file.createNewFile(); writeFileContent(bf.toString(),content); return true; } catch (IOException e) { e.printStackTrace(); } } }else{//路径存在直接创建文件并写入内容 return createFile(path+"/"+fileName,content); } return false; } /** * 创建临时文件 * @param fileName 文件名 * @return */ public static File createTempFile(String fileName){ //boolean isok = false; File file = new File("temp"+fileName); if(!file.exists()){ try { file.createNewFile(); //当你退出的时候,就把我这个临时文件删除掉 file.deleteOnExit(); //isok=true; } catch (Exception e) { e.printStackTrace(); } } return file; } /** * 删除文件 * @param fileName 文件名 */ public static boolean deleteFile(String fileName){ try { //直接创建一个文件的操作对象 File file = new File(fileName); if(file.exists()){ if(file.delete()){ return true; } } } catch (Exception e) { // TODO: handle exception } return false; } }
package com.hwf.auto.util; /** * mybatis的JdbcType处理工具类 * @author * */ public class JdbcTypeUtil { public static String getJdbcType(String dataType){ String type=""; if("String".equals(dataType)){ type="VARCHAR"; } if("BigDecimal".equals(dataType)){ type="NUMERIC"; } if("boolean".equals(dataType)){ type="BOOLEAN"; } if("byte".equals(dataType)){ type="TINYINT"; } if("short".equals(dataType)){ type="SMALLINT"; } if("int".equals(dataType)){ type="INTEGER"; } if("Integer".equals(dataType)){ type="INTEGER"; } if("long".equals(dataType)){ type="BIGINT"; } if("float".equals(dataType)){ type="DOUBLE"; } if("double".equals(dataType)){ type="DOUBLE"; } if("Date".equals(dataType)){ type="DATE"; } if("Time".equals(dataType)){ type="TIME"; } if("Timestamp".equals(dataType)){ type="TIMESTAMP"; } return type; } }
package com.hwf.auto.util; /** * 名字处理工具类(文件名、变量名等) * @author * */ public class NameUtil { /** * 处理文件名 * @param tableName 数据表表名 * @return */ public static String fileName(String tableName){ String fileName=""; //获得表名 //去掉表名的下划线 String[] tablesName =tableName.split("_"); for (int j = 0; j < tablesName.length; j++) { //将每个单词的首字母变成大写 tablesName[j]=tablesName[j].substring(0,1).toUpperCase()+tablesName[j].substring(1); fileName +=tablesName[j].replace("Tb", ""); } return fileName; } /** * 处理变量名(属性名) * @param columnName 字段名称 * @return */ public static String columnName(String columnName){ //将字段名称user_name格式变成userName格式 String colName = ""; //根据下划线将名字分为数组 String[] columnsName = columnName.split("_"); //遍历数组,将除第一个单词外的单词的首字母大写 for (int h = 0; h < columnsName.length; h++) { for (int k = 1; k < columnsName.length; k++) { columnsName[k]=columnsName[k].substring(0,1).toUpperCase()+columnsName[k].substring(1); } //拼接字符串以获得属性名(字段名称) colName +=columnsName[h]; } return colName; } }
package com.hwf.auto.util; /** * mybatis的parameterType处理工具类 * @author * */ public class ParamTypeUtil { public static String getParamType(String dataType){ String type=""; if("String".equals(dataType)){ type="java.lang.String"; } if("BigDecimal".equals(dataType)){ type="java.math.BigDecimal"; } if("boolean".equals(dataType)){ type="java.lang.Boolean"; } if("byte".equals(dataType)){ type="java.lang.Byte"; } if("short".equals(dataType)){ type="java.lang.Short"; } if("int".equals(dataType)){ type="java.lang.Integer"; } if("Integer".equals(dataType)){ type="java.lang.Integer"; } if("long".equals(dataType)){ type="java.lang.Long"; } if("float".equals(dataType)){ type="java.lang.Double"; } if("double".equals(dataType)){ type="java.lang.Double"; } if("Date".equals(dataType)){ type="java.util.Date"; } if("Time".equals(dataType)){ type="java.sql.Time"; } if("Timestamp".equals(dataType)){ type="java.sql.Timestamp"; } if("List".equals(dataType)){ type="java.util.List"; } if("Map".equals(dataType)){ type="java.util.Map"; } return type; } }
5、pom.xml导入依赖
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <!-- 导入Mysql数据库链接jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> </dependency>
6、生成文件类
package com.hwf.auto.main; import com.hwf.auto.dao.*; import com.hwf.auto.daoImpl.BeanAutoDaoImpl; import com.hwf.auto.daoImpl.DaoAutoDaoImpl; import com.hwf.auto.daoImpl.MapperXmlAutoDaoImpl; import com.hwf.auto.daoImpl.ServiceAutoDaoImpl; import com.hwf.auto.daoImpl.ServiceImplAutoDaoImpl; public class MainRunner { public void generateCode(){ //1.生成Bean实体类 BeanAutoDao beanAuto = new BeanAutoDaoImpl(); if(beanAuto.createBean()){ System.out.println("所有Bean实体类生成成功"); }else{ System.out.println("所有Bean实体类生成失败"); } //2.生成Dao接口 DaoAutoDao daoAuto = new DaoAutoDaoImpl(); if(daoAuto.createDao()){ System.out.println("所有Dao接口生成成功"); }else{ System.out.println("所有Dao接口生成失败"); } //3.生成Mapper.xml MapperXmlAutoDao mapperXmlAuto=new MapperXmlAutoDaoImpl(); if(mapperXmlAuto.createMapperXml()){ System.out.println("所有Mapper.xml生成成功"); }else{ System.out.println("所有Mapper.xml生成失败"); } //4.生成Service接口 ServiceAutoDao serviceAuto = new ServiceAutoDaoImpl(); if(serviceAuto.createService()){ System.out.println("所有Service接口生成成功"); }else{ System.out.println("所有Service接口生成失败"); } //5.生成ServiceImpl实现类 ServiceImplAutoDao serviceImplAuto = new ServiceImplAutoDaoImpl(); if(serviceImplAuto.createServiceImpl()){ System.out.println("所有ServiceImpl实现类生成成功"); }else{ System.out.println("所有ServiceImpl实现类生成失败"); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub MainRunner mr=new MainRunner(); mr.generateCode(); } }