Code generation method and system based on dynamic template engine

By using dynamic template engine technology, we have solved the problems of low efficiency in repetitive development, differences in code standardization, and template rigidity in existing technologies. We have achieved efficient, standardized, and automated code generation, which can adapt to changes in the technology stack, support incremental updates and version control, and improve the efficiency and quality of code generation.

CN120929071AInactive Publication Date: 2025-11-11AACAT TECHNOLOGY LTD
View PDF 5 Cites 0 Cited by

Patent Information

Application Number
CN202511453607.X
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-10-13
Publication Date
2025-11-11
Estimated Expiration
Not applicable · inactive patent

AI Technical Summary

Technical Problem

Existing technologies have not effectively solved problems such as low efficiency of repetitive development, differences in code standardization, template rigidity, lack of incremental updates, low integration of generated code, single data source dependency, static condition processing, and lack of version control mechanisms.

Method used

The code generation method based on a dynamic template engine is adopted. By acquiring metadata from multiple heterogeneous data sources, a unified intermediate representation model is constructed. Templates are dynamically loaded in combination with technology stack configuration and business type. An extended template engine is used for dynamic rendering. A difference verification mechanism is used to determine code writing. It supports template inheritance, technology stack conditional macro directives and version control directives to realize dynamic code generation and difference handling.

Benefits of technology

It enables one-click generation of complete functional modules, solving the problem of low efficiency due to repetitive coding, ensuring consistent code standards, automatically adapting to changes in the technology stack, reducing manual maintenance, supporting incremental updates and version control, and improving the efficiency and quality of code generation.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120929071A_ABST
    Figure CN120929071A_ABST
Patent Text Reader

Abstract

The invention provides a code generation method and system based on a dynamic template engine, and the method comprises the steps: 1, obtaining metadata from a multi-source heterogeneous data source, and carrying out the standardization processing of the metadata, so as to construct a unified intermediate representation model; 2, dynamically loading templates from a version control warehouse according to the technology stack configuration and the service type, the templates including a basic template, a technology stack template and a service template; 3, combining the unified intermediate representation model with the template, and performing dynamic rendering through an expanded template engine to generate an original code character string; 4, formatting the original code character string to generate a target code; and 5, judging whether the target code is written into a target file or not through a difference verification mechanism. Through the template engine technology, the problem of low repeated coding efficiency is solved, and the effect of generating a complete function module through one key is achieved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of software development tools technology, and more specifically, to a code generation method and system based on a dynamic template engine. Background Technology

[0002] The existing technology has the following defects: 1. Low efficiency of repetitive development; 2. Differences in code standard execution; 3. Limitations of existing tools: (1) Template fixation problem: such as MyBatis Generator only supports XML configuration and cannot adapt to new technologies such as GraphQL; (2) Lack of incremental updates: such as Spring Boot Starter and other existing tools generally adopt the full coverage mode and lack incremental generation algorithms; (3) Low integration of generated code: such as Spring Roo code generation requires an average of 2.3 hours of manual adjustment; 4. The closest to existing technology: Java code generation method based on fixed templates, whose defects include: single data source dependency (only supports database table structure); static condition processing (cannot automatically identify technology stack based on POM file); lack of version control mechanism (template updates require full replacement).

[0003] Patent application CN115480745A discloses a code generation method and apparatus based on a configuration file. The method includes: obtaining a set of code templates; generating code snippets corresponding to each code template on a target page based on a configuration file corresponding to each code template in the set of code templates; wherein the set of code templates consists of related code templates; the set of code templates is used to generate code for different parts of the same page; and the configuration file is used to indicate the calling rules of the interfaces contained in the corresponding code template. However, this patent cannot completely solve the existing technical problems, nor can it meet the needs of this invention. Summary of the Invention

[0004] In view of the shortcomings of the prior art, the purpose of this invention is to provide a code generation method and system based on a dynamic template engine.

[0005] The code generation method based on a dynamic template engine provided by the present invention includes: Step 1: Obtain metadata from multiple heterogeneous data sources and standardize the metadata to build a unified intermediate representation model; Step 2: Based on the technology stack configuration and business type, dynamically load templates from the version control repository. The templates include a basic template, a technology stack template, and a business template. Step 3: Combine the unified intermediate representation model with the template, and dynamically render it using an extended template engine to generate the original code string; Step 4: Format the original code string to generate the target code; Step 5: Determine whether to write the target code into the target file using a difference verification mechanism.

[0006] Preferably, the unified intermediate representation model includes a field metadata object, a technology stack feature vector, and a business rule tag group; The template supports inheritance relationships, with the business template inheriting from the technology stack template, and the technology stack template inheriting from the base template; The template engine supports technology stack conditional macro directives, which are used to determine whether to render template content based on framework type and version number conditions. The template engine supports version control commands, which are used to determine whether to render template content based on the programming language version number.

[0007] Preferably, the difference verification mechanism includes: calculating the first MD5 value of the newly generated target code; if the target file exists, calculating the second MD5 value of its content; if the first MD5 value is different from the second MD5 value, then proceeding to the AST comparison stage; The AST comparison stage includes: parsing the newly generated target code into a first AST, parsing the target file content into a second AST, comparing the first AST and the second AST, marking the difference nodes, and processing the difference nodes according to a preset strategy; The preset strategy includes: if the difference node is located in a user-marked protected area, the content in the target file is retained; if the difference node is located in an automatically generated area, the newly generated target code is used to overwrite it; if the difference node type cannot be determined, a conflict report is generated and overwriting is skipped.

[0008] Preferably, the multi-source heterogeneous data source includes at least one of the following: JDBC database connection, OpenAPI specification file, Protobuf definition file, and business rule configuration file.

[0009] Preferably, the method further includes: outputting the generated target code according to the corresponding standard directory structure based on the project build tool type; wherein the project build tool includes Maven or Gradle.

[0010] The code generation system based on a dynamic template engine provided by the present invention includes: Module M1: Acquires metadata from multiple heterogeneous data sources and standardizes the metadata to construct a unified intermediate representation model; Module M2: Dynamically loads templates from the version control repository based on the technology stack configuration and business type. The templates include a basic template, a technology stack template, and a business template. Module M3: Combines the unified intermediate representation model with the template, and dynamically renders it through an extended template engine to generate the original code string; Module M4: Formats the original code string to generate target code; Module M5: Uses a difference verification mechanism to determine whether to write the target code into the target file.

[0011] Preferably, the unified intermediate representation model includes a field metadata object, a technology stack feature vector, and a business rule tag group; The template supports inheritance relationships, with the business template inheriting from the technology stack template, and the technology stack template inheriting from the base template; The template engine supports technology stack conditional macro directives, which are used to determine whether to render template content based on framework type and version number conditions. The template engine supports version control commands, which are used to determine whether to render template content based on the programming language version number.

[0012] Preferably, the difference verification mechanism includes: calculating the first MD5 value of the newly generated target code; if the target file exists, calculating the second MD5 value of its content; if the first MD5 value is different from the second MD5 value, then proceeding to the AST comparison stage; The AST comparison stage includes: parsing the newly generated target code into a first AST, parsing the target file content into a second AST, comparing the first AST and the second AST, marking the difference nodes, and processing the difference nodes according to a preset strategy; The preset strategy includes: if the difference node is located in a user-marked protected area, the content in the target file is retained; if the difference node is located in an automatically generated area, the newly generated target code is used to overwrite it; if the difference node type cannot be determined, a conflict report is generated and overwriting is skipped.

[0013] Preferably, the multi-source heterogeneous data source includes at least one of the following: JDBC database connection, OpenAPI specification file, Protobuf definition file, and business rule configuration file.

[0014] Preferably, the system further includes: outputting the generated target code according to the corresponding standard directory structure based on the project build tool type; wherein the project build tool includes Maven or Gradle.

[0015] Compared with the prior art, the present invention has the following beneficial effects: (1) This invention solves the problem of low efficiency of repetitive coding through template engine technology, and achieves the effect of generating complete functional modules with one click; (2) This invention solves the problems of human error and inconsistent code style by using a preset template, and achieves the effect of unified code standardization; (3) This invention solves the problem of fixed code generation templates by extending the Velocity template engine and defining technology stack condition macro instructions, and achieves the effect of automatically selecting templates according to the technology stack; (4) This invention solves the problem of manually maintaining the template lifecycle through real-time hot loading technology, and realizes the effect of automatically synchronizing the template to the generation process after modification. Attached Figure Description

[0016] Other features, objects, and advantages of the present invention will become more apparent from the following detailed description of non-limiting embodiments with reference to the accompanying drawings: Figure 1 This is a diagram of the overall system architecture. Figure 2 Workflow diagram; Figure 3 This is a schematic diagram of template processing; Figure 4 This is a diagram of the incremental protection mechanism. Detailed Implementation

[0017] The present invention will now be described in detail with reference to specific embodiments. These embodiments will help those skilled in the art to further understand the present invention, but do not limit the invention in any way. It should be noted that those skilled in the art can make several changes and improvements without departing from the concept of the present invention. These all fall within the protection scope of the present invention.

