SoFunction
Updated on 2025-05-22

One article teaches you how to quickly build project skeletons in Java

In the process of Java project development, building a project skeleton is a tedious but basic and important task. Fortunately, there are many code generation tools in the Java field that can help us quickly complete this task and greatly improve development efficiency.

1. Overview of code generation tools

Introduction to commonly used Java code generation tools

Generator

MyBatis Generator is a code generation tool designed for the MyBatis framework. It can automatically generate corresponding Mapper interface, XML mapping files, entity classes and other codes based on the database table structure. For example, when we have a "users" table that contains fields such as "id", "name", "age", etc., using MyBatis Generator, we can quickly generate the User entity class, which contains these fields and corresponding getter and setter methods; at the same time, we generate the UserMapper interface, which will include basic database operation method declarations such as insert, delete, update, select, and other basic files, as well as corresponding files, which are used to write MyBatis mapping SQL statements.

Initializr

Spring Initializr is an online project initialization tool provided by Spring. It can help developers quickly generate Spring Boot-based project skeletons. We only need to select the basic information of the project on the web page, such as project name, version, dependencies (such as Spring Web, Spring Data JPA, etc.), and then click the Generate button to download a complete project directory structure, which contains the build file (such as Maven or Gradle), basic configuration file (), main program entry class, etc.

(As a code generation template engine)

FreeMarker is a template-based code generation tool. It itself is not designed specifically for Java code generation, but it can be flexibly used in code generation scenarios in combination with Java programs. For example, we can define a set of code templates, such as templates for Java service classes, and specify the structure of the class, the format of the method, etc. Then, the database table information or other metadata is read through a Java program, and the data is filled into the FreeMarker template, and the corresponding Java code file can be generated, such as generating fields of the entity class based on the table fields and related operation methods.

Advantages of Code Generation Tools

1. Improve development efficiency

Reduces the workload of manually writing repetitive and patterned code. For example, for database persistence layer code, such as entity classes, Mapper interfaces, etc., it can be generated instantly through code generation tools, and manually writing these codes may take a lot of time and effort and are prone to errors.

2. Ensure code consistency

Generating code according to a unified template ensures consistency in code style, structure and naming specifications. This is especially important for team development and helps improve the readability and maintainability of the code.

2. Use MyBatis Generator to build the project skeleton

Build MyBatis Generator environment

1. Add dependencies

If we build the project using Maven, add the MyBatis Generator dependency to the project's file:

<dependency>
    <groupId></groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.4.1</version>
</dependency>

2. Configure the MyBatis Generator configuration file

Create a file to configure database connection information, target locations, templates, etc. The example configuration is as follows:

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE generatorConfiguration
  PUBLIC "-////DTD MyBatis Generator Configuration 1.0//EN"
  "/dtd/mybatis-generator-config_1_0.dtd"&gt;

&lt;generatorConfiguration&gt;
  &lt;!-- Database connection information --&gt;
  &lt;context  targetRuntime="MyBatis3Simple"&gt;
    &lt;jdbcConnection driverClass=""
                    connectionURL="jdbc:mysql://localhost:3306/your_database"
                    userId="root"
                    password="password"&gt;
    &lt;/jdbcConnection&gt;

    &lt;!-- The target location of the generated entity class and other code --&gt;
    &lt;javaModelGenerator targetPackage="" targetProject="src/main/java"&gt;
    &lt;/javaModelGenerator&gt;

    &lt;sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"&gt;
    &lt;/sqlMapGenerator&gt;

    &lt;javaClientGenerator type="XMLMAPPER" targetPackage="" targetProject="src/main/java"&gt;
    &lt;/javaClientGenerator&gt;

    &lt;!-- Specify the database table to generate the code --&gt;
    &lt;table tableName="users" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"&gt;
    &lt;/table&gt;
  &lt;/context&gt;
&lt;/generatorConfiguration&gt;

Run MyBatis Generator to generate code

1. Write a Java program that runs the code

Create a Java class, use the MyBatis Generator API to load the configuration file and generate the code:

