天天看點

MyBatisPlus系列七:代碼生成器

MyBatisPlus的代碼生成器 和 Mybatis MBG 代碼生成器:

 MyBatisPlus的代碼生成器都是基于 java 代碼來生成。MBG 基于 xml 檔案進行代碼生成 。

 MyBatis 的代碼生成器可生成: 實體類、Mapper 接口、Mapper 映射檔案。

 MyBatisPlus的代碼生成器可生成: 實體類(可以選擇是否支援 AR)、Mapper 接口、Mapper 映射檔案、Service 層、Controller 層.。

1、引入依賴

<!-- MyBatisPlus的代碼生成器預設使用的是Apache的Velocity模闆 -->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.0</version>
</dependency>

<!-- sfl4j -->
 <dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-api</artifactId>
	<version>1.7.7</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>1.7.7</version>
</dependency>
           

2、測試代碼生成

@Test
public void  testGenerator() {
	//1. 全局配置
	GlobalConfig config = new GlobalConfig();
	config.setActiveRecord(true) // 是否支援AR模式
		  .setAuthor("lizq") // 作者
		  .setOutputDir("G:\\mybatisplus\\mp03\\src\\main\\java") // 生成路徑
		  .setFileOverride(true)  // 檔案覆寫
		  .setIdType(IdType.AUTO) // 主鍵政策
		  .setServiceName("%sService")  // 設定生成的service接口的名字的首字母不是I
			  .setBaseResultMap(true)
			  .setBaseColumnList(true);
	
	//2. 資料源配置
	DataSourceConfig  dsConfig  = new DataSourceConfig();
	dsConfig.setDbType(DbType.MYSQL)  // 設定資料庫類型
			.setDriverName("com.mysql.jdbc.Driver")
			.setUrl("jdbc:mysql://localhost:3306/mybatisplus")
			.setUsername("root")
			.setPassword("root");
	 
	//3. 政策配置
	StrategyConfig stConfig = new StrategyConfig();
	stConfig.setCapitalMode(true) //全局大寫命名
			.setDbColumnUnderline(true)  // 指定表名、字段名是否使用下劃線
			.setNaming(NamingStrategy.underline_to_camel) // 資料庫表映射到實體的命名政策
			.setTablePrefix("tbl_")
			.setInclude("tbl_employee");  // 生成的表
	
	//4. 包名政策配置 
	PackageConfig pkConfig = new PackageConfig();
	pkConfig.setParent("com.atguigu.mp")
			.setMapper("mapper")
			.setService("service")
			.setController("controller")
			.setEntity("beans")
			.setXml("mapper");
	
	//5. 整合配置
	AutoGenerator  ag = new AutoGenerator();
	ag.setGlobalConfig(config)
	  .setDataSource(dsConfig)
	  .setStrategy(stConfig)
	  .setPackageInfo(pkConfig);
	
	//6. 執行
	ag.execute();
}
           
MyBatisPlus系列七:代碼生成器

注意:生成的EmployeeServiceImpl繼承了ServiceImpl。

  1. 在ServiceImpl中已經完成Mapper對象的注入,直接在EmployeeServiceImpl中進行使用。不用再進行mapper的注入。
  2. 在ServiceImpl中也幫我們提供了常用的CRUD方法, 基本的一些CRUD方法在Service中不需要我們自己定義。

繼續閱讀