进行 crud 时,如果数据库字段少且简单,写对应的实体类和mapper映射文件还能接受,但是在项目中,面对及其复杂的数据库表及其字段,如果还是手写,那将是及其繁杂的
需求: 反向生成 实体类,接口,mapper.xml 映射文件
1、查看数据库表
现有两张表:husb 和 wife
2、配置环境
(1)添加依赖
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
(2)加载插件
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<!--配置文件的路径-->
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
(3)修改配置文件
<?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>
<!--数据库驱动jar -->
<classPathEntry location="F:\Maven\apache-maven-3.3.3\maven_repository\mysql\mysql-connector-java\5.1.40\mysql-connector-java-5.1.40.jar"/>
<context id="MyBatis" targetRuntime="MyBatis3">
<!--去除注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/generator?serverTimezone=GMT%2B8&useSSL=false"
userId="root"
password="123456">
</jdbcConnection>
<!--生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建 使用Maven生成在target目录下,会自动创建) -->
<javaModelGenerator targetPackage="com.xj0927.pojo"
targetProject="F:\IDEA\mybatis_generator\src\main\java">
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--生成SQLmapper文件 -->
<sqlMapGenerator targetPackage="mapper"
targetProject="F:\IDEA\mybatis_generator\src\main\resources">
</sqlMapGenerator>
<!--生成Dao文件,生成接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.xj0927.mapper"
targetProject="F:\IDEA\mybatis_generator\src\main\java">
</javaClientGenerator>
<table tableName="husb" enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
</table>
<table tableName="wife" enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
3、运行
双击运行 mybatis-generator-core
4、查看生成效果
5、启动类
扫描接口
@SpringBootApplication
@MapperScan("com.xj0927.mapper") //扫描mapper接口
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}