


Detailed explanation of the design and implementation of Java Web template code generator
Cause
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 a generator for template code, development efficiency can be improved to a certain extent.
Goal
Configurable generator that generates Dao, Meta, and Service layer template codes in Java Web projects.
Code Framework
mvn archetype:generate -DgroupId=com.zju -DartifactId=JavaWebCodeGenerator -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false -DarchetypeCatalog=internal
Design Idea
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
Code design
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 -config<a href="http://www.php.cn/wiki/1313.html" target="_blank">file</a>
: 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 the SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME="tableName"
statement.
In the result set, subsequent processing generally requires the following table information columns.
) in JavaTypeResolver
and the camel case naming conversion (getCamelCaseString
) in StringUtils
) 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, List<TableColumn> columns) 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()); }Note
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 to new File("").getAbsolutePath();
Get the generation path. Project structure
Configuration file example
generatorConfig.properties
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 -overwriteExample demonstration
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!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools