1. Prerequisites
Development environment:
- Spring Boot
- MyBatis-Plus
- Lombok
- Swagger & Knife4j
- Velocity template engine
- Database (MySQL)
Required dependencies:
existAdd the following dependencies:
<dependencies> <!-- Spring Boot Web --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis-Plus --> <dependency> <groupId></groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <!-- Lombok --> <dependency> <groupId></groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> <scope>provided</scope> </dependency> <!-- Swagger --> <dependency> <groupId></groupId> <artifactId>swagger-annotations</artifactId> <version>1.6.0</version> </dependency> <!-- Knife4j --> <dependency> <groupId></groupId> <artifactId>knife4j-springdoc-ui</artifactId> <version>2.0.6</version> </dependency> <!-- Velocity --> <dependency> <groupId></groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency> </dependencies>
2. Code generator design
Next we create a code generator that can query the table information of the database and generate corresponding code.
2.1 Configuring the Code Generator
exist, write the logic to generate code. It mainly reads table structure information from the database and generates corresponding entity classes, Mappers, Services, Controllers and other codes through Velocity templates.
package ; import .*; import .*; public class CodeGenerator { public static void main(String[] args) { // Configure database connection String url = "jdbc:mysql://localhost:3306/your_database"; String username = "root"; String password = "password"; String database = "your_database"; String tableName = "your_table"; // Get table information and generate code Map<String, Object> tableInfo = getTableInfo(url, username, password, database, tableName); generateCode(tableInfo); } public static Map<String, Object> getTableInfo(String url, String username, String password, String database, String tableName) { Map<String, Object> map = new HashMap<>(); try (Connection conn = (url, username, password)) { // Query table comments String tableQuery = "SELECT table_comment FROM information_schema.tables WHERE table_schema = ? AND table_name = ?"; try (PreparedStatement ps = (tableQuery)) { (1, database); (2, tableName); ResultSet rs = (); if (()) { ("tableComment", ("table_comment")); } } // Query field information String columnQuery = "SELECT column_name, column_type, column_comment FROM information_schema.columns WHERE table_schema = ? AND table_name = ?"; List<Map<String, String>> columns = new ArrayList<>(); try (PreparedStatement ps = (columnQuery)) { (1, database); (2, tableName); ResultSet rs = (); while (()) { Map<String, String> columnInfo = new HashMap<>(); ("columnName", ("column_name")); ("javaName", toCamelCase(("column_name"))); // Convert to Java variable name ("javaType", sqlTypeToJavaType(("column_type"))); // Convert to Java type ("comment", ("column_comment")); (columnInfo); } } ("columns", columns); ("tableName", tableName); ("entityName", toCamelCase(tableName)); } catch (SQLException e) { (); } return map; } private static String sqlTypeToJavaType(String sqlType) { sqlType = (); if (("int")) { return "Integer"; } else if (("bigint")) { return "Long"; } else if (("char") || ("text") || ("varchar")) { return "String"; } else if (("datetime") || ("timestamp")) { return "LocalDateTime"; } else if (("date")) { return "LocalDate"; } else if (("decimal") || ("double")) { return "BigDecimal"; } else { return "String"; } } private static String toCamelCase(String name) { StringBuilder result = new StringBuilder(); String[] parts = ("_"); for (int i = 0; i < ; i++) { if (i == 0) { (parts[i].toLowerCase()); } else { ((parts[i].charAt(0))).append(parts[i].substring(1).toLowerCase()); } } return (); } private static void generateCode(Map<String, Object> tableInfo) { // Read table information String entityName = (String) ("entityName"); String tableName = (String) ("tableName"); String tableComment = (String) ("tableComment"); List<Map<String, String>> columns = (List<Map<String, String>>) ("columns"); // Set Velocity configuration VelocityEngine velocityEngine = new VelocityEngine(); (); //Configuration template directory String templateDir = "path/to/your/templates"; // The path to the template file // Set the output directory String outputDir = "path/to/output"; // Output code folder path // Create Velocity context VelocityContext context = new VelocityContext(); ("package", ""); // Set the package path ("entityName", entityName); ("tableName", tableName); ("tableComment", tableComment); ("columns", columns); // Generate Entity file generateFile(velocityEngine, context, templateDir, "", outputDir + "/entity/" + entityName + ".java"); // Generate Mapper file generateFile(velocityEngine, context, templateDir, "", outputDir + "/mapper/" + entityName + ""); // Generate Service interface file generateFile(velocityEngine, context, templateDir, "", outputDir + "/service/" + entityName + ""); // Generate ServiceImpl file generateFile(velocityEngine, context, templateDir, "", outputDir + "/service/impl/" + entityName + ""); // Generate Controller file generateFile(velocityEngine, context, templateDir, "", outputDir + "/controller/" + entityName + ""); } private static void generateFile(VelocityEngine velocityEngine, VelocityContext context, String templateDir, String templateName, String outputFilePath) { // Get the template Template template = (templateDir + "/" + templateName); // Create file output stream try (FileWriter writer = new FileWriter(outputFilePath)) { // Render context data into template (context, writer); } catch (IOException e) { (); } } }
2.2 Velocity template
Entity template()
package ${}; import ; import ; import ; import ; import ; import ; import ; import ; import ; @Data @TableName("${tableName}") @ApiModel(value = "${entityName} entity") public class ${entityName} implements Serializable { private static final long serialVersionUID = 1L; @TableId @ApiModelProperty("Primary Key ID") private Long id; #foreach ($column in $columns) @ApiModelProperty("${}") private ${} ${}; #end }
Mapper template ()
package ${}; import ; import ${}.${entityName}; import ; @Mapper public interface ${entityName}Mapper extends BaseMapper<${entityName}> { }
Service template ()
package ${}; import ${}.${entityName}; import ; public interface ${entityName}Service extends IService<${entityName}> { }
ServiceImpl Template ()
package ${}; import ${}.${entityName}; import ${}.${entityName}Mapper; import ${}.${entityName}Service; import ; import ; @Service public class ${entityName}ServiceImpl extends ServiceImpl<${entityName}Mapper, ${entityName}> implements ${entityName}Service { }
Controller template()
package ${}; import ${}.${entityName}; import ${}.${entityName}Service; import .*; import ; import ; import ; import ; @RestController @RequestMapping("/${tableName}") @Api(tags = "${tableComment}") public class ${entityName}Controller { @Resource private ${entityName}Service service; @GetMapping("/list") @ApiOperation("Get all ${tableComment}") public List<${entityName}> list() { return (); } @PostMapping("/add") @ApiOperation("New ${tableComment}") public boolean add(@RequestBody ${entityName} entity) { return (entity); } @PutMapping("/update") @ApiOperation("renew ${tableComment}") public boolean update(@RequestBody ${entityName} entity) { return (entity); } @DeleteMapping("/delete/{id}") @ApiOperation("delete ${tableComment}") public boolean delete(@PathVariable Long id) { return (id); } }
3. Run the generated code
- Start the Spring Boot project and configure the database connection.
- Run
, automatically read table information from the database and generate corresponding code.
- View the generated code:
- Entity class: Entity class code that contains database table fields.
- Mapper, Service, ServiceImpl, Controller: Automatically generates interfaces and implementations for adding, deleting, modifying and checking.
4. Test interface
After starting the project, use the Swagger UI to perform interface testing. Visithttp://localhost:8080/
You can see the automatically generated interface documents, and directly add, delete, modify and check operations through Swagger's UI.
5. Summary
Through this tutorial, we use Spring Boot, MyBatis-Plus and Velocity template engines to implement an automated code generator, which can automatically generate code for adding, deleting, modifying and searching operations based on the database table structure, and integrates Lombok, Swagger and Knife4j, which greatly improves development efficiency.
This is the article about SpringBoot+MyBatis-Plus+Velocity implementing automatic code generation. For more related SpringBoot MyBatisPlus code generation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!