MyBatis Generator is a powerful code generation tool that can help developers automatically generate Java Beans, Mapper interfaces and XML files corresponding to database tables. This article will introduce in detail how to configure and use MyBatis Generator, and provide specific code examples to help readers quickly get started with the tool.
1. Configure MyBatis Generator
Add MyBatis Generator dependency in the project’s pom.xml file:
<dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.0</version> </dependency>
Create MyBatis Generator's configuration file (generatorConfig.xml), configure generation rules, database connection information, etc.:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="MyBatisGenerator" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="password"/> <javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java"/> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/> <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/> <table tableName="user" domainObjectName="User"/> </context> </generatorConfiguration>
Configure the Maven plug-in and execute MyBatis Generator:
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.4.0</version> <configuration> <configurationFile>src/main/resources/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin>
2. Use MyBatis Generator
to run the Maven plug-in to generate code:
Execute the following command in the project root directory:
mvn mybatis-generator:generate
Use the generated Mapper interface:
// 自动注入生成的Mapper接口 @Autowired private UserMapper userMapper; // 调用Mapper接口方法 User user = new User(); user.setId(1); user.setName("Test"); userMapper.insert(user);
Through the above configuration and usage method, Developers can quickly generate and use the Java Beans, Mapper interfaces and XML files corresponding to MyBatis, improving development efficiency and reducing duplication of work. I hope this article will help readers understand and use MyBatis Generator.
The above is the detailed content of MyBatis Generator configuration details and usage guide. For more information, please follow other related articles on the PHP Chinese website!