[0018] Example 1 like Figure 1 This invention proposes an intelligent code generation system based on a dynamic template engine, comprising the following core technology modules and their collaborative workflow: 1. Multi-source heterogeneous data parsing subsystem 1.1 Metadata Adaptation Layer Provides pluggable data source adapters (JDBC / Swagger / OpenAPI / Protobuf).

[0019] 1.2 Standardized Processing Unit Constructing a unified intermediate representation model (UIM) includes: Field metadata objects (type, constraints, association tags); Technology stack feature vectors (framework version, dependency library hash values); Business rule tag group (validation logic, transaction propagation type); 2. Intelligent Template Engine Subsystem 2.1 Dynamic Syntax Extension Component Extending the Velocity template engine: Technology stack conditional macro instructions: #techStack(type=SpringBoot, version>=2.7) @RestControllerAdvice #end Version control instructions: #versionCheck(java>=11) record ${entity}DTO(...) #end 2.2 Template Combination Mechanism Supports template inheritance relationships: Basic template ← Technology stack template ← Business template; Provides mixin functionality to enable cross-cutting concerns (such as logs and transactions).

[0020] 3. Multidimensional decision-making subsystem 3.1 Technology Stack Adaptation Decision Tree Example of a decision path: SpringBoot → MyBatis → Lombok → PageHelper.

[0021] Generate @MapperScan annotation → Inject PageHelper pagination logic → Automatically add @Data annotation.

[0022] Based on the technology stack conditional macro `#techStack(type=SpringBoot, version>=2.7)`, a Spring Boot template is selected, which includes pre-defined annotations and pagination logic. The pagination logic is handled by the PageHelper plugin, which intercepts SQL execution, automatically adds pagination parameters, and calls `PageHelper.startPage()` to set these parameters.

[0023] 3.2 Business Rule Injection Engine Implementing the conversion of business rules into code based on a DSL parser: Rule input: validation: field: phone rules: [@Pattern(regexp="^1[3-9]\\d{9}$")] Generate code: @Pattern(regexp="^1[3-9]\\d{9}$", message="Incorrect phone number format") private String phone; 4. Layered generation architecture 4.1 Metadata Acquisition Layer Functions: JDBC metadata scanning, OpenAPI parsing, Protobuf conversion, and business rule collection.

[0024] Specific process: 4.1.1 JDBC Metadata Scanning Input: Database connection information (URL, username, password), table name to be scanned (optional).

[0025] process: a. Connect to the database via JDBC and obtain the DatabaseMetaData object.

[0026] b. Retrieve table information: getTables() retrieves a list of tables, then for each table: Call getColumns() to retrieve column information (field name, type, length, whether it can be null, etc.); Call getPrimaryKeys() to retrieve primary key information; Call getImportedKeys() to retrieve foreign key information (relationships).

[0027] c. Convert the acquired information into entity objects of the Internal Uniform Representation (UIM) (such as Table, Column, ForeignKey, etc.).

[0028] Output: Table structure metadata (including tables, fields, constraints, relationships, etc.).

[0029] 4.1.2. OpenAPI analysis Input: The path or URL of the JSON / YAML file for OpenAPI / Swagger.

[0030] process: a. Use the Swagger Parser library to parse the OpenAPI file and obtain the OpenAPI object.

[0031] b. Traverse the paths of the OpenAPI object to obtain information about each interface (path + method).

[0032] c. Extract the request parameters (query / path / header / body), response structure, error codes, etc. for each interface.

[0033] d. Convert the interface information into an API model (such as APIOperation, APIParameter, etc.) of the internal unified representation (UIM).

[0034] Output: API interface metadata (including interface path, method, parameters, response, etc.).

[0035] 4.1.3 Protobuf Conversion Input: Path to the .proto file.

[0036] process: a. Use a Protobuf parser (such as com.google.protobuf:protobuf-java) to parse .proto files.

[0037] b. Extract message definitions (field names, types, tag numbers, nesting structures, etc.) and service definitions (RPC methods).

[0038] c. Convert messages into UIM data structures (similar to table structures), and convert services into UIM API models.

[0039] Output: Metadata for structures and services defined by Protobuf.

[0040] 4.1.4 Business Rule Collection Input: Business rule configuration file (such as YAML file) or rule table in database.

[0041] process: a. Read the configuration file (such as YAML) and parse it into a business rule object.

[0042] b. Rules include: field validation rules (such as @NotNull, @Size, etc.), business logic rules (such as state transitions), and permission rules.

[0043] c. Attach the rule information to the corresponding elements of the UIM model (such as field validation rules, interface permission rules, etc.).

[0044] Output: Business rule metadata (associated with other parts of the UIM model) 4.2 Template Management Layer Features: Dynamic template loading, version control repository, syntax extension module, template inheritance system.

