MGB MyBatis Generator
一個生成MyBatis的代碼生成器
自動生成的mapper.xml文件兽泄,model對象(pojo)和mapper類的工具。
MGB為配置中的每個表生成簡單的CRUB函數(shù)生成sql,如下
- insert
- update by primary key
- update by example (可以編輯where的條件)
- delete by primary key
- delete by example
- select by primary key
- select by example
- count by example
如果對應的表沒有主鍵則不會生成有關(guān)primary的函數(shù)
使用:
在resources中創(chuàng)建一mbg的配置文件刀闷,用來編寫相關(guān)的生成配置。
默認的是genratorConfig.xml仰迁。MGB就是從該配置文件自動生成pojo甸昏,mapper以及對應的xml映射文件。
配置
最簡單的配置文件需要如下幾個標簽
- jdbcConnection
配置數(shù)據(jù)源 - javaModelGenerator
指定目標目錄生成相應的pojo類轩勘。 - sqlMapGenerator
指定目標目錄生成相應的mapper文件(xml)筒扒。 - javaClientGenerator(這個可以沒有)
在目標目錄生成相應的接口和mapper類(dao層)。 - table
配置表如何映射成對應的類绊寻,開啟什么樣的接口。
還有許多配置悬秉,詳見官方文檔
啟動MBG
需要編寫一些代碼通過類加載器生成
List<String > warnings = new ArrayList<String >();
boolean overwrite = true;
File configFile = new File(MyBatisGenerator.class.getClassLoader()
.getResource("generatorConfig.xml").toURI());
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
ShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);