mybatis-generator可以根据数据库的表来生成POJO类、mapper.xml和DAO接口,用这个插件会大大地提高开发的效率。网上虽然有一些使用这个插件的教程,但我单个试了并不能成功,会出现各种问题,直到综合了几篇文章所讲的方法,才将其真正的弄好
1、在pom,xml中添加依赖包,这里我用的是1.3.2
<properties> <mybatis-generator.version>1.3.2</mybatis-generator.version> </properties> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>${mybatis-generator.version}</version> </dependency>
2、在pom,xml中添加插件
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin>
替换成你jdbc的jar包路径
<?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="C:/Users/fzj/.m2/repository/mysql/mysql-connector-java/5.1.22/mysql-connector-java-5.1.22.jar" /> <context id="mysqlTables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/two" userId="root" password="123456"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成model模型,对应的包,存放位置可以指定具体的路径,如/ProjectName/src,也可以使用MAVEN来自动生成 --> <javaModelGenerator targetPackage="com.two.entity" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--对应的xml mapper文件 --> <sqlMapGenerator targetPackage="mybatis" targetProject="src/main/resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 对应的dao接口 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.two.dao" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 这里是数据库的表名table_user 以及 POJO类的名字User --> <table tableName="table_user" domainObjectName="User" enableCountByExample="false" enableSelectByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"> </table> </context> </generatorConfiguration>
选中项目——run as ——maven build——(会看到有一个Goals)select——mybatis-generator(点击下面的generate)——Run
如果看到控制台出现success,说明成功,即可生成UserMapper.java、userMapper.xml、User.java