Mybatis 代码生成器(集成通用Mapper)
0、确保通用Mapper被正确配置
1、pom.xml追加
<properties> <targetJavaProject>${basedir}/src/main/java</targetJavaProject> <targetResourcesProject>${basedir}/src/main/resources </targetResourcesProject> <!-- MyBatis Generator mapper接口的生成位置 --> <targetMapperPackage>com.spldeolin.demoapp.dao</targetMapperPackage> <!-- MyBatis Generator model类的生成位置 --> <targetModelPackage>com.spldeolin.demoapp.po</targetModelPackage> <!-- MyBatis Generator mapper.xml生成位置 --> <targetXMLPackage>mapper</targetXMLPackage> </properties>
<!--Mybatis Generator--> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <configuration> <configurationFile> ${basedir}/src/main/resources/mybatis/generator-config.xml </configurationFile> <overwrite>false</overwrite> <verbose>true</verbose> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.43</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.4.6</version> </dependency> </dependencies> </plugin>
2、追加代码生成器配置文件
generator-config.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> <properties resource="mybatis/db.properties" /> <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <property name="beginningDelimiter" value="`" /> <property name="endingDelimiter" value="`" /> <plugin type="tk.mybatis.mapper.generator.MapperPlugin"> <!--自定义通用Mapper接口,将来所有生成的mapper接口都会继承这个接口--> <property name="mappers" value="com.spldeolin.demoapp.component.Mapper" /> </plugin> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"> </jdbcConnection> <javaModelGenerator targetPackage="${targetModelPackage}" targetProject="${targetJavaProject}" /> <sqlMapGenerator targetPackage="${targetXMLPackage}" targetProject="${targetResourcesProject}" /> <javaClientGenerator targetPackage="${targetMapperPackage}" targetProject="${targetJavaProject}" type="XMLMAPPER" /> <table tableName="%"> <generatedKey column="id" sqlStatement="Mysql" identity="true" /> </table> </context> </generatorConfiguration>
3、通过运行Maven命令来自动生成Model类、mapper接口、mapper.xml文件
mybatis-generator:generate
4、通过改变pom.xml中mybatis-generator-maven-plugin插件的overwrite标签,来决定生成后的文件是否覆盖已存在的文件。一般是选择false,这样只会生成DB中新建表对应的代码