In this article, we will use actual code examples to illustrate how to use MyBatis Generator (MBG) to automatically generate the entity classes, Mapper interfaces, and Mapper XML files required for the MyBatis project.
We will use a Maven plugin to perform code generation and provide detailed configuration and explanation.
1. Introduction to MyBatis Generator
MyBatis Generator (MBG for short) is a tool provided by MyBatis, aiming to automatically generate the code required for MyBatis through the database table structure, including Java entity classes (Models), Mapper interfaces, and Mapper XML files. Using MBG can greatly reduce the repetitive work of developers when performing CRUD operations, and improve development efficiency and code consistency.
2. Functions of MyBatis Generator
MBG mainly provides the following functions:
- Generate Java entity class (Model): Automatically generate corresponding Java classes based on the structure of the database table, and the fields of the class and the columns of the database table are one by one.
- Generate Mapper interface: Generate a corresponding Mapper interface for each database table, and the interface contains common CRUD methods.
- Generate MyBatis mapping file (Mapper XML): According to the database table structure, an XML mapping file corresponding to the Mapper interface method is automatically generated, which contains the definition of SQL statements.
3. Advantages of using MyBatis Generator
- Save time and energy: By automatically generating code, reducing duplication of work, developers can spend more time focusing on the implementation of business logic.
- Reduce errors: The automatically generated code follows certain specifications and templates, avoiding spelling errors and irregularities during manual writing.
- Improve consistency: The generated code is very unified in structure and format, which is convenient for team collaboration and code maintenance.
- Flexibility and scalability:MBG provides rich configuration options, and can customize generated code according to project needs, including field type mapping, SQL statement generation rules, etc.
4. MyBatis Generator configuration and usage examples
4.1 Maven plug-in configuration
First, we need toAdd configuration for the MyBatis Generator plug-in.
Here is a typical Maven configuration segment:
<plugin> <groupId></groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.4.0</version> <configuration> <!-- Specify MyBatis Generator Configuration file --> <configurationFile>src/main/resources/</configurationFile> <!-- If you need to overwrite existing code,set up overwrite for true --> <overwrite>true</overwrite> <!-- Display detailed logs during the generation process --> <verbose>true</verbose> </configuration> <dependencies> <!-- Add database connection dependencies,like MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> </dependencies> </plugin>
-
configurationFile
: Specify the configuration file path of the MyBatis Generator. -
overwrite
: If set totrue
, then the existing generated files are allowed to be overwritten. -
verbose
: If set totrue
, more process logs will be output for easy debugging.
4.2 MyBatis Generator Configuration File
Next is the core configuration file of MyBatis Generator, When configuring the basic settings of the generator, you need to pay attention to the following important configurations:
Database connection, generated Java classes, Mapper classes and XML file configuration. The following is the specific content of this configuration file:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-////DTD MyBatis Generator Configuration 1.0//EN" "/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context targetRuntime="MyBatis3" defaultModelType="flat"> <!-- Automatically check the database keywords and add backquotes,Avoid conflicts with database keywords --> <property name="autoDelimitKeywords" value="true"/> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <!-- Plug-in configuration:Enhanced XML Mergerability --> <plugin type=""/> <!-- Plug-in configuration:Automatically generated toString() method --> <plugin type=""/> <!-- Configure comment generation policy,Select not to generate comments here --> <commentGenerator> <property name="suppressAllComments" value="true"/> </commentGenerator> <!-- Configure database connections,Modify the connection information to the actual database --> <jdbcConnection driverClass="" connectionURL="jdbc:mysql://localhost:3306/train?characterEncoding=UTF8&amp;allowPublicKeyRetrieval=true&amp;useSSL=false&amp;serverTimezone=Asia/Shanghai" userId="train" password="123456"> </jdbcConnection> <!-- Configure the generated entity class location --> <javaModelGenerator targetProject="../member/src/main/java" targetPackage=""/> <!-- Configuration generated SQL Map file location --> <sqlMapGenerator targetProject="../member/src/main/resources" targetPackage="mapper"/> <!-- Configuration generated Mapper Class Location --> <javaClientGenerator targetProject="../member/src/main/java" targetPackage="" type="XMLMAPPER"/> <!-- Select the database table to generate the code --> <table tableName="passenger" domainObjectName="Passenger"/> </context> </generatorConfiguration>
4.3 Configuration item description
-
jdbcConnection
: Configure database connection information, including the database URL, username, password, etc. -
javaModelGenerator
: Configure the storage location of the generated Java entity class. -
sqlMapGenerator
: Configure the storage location of the generated SQL map files. -
javaClientGenerator
: Configure the location of the generated Mapper interface class. -
table
: Specifies the database table to generate the code, which can be configured multiple times to support multiple tables.
4.4 Execute MyBatis Generator to generate code
After the configuration is complete, code generation can be performed through Maven.
Run the following command from the command line (or double-click to execute in the Maven plugin):
mvn mybatis-generator:generate
After execution, MyBatis Generator will automatically generate the corresponding Java entity class according to the configuration file.Example
Classes (for complex queries), Mapper interfaces, and Mapper XML files.
The generated file structure is roughly as follows:
src/main/java └── com └── stu └── train └── member └── domain └── <-- Generated entity class └── <-- Generated auxiliary class └── mapper └── <-- Generated Mapper interface src/main/resources └── mapper └── <-- Generated XML Mapping files
The code automatically generated by MyBatis Generator includes the following parts:
-
Entity class (
): Corresponding to each column of the database table, it usually contains basic fields, getters, and setter methods.
-
Example
kind(): Used to build dynamic query conditions, and supports chain calls to add query conditions, sorting, paging, etc.
-
Mapper interface (
): Define methods to interact with the database, such as adding, deleting, modifying, and checking.
-
Mapper XML file (
): The corresponding method of the Mapper interface is written and SQL query statements are written.
4.5 Generated code examples
(Entity Class)
public class Passenger { 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; } }
(Mapper interface)
public interface PassengerMapper { int deleteByPrimaryKey(Integer id); int insert(Passenger record); Passenger selectByPrimaryKey(Integer id); int updateByPrimaryKey(Passenger record); List<Passenger> selectByExample(PassengerExample example); }
(Mapper map file)
<mapper namespace=""> <!-- Query a single passenger --> <select resultType=""> SELECT id, name, age FROM passenger WHERE id = #{id} </select> <!-- Insert passenger --> <insert parameterType=""> INSERT INTO passenger (name, age) VALUES (#{name}, #{age}) </insert> <!-- Delete passengers --> <delete parameterType=""> DELETE FROM passenger WHERE id = #{id} </delete> <!-- Update passengers --> <update parameterType=""> UPDATE passenger SET name = #{name}, age = #{age} WHERE id = #{id} </update> </mapper>
(Example class)
PassengerExample
Classes are used to build SQL query conditions. It usually contains an inner classCriteria
, used to define specific query conditions.
The following is onePassengerExample
Example of generated code:
public class PassengerExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public PassengerExample() { oredCriteria = new ArrayList<>(); } // Set the sorting field public void setOrderByClause(String orderByClause) { = orderByClause; } public String getOrderByClause() { return orderByClause; } // Set whether to re-release query public void setDistinct(boolean distinct) { = distinct; } public boolean isDistinct() { return distinct; } // Get all query conditions public List<Criteria> getOredCriteria() { return oredCriteria; } // Add query conditions public void or(Criteria criteria) { (criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); (criteria); return criteria; } // Create query conditions public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (() == 0) { (criteria); } return criteria; } protected Criteria createCriteriaInternal() { return new Criteria(); } // Clear query conditions public void clear() { (); orderByClause = null; distinct = false; } public static class Criteria { protected List<Criterion> criteria; protected Criteria() { criteria = new ArrayList<>(); } // Determine whether the conditions are valid public boolean isValid() { return () > 0; } // Get all conditions public List<Criterion> getAllCriteria() { return criteria; } // Add a single condition public void addCriterion(String condition) { (new Criterion(condition)); } public void addCriterion(String condition, Object value, String property) { (new Criterion(condition, value)); } public void addCriterion(String condition, Object value1, Object value2, String property) { (new Criterion(condition, value1, value2)); } // For example, add condition: id = ? public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return this; } // For example, add condition: name like ? public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return this; } // ...More query conditions methods } // Used to represent a condition public static class Criterion { private String condition; private Object value; private Object secondValue; public Criterion(String condition) { = condition; } public Criterion(String condition, Object value) { this(condition); = value; } public Criterion(String condition, Object value, Object secondValue) { this(condition, value); = secondValue; } public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } } }
4.6 Dynamic query using the Example class
usePassengerExample
When a class conducts dynamic query, it can be passedCriteria
Class to set query conditions and then pass to the Mapper method.
For example:
PassengerExample example = new PassengerExample(); criteria = (); ("%John%"); // Query the record in the name field containing "John"(20); // Query records with age greater than 20 List<Passenger> passengers = (example);
In this example, we usePassengerExample
andCriteria
A dynamic SQL query is constructed, which contains two conditions:
-
name
The field contains "John". -
age
Fields greater than 20.
Finally, use(example)
Perform a query operation.
Summarize
Through the configuration and usage examples of MyBatis Generator, we can quickly generate entity classes, Mapper interfaces, and XML mapping files based on database tables, greatly improving development efficiency.
The above code example shows how to configure MyBatis Generator in a Maven project and generate corresponding code in combination with the actual database table. Through custom configuration files, we can control the generated code style, storage location and generated content, further improving the degree of automation and consistency of the code.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.