[0045] Specific process: 4.2.1 Dynamic Template Loading: Input: Technology stack configuration (e.g., Spring Boot + MyBatis Plus), business type (e.g., Controller, Service, etc.).

[0046] process: a. Determine the template group to be loaded based on the configuration (e.g., SpringBoot-MyBatisPlus-Controller.vm). b. Read the corresponding Velocity template file from the template repository (such as the file system or database).

[0047] c. Load the template content into memory, ready for rendering.

[0048] Output: The template object in memory.

[0049] 4.2.2 Version Control Repository: Use Git to manage template versions.

[0050] a. Template files are stored in a Git repository, with one directory or branch corresponding to each technology stack or business scenario.

[0051] b. Template modifications can be rolled back and differences compared through Git commit records.

[0052] c. When loading a template, obtain the corresponding version of the template based on the configured version tag (e.g., v1.0.0) or branch (e.g., feature / validation).

[0053] 4.2.3, Syntax Extension Module: Extend the Velocity engine with custom directives, such as #techStack and #versionCheck.

[0054] a. Implement a custom instruction parser: convert extended instructions into instructions that Velocity can recognize.

[0055] b. For example: When encountering #techStack(type=SpringBoot, version>=2.7), check whether the technology stack in the current context meets the conditions during rendering. If it does, render its content; otherwise, skip it.

[0056] c. Extended directives are implemented by inheriting the Directive class of Velocity.

[0057] 4.2.4 Template Inheritance Hierarchy: It supports template inheritance and combination.

[0058] a. Basic template: Defines a common code structure (such as class definition, package import, etc.).

[0059] b. Technology stack template: Inherit from the base template and override specific parts (such as using the Mapper template of MyBatis Plus).

[0060] c. Business Template: Inherit the technology stack template and add business-related logic (such as specific validation rules).

[0061] d. Composition can be achieved through Velocity's #include or #parse directives, or through a custom inheritance mechanism.

[0062] Data connection with the metadata collection layer: The template management layer receives a UIM object (containing metadata) from the metadata collection layer via direct method calls.

[0063] After the template is loaded, the UIM object is passed as a context to the generation core layer for rendering.

[0064] Data transfer method: When the rendering engine is called in the core layer, the UIM object is placed in the Velocity Context.

[0065] 4.3 Generating the core layer Features: Context-aware rendering, AST code formatting, MD5 difference verification, and rule injection engine.

[0066] Specific process: 4.3.1 Context-Aware Rendering: Input: Template (from template management layer), context data (UIM object + environment variables).

[0067] process: a. Initialize the Velocity engine and load templates.

[0068] b. Place the UIM object into the Velocity Context, and also add environment variables (such as project package name, author, etc.).

[0069] c. Perform template rendering to generate the original code string.

[0070] Output: The rendered code string 4.3.2 AST code formatting: Input: The rendered code string.

[0071] process: a. Use tools such as ANTLR to generate the AST (Abstract Syntax Tree) of the code.

[0072] b. Traverse the AST and adjust the format (indentation, spaces, line breaks, etc.) according to the preset code style (such as Google Java Style).

[0073] c. Regenerate the formatted AST into a code string.

[0074] Output: Formatted code.

[0075] 4.3.3 MD5 Difference Verification (First Stage of Two-Stage Verification): Input: The path to the file to be generated, and the content of the newly generated code.

[0076] process: a. If the target file does not exist, it will be generated directly.

[0077] b. If the target file exists, calculate the MD5 of the newly generated code and the MD5 of the existing file.

[0078] c. If the MD5 hashes are the same, skip the file; if they are different, proceed to the AST difference analysis stage.

[0079] Output: Files that require further analysis.

[0080] 4.3.4 Rule Injection Engine: Input: Business rules in UIM, and the current rendering context.

[0081] process: a. During template rendering, if specific markers (such as field validation) are encountered, the rule injection engine is invoked.

[0082] b. The engine generates corresponding code snippets based on the business rules configuration (such as adding the @NotNull annotation to a field).

[0083] c. Insert the code snippet into the appropriate position in the template.

[0084] Output: The complete content containing the business rule code.

[0085] Data connection with template management layer: The core layer is generated by retrieving template objects and UIM metadata from the template management layer.

[0086] During the rendering process, the templates and metadata provided by the template management layer are combined to generate code.

[0087] Data transfer: Passed via method parameters or events.

[0088] 4.4 Output Adaptation Layer Features: Incremental build mode, Maven adaptation, Gradle adaptation, CI / CD integration.

