idea中新建maven web项目,完善java,resources目录:
pom.xml中添加jdbc依赖,mybatis generator的依赖和插件:
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.7</version> </dependency> </dependencies> <build> <plugins> <plugin> <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-maven-plugin --> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> </plugin> </plugins> </build>
resources目录下创建mybatis generator的配置文件generatorConfig.xml(mybatis generator配置文件默认名),内容大致如下:
<?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> <classPathEntry location="/Users/yanguobin/.m2/repository/mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar"/> <context id="mygenerator"> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatisgeneratordemodb" userId="root" password="123"> <!-- 避免同时生成 *Example类 --> <property name="nullCatalogMeansCurrent" value="true"></property> </jdbcConnection> <!-- 包名不存在时会自动生成 --> <javaModelGenerator targetPackage="com.yanguobin.pojo" targetProject="src/main/java"></javaModelGenerator> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"></sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="com.yanguobin.dao" targetProject="src/main/java"></javaClientGenerator> <!-- enable* 属性设为false,避免把其他数据库下的同名表也给生成下来 --> <table tableName="book" domainObjectName="Book" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false" selectByPrimaryKeyQueryId="false"></table> </context> </generatorConfiguration>
数据表book:
点击Add Configuration...
点击+Maven
在Command line:下输入mybatis-generator:generate -e
点击绿色三角运行,同时观察Project栏目录文件变化情况