


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()); }
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 -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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



After actual testing, the AI ID photo generator performed well and its powerful functions are amazing. You really don’t need to worry about taking photos anymore! This sentence is rewritten as follows: Use Chuzhan AI software (the copyright and interpretation rights belong to Chuzhan AI and are only used to show the generated effect) sketch mode: Whether in daily work or business office situations, professional image is crucial . A beautiful ID photo can enhance one's professional image. ID photos generated through AI not only meet traditional photo standards, but can also restore a person's unique facial features. AI technology can intelligently identify various details such as facial contours, skin color, lighting, etc., and generate the most suitable ID photo. Whether it is appearance or temperament, it can be perfectly displayed and leave a deep first impression on people. AI generates ID photos with one click.

How to write a simple student performance report generator using Java? Student Performance Report Generator is a tool that helps teachers or educators quickly generate student performance reports. This article will introduce how to use Java to write a simple student performance report generator. First, we need to define the student object and student grade object. The student object contains basic information such as the student's name and student number, while the student score object contains information such as the student's subject scores and average grade. The following is the definition of a simple student object: public

If you are eager to find the top free AI animation art generator, you can end your search. The world of anime art has been captivating audiences for decades with its unique character designs, captivating colors and captivating plots. However, creating anime art requires talent, skill, and a lot of time. However, with the continuous development of artificial intelligence (AI), you can now explore the world of animation art without having to delve into complex technologies with the help of the best free AI animation art generator. This will open up new possibilities for you to unleash your creativity. What is an AI anime art generator? The AI Animation Art Generator utilizes sophisticated algorithms and machine learning techniques to analyze an extensive database of animation works. Through these algorithms, the system learns and identifies different animation styles

How to write a simple QR code generator through PHP QR codes have become very common in modern society. They can quickly transmit information and improve user experience. In this article, I will introduce you to how to write a simple QR code generator using PHP. 1. Install the necessary tools and libraries Before starting, we need to make sure that the following tools and libraries have been installed: PHP: Make sure that the latest version of PHP is installed. You can check the current PHP version by running the php-v command. Composer: C

Generators in PHP7: How to handle large-scale data efficiently and save memory? Overview: PHP7 introduces generators as a powerful tool in terms of large-scale data processing and memory saving. Generators are a special type of function in the PHP language. Unlike ordinary functions, generators can pause execution and return intermediate results instead of returning all results at once. This makes the generator ideal for processing large batches of data, reducing memory usage and improving processing efficiency. This article will introduce students

The concept of generator (Generator) was introduced in PHP7, which provides a method to efficiently handle large amounts of data and lazy loading. This article will start with concepts and principles, combined with specific code examples, to introduce the usage and advantages of generators in PHP7. A generator is a special function that, instead of returning all data at once, generates data on demand. When the function executes the yield statement, the currently generated value will be returned, and the function's state will be saved. The next time the generator function is called, the function will

After ChatGPT can be connected to the Internet, OpenAI also quickly introduced a code generator. With the support of this plug-in, ChatGPT can even generate its own machine learning model. Last Friday, OpenAI just announced the shocking news that ChatGPT can connect to the Internet and connect to third-party plug-ins! In addition to third-party plug-ins, OpenAI also introduced its own plug-in "Code Interpreter" and gave several special use cases: solving quantitative and qualitative mathematical problems; performing data analysis and visualization; and quickly converting file formats. In addition, Greg Brockman demonstrated that ChatGPT can also process uploaded video files. And a best-selling author named Andrew Mayne

What is the difference between iterators and generators in Python? In Python programming, iterators and generators are tools used to process iterable objects. Both of them can be used to traverse data, but there are some differences in implementation. An iterator is an object that implements the iterator protocol. The iterator object needs to contain two methods: __iter__() and __next__(). That