import ;
import ;
import ;
import ;

import ;
import ;
import ;

public class Generator {
    public static void main(String[] args) {
        List<String> warnings = new ArrayList<>();
        boolean overwrite = true;
        File configFile = new File("");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = null;
        try {
            config = (configFile);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            (null);
        } catch (Exception e) {
            ();
        }

        for (String warning : warnings) {
            (warning);
        }
    }
}

2. View the generated code

After running the above Java program, the User entity class, UserMapper interface and files will be automatically generated at the specified target location. For example, the User entity class code is as follows:

public class User {
    private Integer id;

    private String name;

    private Integer age;

    // getter and setter methods    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
         = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
         = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
         = age;
    }
}

3. Use Spring Initializr to build project skeleton

Operation on Spring Initializr webpage

1. Visit the Spring Initializr URL

Open the browser and access/

2. Fill in the basic project information

Fill in the basic information about the project on the page, such as Group (the project's Maven GroupId), Artifact (the project's Maven ArtifactId, usually the project name), Version (the project version), Project Metadata (the project metadata, such as name, description, etc.).

Select the build tools used by the project, such as Maven or Gradle, and the Java version.

3. Add dependencies

Click the “Dependencies” drop-down menu to select the required dependencies. For example, if we want to build a web application, select "Spring Web"; if we need to operate a relational database, add "Spring Data JPA" and the corresponding database driver dependencies (such as "MySQL Driver").

4. Generate project

After clicking the “Generate” button, the website will generate a compressed package. After downloading and decompressing, we can get a complete Spring Boot project skeleton.

View the generated project structure

1. Build the file

For Maven projects, the generated file contains all selected dependencies. For example, some of the contents after adding Spring Web and Spring Data JPA and MySQL Driver dependencies are as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0" xmlns:xsi="http:///2001/XMLSchema-instance"
    xsi:schemaLocation="/POM/4.0.0 /xsd/maven -4.0.">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId></groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId></groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <>17</>
    </properties>
    <dependencies>
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</project>

2. Main program entry class

The generated main program entry class is very simple, including a main method, which starts the application through the () method of Spring Boot. The sample code is as follows:

import ;
import ;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        (, args);
    }

}

4. Use FreeMarker to build project skeleton

Introducing FreeMarker dependencies

Maven dependency configuration

Add FreeMarker dependencies to the project's file:

<dependency>
    <groupId></groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.32</version>
</dependency>

Create a code generation template

Define entity class template ()

For example, the following is a simple entity class template for generating Java entity class code from table fields:

package ${package}.entity;

public class ${className} {
    <#list  as column>
    // ${}
    private ${} ${};

    public ${} get${}() {
        return this.${};
    }

    public void set${}(${} ${}) {
        this.${} = ${};
    }
    </#list>
}

Generate code in combination with Java programs

1. Read database table information

Write a Java program to read the metadata of the database table through JDBC or other database access methods, including table name, field name, field type, field comment and other information. This information is then encapsulated into a data model for filling into the FreeMarker template.

.2 Use FreeMarker to generate code

The sample code is as follows:

import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;

public class CodeGenerator {
    public static void main(String[] args) {
        // Configure FreeMarker        Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
        try {
            // Set the directory where the template file is located            (new File("templates"));
            // Loading template            Template template = ("");
            // Create a data model            Map&lt;String, Object&gt; dataModel = new HashMap&lt;&gt;();
            ("package", "");
            ("className", "User");
            ("table", getTableInfo());
            // Output code            Writer out = new FileWriter(new File("src/main/java/com/example/entity/"));
            (dataModel, out);
            ();
        } catch (IOException | TemplateException e) {
            ();
        }
    }

    // Simulate the method of obtaining table information    public static Table getTableInfo() {
        Table table = new Table();
        ("users");
        // Add field information        Column column1 = new Column();
        ("id");
        ("Integer");
        ("id");
        ("Id");
        ("User ID");

        Column column2 = new Column();
        ("name");
        ("String");
        ("name");
        ("Name");
        ("User Name");

