1、用Idea創建一個Maven項目,在Maven項目中添加依賴和插件。然后點擊Maven Projects--install,完成對依賴的包的導入。此項目需要mybatis-generator-core.jar、mysql-connector-java.jar包等,可以從Maven中央倉庫下載。由于不能上傳代碼,所以將代碼提交到了github:
https://github.com/juxiemushu/Mybatis_generator_core.git
2、在resources資源目錄下創建一個Config文件夾,用于存儲初始化的數據庫信息,以及代碼生成需要的 xml 文件。
其中 init.properties 的代碼如下:
javapath:指定了生成的
#Mybatis Generator configuration
javapath=src/main/java
xmlpath=src/main/resources
classPath=G:/mysql-connector-java-5.1.39.jar
jdbc_driver=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://127.0.0.1:3306/db_exam?characterEncoding=utf8
jdbc_user=root
jdbc_password=wsp19940812
代碼生成配置文件 mbgConfiguration.xml ,在配置文件中可以配置數據庫的連接,代碼生成的包名,與數據庫對應的表等信息。
3、創建一個Java類,用于讀取配置文件,生成代碼,內容如下:
public classGenerator {
public static voidmain(String[] args){
List warnings =newArrayList();
booleanoverwrite =true;
String path ="/Config/mbgConfiguration.xml";
File configFile =newFile(Generator.class.getResource(path).getFile());
ConfigurationParser cp =newConfigurationParser(warnings);
Configuration config =null;
try{
config = cp.parseConfiguration(configFile);
}catch(IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch(XMLParserException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
DefaultShellCallback callback =newDefaultShellCallback(overwrite);
MyBatisGenerator mybatisGenerator =null;
try{
mybatisGenerator =newMyBatisGenerator(config,callback,warnings);
}catch(InvalidConfigurationException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
try{
mybatisGenerator.generate(null);
}catch(SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch(InterruptedException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
4、運行步驟3中的Java類,如股票運行正常,則在相應的包中會出現自動生成的代碼。