第一步:新建一个Java项目,导入JDBC驱动、MyBatis的jar包以及mybatis-generator-core-1.3.5.jar文件并加载到项目的类路径中。
第二步:在MySQL的test数据库中创建tb_dept数据表,创建Java项目MyBatisDemo,然后在src下依次创建包com.domain、com.mapping、com.dao。
第三步:在项目中利用向导创建generatorConfig.xml文件(名称可修改)然后修改文件内容,主要是设置连接数据的相关参数:
-------①
-------①
-------①
如果想生成Example之类的代码,只需要将
里面的下面所示的内容去掉就可以了:enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"
第四步:生成代码。 配置好连接数据库及表的信息后就可以利用插件自动生成代码了:
-
方式一,使用插件:在generatorConfig_plugin.xml上右键,选择Generate MyBatis/iBATIS Artifacts运行,就可以得到生成的实体类、DAO类、映射文件,如下图所示:
-
方式二,CMD方式:此种方式,首先需要将上面编号①处的tartgetProject改为相对路径,比如targetProject="…/src",然后再在项目的libs路径下打开命令行窗口输入:java -jar mybatis-generator-core-1.3.2.jar -configfile …/config/generatorConfig_cmd.xml -overwrite,也可以得到实体类、DAO类、映射文件,如下图所示:
-
方式三:编写生成代码的主方法,然后运行该方法
public static void main(String[] args) { List warnings = new ArrayList(); boolean overwrite = true; String cfg = "/generatorConfig.xml"; File configFile = new File(MyBatisGeneratorTool.class.getResource( cfg).getFile()); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = null; try { config = cp.parseConfiguration(configFile); } catch (IOException e) { e.printStackTrace(); } catch (XMLParserException e) { e.printStackTrace(); } DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = null; try { myBatisGenerator = new MyBatisGenerator(config, callback, warnings); } catch (InvalidConfigurationException e) { e.printStackTrace(); } try { myBatisGenerator.generate(null); } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }