This is the 12th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Mountains have peaks, the sea has the other shore, long road, there will be turn, bitter aftertaste, there will be back to gan. Don’t be defeated by the present ordeal, maybe the light is in the moment before you give up. Dream a happy dream with a happy heart. Wake up to a new day.

preface

Humans differ from animals for one reason: creating tools and being able to use them are more likely to develop tools.

In the project, for every class we create, we need to create controller Service mapper files and so on, which would be tedious to do if there were too many of them. Laziness is a human thing, tool building is human development, hence the code generator. Code generators can’t generate all code, but we can tweak them to generate the generic code we need in our project.

Open source code generators

mybatis-plus-generator

MyBatis – Plus a tool of open source, MyBatis – Plus – all the code generator can generate by default back-end, 3.5.1 track of + version more parameters, if see, can be applied to most of the scene

MagicalCoder

MagicalCoder creates a front and back interface that includes add, delete, change and check by dragging and dropping. There are different versions available now, you can try them out

Now all kinds of open source background management system

Now open source all kinds of backend management systems, including code generators, if the use of these open source frameworks, then the code generator is the most suitable.

Build your own wheel

The principle of analysis

A code generator that reads tables from a database works by connecting to the database, reading table structures from the database (there is a separate system library that manages table structures), establishing relationships between database fields and code fields, and rendering them through a written template engine.

preparation

The current wheel is created from the Test class and requires the mysql driver and freemarker template engine

<dependency> <groupId>freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.9</version> </dependency> < the dependency > < groupId > mysql < / groupId > < artifactId > mysql connector - Java < / artifactId > < version > 8.0.16 < / version > </dependency>Copy the code

Here is the core code posted, because the source code has been encapsulated, here for the sake of simplicity, all modified, here is the process of the database table to generate Entity class, can also be used in the front and back section of the code.

Connection data

Class.forName("com.mysql.cj.jdbc.Driver"); private static Connection con = DriverManager.getConnection("jdbc:mysql:///zdc_test? serverTimezone=UTC", "root", "root");Copy the code

Gets the table structure to generate code for

String tableName ="student"; String database ="zdc_test"; List<Map<String,String>> columns = new ArrayList<Map<String,String>>(); Statement stmt = con.createStatement(); String sql = "select column_name, data_type, column_key, is_nullable, column_comment from information_schema.columns where table_name='" + tableName + "'and table_schema='" + database+ "' ORDER BY ORDINAL_POSITION "; ResultSet rs = stmt.executeQuery(sql); while (rs.next()){ HashMap<String,String> map = new HashMap<String,String>(); map.put("columnName", rs.getString("column_name")); map.put("dataType", rs.getString("data_type")); map.put("isKey", isEmpty(rs.getString("column_key"))?" false":"true"); map.put("notNull", rs.getString("is_nullable").equals("YES")?" false":"true"); map.put("comment", rs.getString("column_comment")); columns.add(map); }Copy the code

Convert the database underscore field to a Java hump field and correspond the database data type to a Java data type

for (Map<String, String> column : columns) { column.put("fieldName", column2Property(column.get("columnName"))); Column. put("fieldType", columnType2FieldType(column.get("dataType"))); // Entity attribute types correspond the database data type to the Java data type column.put("fieldNote", column.get("comment")); // Field description, i.e. property description}Copy the code

Read the Freemarker template engine

Configuration configuration= new Configuration();
configuration.setObjectWrapper(new DefaultObjectWrapper());
Template template =configuration.getTemplate("entity.ftl", "UTF-8")

Copy the code

The entity. The FTL template

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ${sysFieldTableName} {

<#list sysParams as param>
    // ${param.fieldNote}
    private ${param.fieldType} ${param.fieldName};

</#list>

}
Copy the code

The Freemarker template is rendered to the corresponding class

HashMap<String, Object> map = new HashMap<>();
map.put("param",column);
map.put("sysFieldTableName","Student");

Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("StudentEntity.java"),  "UTF-8");
template.process(map,out);
out.flush();
out.close();
Copy the code

The last

Don’t want to write, byte code also don’t want to see the second time, source code here, if you want to write a wheel together to see, if you don’t write don’t need to see

Source: author: ZOUZDC links: https://juejin.cn/post/7028963866063306760 re the nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code