首先创建一个test类:
在main方法里写上如下代码:
List <String> warnings = new ArrayList <String>(); boolean overwrite = true; File configFile = new File("generator.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,callback,warnings); myBatisGenerator.generate(null);
在工程目录下新建一个generator.xml文件:
开发工具eclipse:
开发工具idea:
<?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"> <commentGenerator> <property name="suppressAllComments" value="true"></property> </commentGenerator> <!-- 设定数据库连接 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root" password="123"> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成 bean 存放的位置 --> <javaModelGenerator targetPackage="com.ujiuye.bean" targetProject=".\src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成的mapper文件的位置 --> <sqlMapGenerator targetPackage="com.ujiuye.mapper" targetProject=".\src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成的mapper.xml 对应的那个mapper接口的存放位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.ujiuye.mapper" targetProject=".\src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 设定反向生成的表 --> <table tableName="Person"></table> <table tableName="car"></table> <table tableName="card"></table> </context> </generatorConfiguration>
最后的table标签是自己数据库中表的名字;数据库的连接信息需要自己修改
执行test类就会自动生成自己以上设置table标签中数据中表的对应的实体类,dao层接口以及对应的mapper映射
此外需要的jar包请自行下载:https://github.com/Pei-Qi/mybatis_jar