In the project, a lot of Meta, Dao, and Service codes need to be written based on database tables, and many of them are repetitive and cumbersome. Therefore, if there is ageneratorfor template code, development efficiency can be improved to a certain extent.
Configurable generator that generates Dao, Meta, and Service layer template codes in Java Web projects.
mvn archetype:generate -DgroupId=com.zju -DartifactId=JavaWebCodeGenerator -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false -DarchetypeCatalog=internal
The project refers to the process of generating code with Mybatis generator. The specific steps are divided into the following 5 steps.
Logical steps
Parsing the command line
ParsingConfiguration file
Get data table information
Generate configuration information
Generate file
Command parsing class ShellRunner
This class is responsible for parsing command line commands, parsing configuration files and encapsulating the required data to Code generation class.
The parsable commands include-configfile
: specify the path where the configuration file is located and-overwrite
: whether to rewrite the target file.
The configuration items of the configuration file are:
//Java SQL 驱动所在路径(暂未使用) private static final String CLASS_PATH_ENTRY = "class.path.entry"; //Java 驱动类型(暂未使用) private static final String DRIVER_CLASS = "driver.class"; //数据库地址 private static final String CONNECTION_URL = "connection.url"; //数据库用户名 private static final String USER_ID = "user.id"; //数据库密码 private static final String USER_PASSWORD = "user.password"; //模型生成地址 private static final String JAVA_MODEL_PACKAGE = "java.model.package"; //SQL生成地址 private static final String SQL_MAPPING_PACKAGE = "sql.mapping.package"; //项目地址 private static final String PROJECT = "project"; //数据表名 private static final String TABLE_NAME = "table.name"; //模型名称 private static final String DOMAIN_OBJECT_NAME = "domain.object.name";
Code generation class CodeGenerator
This class is responsible for connecting to the database, querying the table information of the data table, and SQL types are mapped to Java types and encapsulate the required data to file generation classes.
Class.forName(configuration.getDriverClass()); //获取数据库连接 Connection connection = DriverManager.getConnection(configuration.getConnectionURL(), configuration.getUserId(), configuration.getPassword()); DatabaseMetaData databaseMetaData = connection.getMetaData(); //获取表结构信息 ResultSet rs = databaseMetaData.getColumns("", "", configuration.getTableName(), "%");
Through the above lines of code, the table information of the target data table has been obtained in the rs variable.
databaseMetaData.getColumns
The essence of the method is to execute theSELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME="tableName"
statement.
In the result set, subsequent processing generally requires the following table information columns.
) inJavaTypeResolver
and the camel case naming conversion (getCamelCaseString
) inStringUtils
) SQL information is converted into Java information.
This class combines data into a target code file through
FreeMarkertemplate engine.The main logic is as follows:
/** * @param configuration 封装的配置信息 * @param columns 封装的数据表列信息 * @throws IOException * @throws TemplateException */ public static void writeFile(Configuration configuration, Listcolumns) throws IOException, TemplateException { File r=new File(""); //测试环境获取项目根目录路径 //String path=Class.class.getClass().getResource("/").getPath(); //Jar包获取根目录路径 String path=r.getAbsolutePath(); //System.out.println("path:"+path); Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(new File(path + "/ftl")); //需要文件夹绝对路径 cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); Map root = new HashMap(); root.put("configuration", configuration); root.put("columnList", columns); writeSingleFile(cfg, root, "DaoImpl.ftl", configuration.getProjectPath(), configuration.getSqlMappingPackage().replace(".", "/"), configuration.getDomainObjectName(), "DaoImpl.java",configuration.getOverwrite()); writeSingleFile(cfg, root, "Dao.ftl", configuration.getProjectPath(), configuration.getSqlMappingPackage().replace(".", "/"), configuration.getDomainObjectName(), "Dao.java",configuration.getOverwrite()); writeSingleFile(cfg, root, "Meta.ftl", configuration.getProjectPath(), configuration.getJavaModelPackage().replace(".", "/"), configuration.getDomainObjectName(), ".java",configuration.getOverwrite()); }
In the test,
Class.class.getClass().getResource("/" ).getPath();This method can obtain the project root directory, but when testing the generated Jar package, this method is timely. Therefore, before generating the Jar package, you need to modify this line tonew File("").getAbsolutePath();
Get the generation path.Project structure
Configuration file example
class.path.entry=src/test/resources/mysql-connector-java-5.1.38.jar driver.class=com.mysql.jdbc.Driver connection.url=jdbc:mysql://localhost:3307/work user.id= user.password= java.model.package=com.model sql.mapping.package=com.dao project=src table.name=holiday domain.object.name=Holiday
Running command example
java -jar JavaWebCodeGenerator.jar -configfile generatorConfig.properties -overwrite
The above is the detailed content of Detailed explanation of the design and implementation of Java Web template code generator. For more information, please follow other related articles on the PHP Chinese website!