[0089] Specific process: 4.4.1 Incremental Generation Mode (Combined with Two-Stage Verification): Phase 1: MD5 verification (quickly determine if a file has been modified); For each file to be generated, calculate the MD5 value of the newly generated content.

[0090] If the target file exists, read its contents and calculate its MD5 hash.

[0091] Compare two MD5 values: Same: The file is considered unchanged, and subsequent processing is skipped.

[0092] Difference: Entering the AST analysis stage.

[0093] Phase 2: Precise AST comparison (when MD5 values ​​are different); Use tools such as ANTLR to generate ASTs for both existing file content and newly generated content.

[0094] Recursively traverse the AST nodes and perform depth comparisons (ignoring comments and formatting differences).

[0095] Mark the differences in nodes and categorize them: Change of node type (e.g., from method to field) → major change, requiring manual intervention; Node attributes change (e.g., method body content changes) → Check if it is a node that is allowed to be covered (e.g., automatically generated code marker area). Adding / deleting nodes; Differences are handled according to the strategy: If the difference node is in a user-marked "protected area" (marked by a specific annotation such as ` / / @manual-code`), the contents of the existing file are preserved.

[0096] If the difference node is in the automatically generated area, it is overwritten with the newly generated content.

[0097] If it cannot be determined, a conflict report (diff file) is generated and the overwrite is skipped.

[0098] Merged output: The code that is finally written to the file system; Based on the AST comparison results, the newly generated content is merged with the manually modified parts in the existing files.

[0099] Generate the final file and update the MD5 record (for the next comparison).

[0100] 4.4.2 Maven compatibility: Input: Project root path process: a. Parse the pom.xml file to obtain project information (package name, dependencies, etc.).

[0101] b. Store the generated code files according to the standard Maven directory structure (src / main / java, src / test / java).

[0102] c. If necessary, automatically update pom.xml (e.g., add dependencies).

[0103] 4.4.3 Gradle compatibility: Similar to Maven adaptation, but it parses the build.gradle file and stores it according to the Gradle directory structure.

[0104] 4.4.4 CI / CD Integration: Provide a command-line interface or plugin for use by Jenkins, GitLab CI, etc.

[0105] a. In a CI pipeline, execute code generation commands to generate or update code.

[0106] b. Supports the generation of reports for use in subsequent steps (such as code review).

[0107] Data connection with the generation of the core layer: The output adaptation layer obtains the generated code (which may have been formatted) and difference analysis results from the core generation layer.

[0108] Organize the code structure according to the adaptation requirements (Maven / Gradle) and write it to the file system.

[0109] Data transfer: The core generation layer passes the generated code and difference analysis result objects to the output adaptation layer.

[0110] 5. System Collaboration Workflow like Figure 2 The process is as follows: ① Metadata input → ② Feature extraction → ③ Template matching → ④ Rule injection → ⑤ Dynamic rendering → ⑥ Formatted output. (Each stage passes context objects through an event bus to ensure data consistency).

[0111] Detailed process: Phase ①: Metadata Input; User-submitted configurations include: Data source configuration (such as database connection information, OpenAPI file path, etc.); Technology stack configuration (such as Spring Boot version, ORM framework, etc.); Business rule files (such as validation-rules.yaml); Phase 2: Feature Extraction (Metadata Parsing); Metadata parsing layer execution: JDBC metadata scanning: Connect to the database, read the table structure, and extract information such as tables, fields, primary keys, and foreign keys.

[0112] OpenAPI parsing: Parses OpenAPI files to extract interface paths, request parameters, response structures, etc.

[0113] Business rule collection: Read the business rule file and parse it into internal rule objects.

[0114] Construct a unified intermediate representation model (UIM) that includes all metadata information, technology stack feature vectors, and business rule label groups.

[0115] Phase 3: Template Matching Template management tasks: Dynamic template loading: Load the corresponding template from the version control repository based on the technology stack feature vector (such as the framework version).

[0116] Check the template inheritance hierarchy, load the base template, technology stack template, and business template, and handle the inheritance relationships between the templates.

[0117] Version conflict handling: If the version required by the template is incompatible with the version configured in the technology stack (e.g., the template requires Spring Boot >= 3.0, while the project is configured to use 2.7), a version incompatibility warning will be triggered, and an attempt will be made to find a compatible template or use the default template.

[0118] Phase 4: Rule Injection The template engine receives business rules and injects them into the template context.

[0119] For example, if the business rules define verification of mobile phone numbers, the rule injection engine will add code snippets with verification annotations to the corresponding fields.

[0120] Phase 5: Dynamic Rendering The template engine combines the UIM model with the template, performs rendering, and generates the original code string.

