Running MyBatis Generator With Java

MyBatis Generator (MBG) may be invoked directly from Java. For configuration, you may use either an XML configuration file, or configure MBG completely with Java.

Running MBG from Java with an XML Configuration File

The following code sample shows how to call MBG from Java with an XML based configuration. It does not show exception handling, but that should be obvious from the compiler errors :)

   List<String> warnings = new ArrayList<String>();
   boolean overwrite = true;
   File configFile = new File("generatorConfig.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);

Notes:

  • Configuration file properties may be passed to the parser as a parameter on the ConfigurationParser constructor. If not passed explicitly, the JVM system properties will be searched for the value of configuration file properties. For example, the property generated.source.dir can be accessed in the configuration file with the escape sequence ${generated.source.dir}
  • If a property is specified in the configuration file and is not resolved, then the escaped property string will be passed "as is" into the generated code.

Running MBG from Java with a Java Based Configuration

The following code sample shows how to call MBG from Java with a Java based configuration. It does not show exception handling, but that should be obvious from the compiler errors :)

   List<String> warnings = new ArrayList<String>();
   boolean overwrite = true;
   Configuration config = new Configuration();

   //   ... fill out the config object as appropriate...

   DefaultShellCallback callback = new DefaultShellCallback(overwrite);
   MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
   myBatisGenerator.generate(null);