Home > Java > javaTutorial > body text

Detailed explanation of the design and implementation of Java Web template code generator

黄舟
Release: 2017-03-18 10:32:23
Original
2307 people have browsed it

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
Copy after login

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

  1. Parsing the command line

  2. ParsingConfiguration file

  3. Get data table information

  4. Generate configuration information

  5. 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";
Copy after login

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(), "%");
Copy after login

Through the above lines of code, the table information of the target data table has been obtained in the rs variable.

databaseMetaData.getColumnsThe 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.

##DATA_TYPECOLUMN_SIZEData length##COLUMN_NANENULLABLEDECIMAL_DIGITSREMARKSCOLUMN_DEFFinally Through the type mapping (
FieldDescription
Data type
Column name
Whether non-null is allowed
The number of decimal places
Remarks
Default value
Map typeMap

) in JavaTypeResolver and the camel case naming conversion (getCamelCaseString) in StringUtils) SQL information is converted into Java information.

File generation class FileGenerator

This class combines data into a target code file through

FreeMarker

template 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());
}
Copy after login

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

Detailed explanation of the design and implementation of Java Web template code generatorConfiguration 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
Copy after login

Running command example

java -jar JavaWebCodeGenerator.jar -configfile generatorConfig.properties -overwrite
Copy after login

Example 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!