[0121] During the rendering process, extended template directives (such as #techStack) are used for conditional checks to ensure that the generated code is adapted to the technology stack.

[0122] Phase 6: Formatted Output Output adaptation layer execution: AST code formatting: Parses the original code string into an AST (Abstract Syntax Tree), applies code style rules (such as indentation, line breaks, spaces, etc.), and generates formatted code.

[0123] Incremental generation mode: 1. MD5 Difference Verification (Quick Filtering): Calculate the MD5 value of the newly generated code and compare it with the MD5 of the target file (if it already exists). If they are the same, skip the step; otherwise, proceed to the next step.

[0124] 2. Precise AST comparison: Parse the existing file into an AST and compare it with the AST of the newly generated code, marking the differences.

[0125] 3. Smart Merge: Only overwrites parts that are not manually modified (based on protected area markings), retains manually modified parts, and generates a patch.

[0126] Output the final code to the specified directory and organize it according to the Maven / Gradle project structure.

[0127] Integration with CI / CD: Once the build is complete, the build script is triggered (such as Maven's package command).

[0128] The event bus passes context objects throughout the process. After each stage is completed, the result data is encapsulated into an event and published. The next stage subscribes to the event and processes it.

[0129] like Figure 3 This diagram illustrates template processing. The left-hand template processing module includes basic templates, technology stack templates, and business templates. It flexibly processes templates through version checks, technology stack instructions, field mapping, and rule injection. The right-hand metadata standardization module covers technology stack vectors, field metadata, validation rule tags, and API metadata. It utilizes feature extraction, table structure parsing, semantic parsing, and interface analysis to achieve standardized metadata processing. The core process, from template processing to metadata standardization, forms a complete metadata management system.

[0130] like Figure 4 Diagram of incremental protection mechanism: 1. After the template is modified, the code to be generated will be produced.

[0131] 2. Perform MD5 quick verification on these codes to ensure data integrity.

[0132] 3. Use AST (Abstract Stamping) precise comparison technology to determine file status: a. Unmodified files will skip the generation step.

[0133] b. Files that have been securely modified will be updated incrementally.

[0134] C. Conflicting files will generate a conflict report.

[0135] This process is designed to efficiently manage code updates, reduce unnecessary build operations, and quickly identify and resolve conflicts.

[0136] Example 2 Example 2 is a preferred example of Example 1.

[0137] This invention provides a code generation method based on a dynamic template engine, comprising: Step 1: acquiring metadata from multiple heterogeneous data sources and standardizing the metadata to construct a unified intermediate representation model; Step 2: dynamically loading templates from a version control repository according to the technology stack configuration and business type, wherein the templates include a basic template, a technology stack template, and a business template; Step 3: combining the unified intermediate representation model with the templates and dynamically rendering them through an extended template engine to generate a raw code string; Step 4: formatting the raw code string to generate target code; Step 5: determining whether to write the target code into a target file through a difference verification mechanism.

[0138] The unified intermediate representation model includes field metadata objects, technology stack feature vectors, and business rule tag groups; The template supports inheritance relationships, with the business template inheriting from the technology stack template, and the technology stack template inheriting from the base template; The template engine supports technology stack conditional macro directives, which are used to determine whether to render template content based on framework type and version number conditions. The template engine supports version control commands, which are used to determine whether to render template content based on the programming language version number.

[0139] The difference verification mechanism includes: calculating the first MD5 value of the newly generated target code; if the target file exists, calculating the second MD5 value of its content; if the first MD5 value is different from the second MD5 value, then proceeding to the AST comparison stage. The AST comparison stage includes: parsing the newly generated target code into a first AST, parsing the target file content into a second AST, comparing the first AST and the second AST, marking the difference nodes, and processing the difference nodes according to a preset strategy; The preset strategy includes: if the difference node is located in a user-marked protected area, the content in the target file is retained; if the difference node is located in an automatically generated area, the newly generated target code is used to overwrite it; if the difference node type cannot be determined, a conflict report is generated and overwriting is skipped.

[0140] The multi-source heterogeneous data source includes at least one of the following: JDBC database connection, OpenAPI specification file, Protobuf definition file, and business rule configuration file.

[0141] The method further includes: outputting the generated target code according to the corresponding standard directory structure based on the project build tool type; wherein the project build tool includes Maven or Gradle.

[0142] This invention provides a code generation system based on a dynamic template engine, comprising: module M1: acquiring metadata from multiple heterogeneous data sources and standardizing the metadata to construct a unified intermediate representation model; module M2: dynamically loading templates from a version control repository according to the technology stack configuration and business type, the templates including a basic template, a technology stack template, and a business template; module M3: combining the unified intermediate representation model with the templates and dynamically rendering them through an extended template engine to generate a raw code string; module M4: formatting the raw code string to generate target code; and module M5: determining whether to write the target code into a target file through a difference verification mechanism.

[0143] The unified intermediate representation model includes field metadata objects, technology stack feature vectors, and business rule tag groups; The template supports inheritance relationships, with the business template inheriting from the technology stack template, and the technology stack template inheriting from the base template; The template engine supports technology stack conditional macro directives, which are used to determine whether to render template content based on framework type and version number conditions. The template engine supports version control commands, which are used to determine whether to render template content based on the programming language version number.

[0144] The difference verification mechanism includes: calculating the first MD5 value of the newly generated target code; if the target file exists, calculating the second MD5 value of its content; if the first MD5 value is different from the second MD5 value, then proceeding to the AST comparison stage. The AST comparison stage includes: parsing the newly generated target code into a first AST, parsing the target file content into a second AST, comparing the first AST and the second AST, marking the difference nodes, and processing the difference nodes according to a preset strategy; The preset strategy includes: if the difference node is located in a user-marked protected area, the content in the target file is retained; if the difference node is located in an automatically generated area, the newly generated target code is used to overwrite it; if the difference node type cannot be determined, a conflict report is generated and overwriting is skipped.

[0145] The multi-source heterogeneous data source includes at least one of the following: JDBC database connection, OpenAPI specification file, Protobuf definition file, and business rule configuration file.

[0146] The system further includes: outputting the generated target code according to the corresponding standard directory structure based on the project build tool type; wherein the project build tool includes Maven or Gradle.

[0147] Example 3: Complex Business Rule Processing (Inventory Verification + Distributed Transactions) 1. Business rule configuration # business-rules.yaml transaction: mode: distributed retry: 3 validations: - field: operationType rules: ["@InventoryOperationValid"] custom-code: - trigger: preUpdate logic: | if (stockChange < 0) { throw new BusinessException("Insufficient Stock"); } 2. Code generation process Step 1: Select Transaction Template The system identifies distributed transaction requirements and automatically selects the Seata-compatible template: ## Transaction Aspect Template #techStack(springCloudAlibaba) @GlobalTransactional public void ${methodName}() { / / Generated service method } Step 2: Custom validation injection Generate custom validation annotations: @Target(FIELD) @Retention(RUNTIME) @Constraint(validatedBy = InventoryOperationValidator.class) public @interface InventoryOperationValid { String message() defaults to "illegal operation type"; Class<?> [] groups() default {}; Class<? extends Payload> [] payload() default {}; } Step 3: Insert Business Logic Inject pre-validation logic into the Service implementation class: @Override @Transactional public void updateStock(StockUpdateDTO dto) { / / Automatically generated verification logic if (dto.getStockChange()<0) { throw new BusinessException("Insufficient Stock"); } / / Core business logic } 3. Generated Code Features Automatically add the @GlobalTransactional annotation Generate InventoryOperationValidator validator class Error handling code conforms to the project's unified exception specification. Example 4: Incremental Generation Mode Practice 1. Initial project status; order-service / └── src / main / java / com / example / order / ├── OrderController.java (Manually modified) └── OrderService.java (System-generated) 2. System behavior; Modify the detection; Quickly identify modified files by comparing the generated file with the existing file using MD5; The differences between the generated code and the existing code are marked by comparing the generated code through AST parsing: OrderController.java - @GetMapping(" / orders") + @GetMapping(value = " / orders", produces = "application / json") public List <order>list() { ...} Security Generation Strategy Retain the manually added `produces` property; Only update the query logic within the method; Generate report output; [SAFE MODE] Skip modified file: OrderController.java.

[0148] Those skilled in the art will understand that, in addition to implementing the system, apparatus, and their modules provided by this invention in purely computer-readable program code, the same program can be implemented in the form of logic gates, switches, application-specific integrated circuits, programmable logic controllers, and embedded microcontrollers by logically programming the method steps. Therefore, the system, apparatus, and their modules provided by this invention can be considered a hardware component, and the modules included therein for implementing various programs can also be considered structures within the hardware component; alternatively, modules for implementing various functions can be considered both software programs implementing the method and structures within the hardware component.

[0149] Specific embodiments of the present invention have been described above. It should be understood that the present invention is not limited to the specific embodiments described above, and those skilled in the art can make various changes or modifications within the scope of the claims, which do not affect the essence of the present invention. Unless otherwise specified, the embodiments and features described in this application can be arbitrarily combined with each other.< / order>

Claims

1. A code generation method based on a dynamic template engine, characterized in that, include: Step 1: Obtain metadata from multiple heterogeneous data sources and standardize the metadata to build a unified intermediate representation model; Step 2: Based on the technology stack configuration and business type, dynamically load templates from the version control repository. The templates include a basic template, a technology stack template, and a business template. Step 3: Combine the unified intermediate representation model with the template, and dynamically render it using an extended template engine to generate the original code string; Step 4: Format the original code string to generate the target code; Step 5: Determine whether to write the target code into the target file using a difference verification mechanism.

2. The code generation method based on a dynamic template engine according to claim 1, characterized in that, The unified intermediate representation model includes field metadata objects, technology stack feature vectors, and business rule tag groups; The template supports inheritance relationships, with the business template inheriting from the technology stack template, and the technology stack template inheriting from the base template; The template engine supports technology stack conditional macro directives, which are used to determine whether to render template content based on framework type and version number conditions. The template engine supports version control commands, which are used to determine whether to render template content based on the programming language version number.

3. The code generation method based on a dynamic template engine according to claim 1, characterized in that, The difference verification mechanism includes: calculating the first MD5 value of the newly generated target code; if the target file exists, calculating the second MD5 value of its content; if the first MD5 value is different from the second MD5 value, then proceeding to the AST comparison stage. The AST comparison stage includes: parsing the newly generated target code into a first AST, parsing the target file content into a second AST, comparing the first AST and the second AST, marking the difference nodes, and processing the difference nodes according to a preset strategy; The preset strategy includes: if the difference node is located in a user-marked protected area, the content in the target file is retained; if the difference node is located in an automatically generated area, the newly generated target code is used to overwrite it; if the type of difference node cannot be determined, a conflict report is generated and the overwriting is skipped.

4. The code generation method based on a dynamic template engine according to claim 1, characterized in that, The multi-source heterogeneous data source includes at least one of the following: JDBC database connection, OpenAPI specification file, Protobuf definition file, and business rule configuration file.

5. The code generation method based on a dynamic template engine according to claim 1, characterized in that, The method further includes: outputting the generated target code according to the corresponding standard directory structure based on the project build tool type; wherein the project build tool includes Maven or Gradle.

6. A code generation system based on a dynamic template engine, characterized in that, include: Module M1: Acquires metadata from multiple heterogeneous data sources and standardizes the metadata to construct a unified intermediate representation model; Module M2: Dynamically loads templates from the version control repository based on the technology stack configuration and business type. The templates include a basic template, a technology stack template, and a business template. Module M3: Combines the unified intermediate representation model with the template, and dynamically renders it through an extended template engine to generate the original code string; Module M4: Formats the original code string to generate target code; Module M5: Uses a difference verification mechanism to determine whether to write the target code into the target file.

7. The code generation system based on a dynamic template engine according to claim 6, characterized in that, The unified intermediate representation model includes field metadata objects, technology stack feature vectors, and business rule tag groups; The template supports inheritance relationships, with the business template inheriting from the technology stack template, and the technology stack template inheriting from the base template; The template engine supports technology stack conditional macro directives, which are used to determine whether to render template content based on framework type and version number conditions. The template engine supports version control commands, which are used to determine whether to render template content based on the programming language version number.

8. The code generation system based on a dynamic template engine according to claim 6, characterized in that, The difference verification mechanism includes: calculating the first MD5 value of the newly generated target code; if the target file exists, calculating the second MD5 value of its content; if the first MD5 value is different from the second MD5 value, then proceeding to the AST comparison stage. The AST comparison stage includes: parsing the newly generated target code into a first AST, parsing the target file content into a second AST, comparing the first AST and the second AST, marking the difference nodes, and processing the difference nodes according to a preset strategy; The preset strategy includes: if the difference node is located in a user-marked protected area, the content in the target file is retained; if the difference node is located in an automatically generated area, the newly generated target code is used to overwrite it; if the type of difference node cannot be determined, a conflict report is generated and the overwriting is skipped.

9. The code generation system based on a dynamic template engine according to claim 6, characterized in that, The multi-source heterogeneous data source includes at least one of the following: JDBC database connection, OpenAPI specification file, Protobuf definition file, and business rule configuration file.

10. The code generation system based on a dynamic template engine according to claim 6, characterized in that, The system further includes: outputting the generated target code according to the corresponding standard directory structure based on the project build tool type; wherein the project build tool includes Maven or Gradle.

Citation Information

Patent Citations

  • Code generation method and device based on configuration file

    CN115480745A

  • Non-coverage code updating method and device, equipment and medium

    CN114924771A

  • Target code generation method based on template engine

    CN119556897A

  • Function Declaration-oriented code intelligent comparison and incremental updating method and system

    CN120491978A

  • Method and system of difference extraction of source code using syntax analysis

    JP2013257639A