        Column column3 = new Column();
        ("age");
        ("Integer");
        ("age");
        ("Age");
        ("User Age");

        (new Column[]{column1, column2, column3});
        return table;
    }

    // Table class is used to encapsulate table information    public static class Table {
        private String name;
        private Column[] columns;

        // getter and setter methods        public String getName() {
            return name;
        }

        public void setName(String name) {
             = name;
        }

        public Column[] getColumns() {
            return columns;
        }

        public void setColumns(Column[] columns) {
             = columns;
        }
    }

    // The Column class is used to encapsulate field information    public static class Column {
        private String name;
        private String javaType;
        private String javaField;
        private String javaCap;
        private String comments;

        // getter and setter methods        public String getName() {
            return name;
        }

        public void setName(String name) {
             = name;
        }

        public String getJavaType() {
            return javaType;
        }

        public void setJavaType(String javaType) {
             = javaType;
        }

        public String getJavaField() {
            return javaField;
        }

        public void setJavaField(String javaField) {
             = javaField;
        }

        public String getJavaCap() {
            return javaCap;
        }

        public void setJavaCap(String javaCap) {
             = javaCap;
        }

        public String getComments() {
            return comments;
        }

        public void setComments(String comments) {
             = comments;
        }
    }
}

In this way, the corresponding Java entity class code can be generated according to the database table structure. For example, the User entity class code generated based on the above code is as follows:

package ;

public class User {
    // User ID    private Integer id;

    // User name    private String name;

    // User age    private Integer age;

    public Integer getId() {
        return ;
    }

    public void setId(Integer id) {
         = id;
    }

    public String getName() {
        return ;
    }

    public void setName(String name) {
         = name;
    }

    public Integer getAge() {
        return ;
    }

    public void setAge(Integer age) {
         = age;
    }
}

5. Comparison of different code generation tools

Function comparison

Generator

It is mainly aimed at the MyBatis persistence layer framework, and the function focuses on generating MyBatis-related code based on database tables, such as entity classes, Mapper interfaces, XML mapping files, etc. There is limited support for non-MyBatis projects or code generation that does not involve database operations.

Initializr

It is mainly used to quickly generate the initial skeleton of Spring Boot project, focusing on the overall construction of the project, including construction files, main program entry class, etc., but the generation ability of specific business codes (such as entity classes, service classes, etc.) within the project is weak, and the developer needs to further manually code.

(In combination with Java programs)

It has high flexibility and can customize templates according to your needs and generate various types of code. Not only can Java code be generated, but configuration files, HTML pages, etc. However, developers need to write code to read metadata (such as database table information) and logic to process templates themselves, which is relatively expensive to develop.

Ease of use comparison

Generator

For developers familiar with MyBatis and database operations, configuration and use are relatively simple. You only need to write a configuration file and generate code through simple runs. But some XML configuration knowledge is required to set various details of code generation.

Initializr

It provides a very friendly web interface, which can be easily used by even beginners. Just fill in the basic project information and select dependencies, and click the Generate button to get the project skeleton. When used locally, there are also corresponding Maven and Gradle plug-ins for easy integration into the development environment.

(In combination with Java programs)

It is relatively complicated to use. You need to first learn the template syntax of FreeMarker, and also develop supporting Java programs to read data and process templates. However, once you master the basic principles and development models, you can flexibly use them in various code generation scenarios.

6. Summary and Outlook

Java code generation tools provide great convenience for us to quickly build project skeletons. MyBatis Generator performs excellently in persistent layer code generation; Spring Initializr is a powerful tool for building Spring Boot projects; FreeMarker provides flexible and customized code generation methods. In actual project development, we can choose appropriate code generation tools based on the project's technical selection and specific needs, or combine multiple tools to efficiently complete the construction of the project skeleton. With the continuous development of technology, future code generation tools may be more intelligent and automated, able to better understand business logic, generate higher-quality and more in line with actual needs, and further improve the efficiency and quality of software development.

This is the article about this article teaching you how to quickly build a project skeleton in Java. For more related content on building a project skeleton in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!