springbootmybatis自动生成
时间: 2023-12-07 17:39:30 浏览: 135
以下是使用Spring Boot和MyBatis自动生成数据库表的步骤:
1.在pom.xml文件中添加MyBatis和MyBatis Generator的依赖:
```xml
<dependencies>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- MyBatis Generator -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
```
2.在application.properties文件中配置数据库连接信息:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3.创建实体类和Mapper接口,使用注解或XML文件配置SQL语句。
4.在resources目录下创建generatorConfig.xml文件,配置MyBatis Generator的相关信息,例如数据库连接信息、生成的实体类和Mapper接口的包名、生成的表名等。
```xml
<?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="DB2Tables" targetRuntime="MyBatis3">
<jdbcConnection driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.connectionURL}"
userId="${jdbc.userId}"
password="${jdbc.password}">
</jdbcConnection>
<javaModelGenerator targetPackage="com.example.demo.entity"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.example.demo.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="user"></table>
</context>
</generatorConfiguration>
```
5.在Maven的命令行中执行以下命令,生成实体类和Mapper接口:
```shell
mvn mybatis-generator:generate
```
6.查看生成的实体类和Mapper接口,如果有需要可以进行修改。
阅读全文