Mybatis Plus是扳手,那Mybatis Generator就是生產扳手的工廠。
Mybatis Plus:國人團隊苞米豆在Mybatis的基礎上開發的框架,在Mybatis基礎上擴展了許多功能,榮獲了2018最受歡迎國產開源軟件第5名,當然也有配套的↓
Mybatis Plus Generator:同樣爲苞米豆開發,比Mybatis Generator更加強大,支持功能更多,自動生成Entity、Mapper、Service、Controller等
Mybatis-Plus是一個Mybatis的增強工具,它在Mybatis的基礎上做了增強,卻不做改變。我們在使用Mybatis-Plus之後既可以使用Mybatis-Plus的特有功能,又能夠正常使用Mybatis的原生功能。Mybatis-Plus(以下簡稱MP)是爲簡化開發、提高開發效率而生,但它也提供了一些很有意思的插件,比如SQL性能監控、樂觀鎖、執行分析等。
一、 集成步驟↓:(首先,你要有個spring項目)
集成依賴,pom中加入依賴即可,不多說:
Java代碼 收藏代碼
.
.
.
.
.
.
.
說明:筆者使用的版本爲:mybatis-plus.version=2.1-gamma,上邊的代碼中有兩個依賴,第一個是mybatis-plus核心依賴,第二個是使用代碼生成器時需要的模板引擎依賴,若果你不打算使用代碼生成器,此處可不引入。
注意:mybatis-plus的核心jar包中已集成了mybatis和mybatis-spring,所以爲避免衝突,請勿再次引用這兩個jar包。
.
.
.
.
.
.
.
二、 在spring中配置MP:
<!-- MP 全局配置注入 -->
<property name="globalConfig" ref="globalConfig" />
.
.
.
.
.
.
.
.
<tx:annotation-driven transaction-manager=“transactionManager”
proxy-target-class=“true” />
注意:只要做如上配置就可以正常使用mybatis了,不要重複配置。MP的配置和mybatis一樣,都是配置一個sqlSessionFactory,只是現在所配置的類在原本的SqlSessionFactoryBean基礎上做了增強。插件等配置請按需取捨。
插件配置,按需求配置就可以,此處把可以配置的插件都列了出來,具體的請看代碼註釋:
Java代碼 收藏代碼
<!-- SQL 執行性能分析,開發環境使用,線上不推薦。 maxTime 指的是 sql 最大執行時長 -->
<plugin interceptor="com.baomidou.mybatisplus.plugins.PerformanceInterceptor">
<property name="maxTime" value="2000" />
<!--SQL是否格式化 默認false -->
<property name="format" value="true" />
</plugin>
<!-- SQL 執行分析攔截器 stopProceed 發現全表執行 delete update 是否停止運行 該插件只用於開發環境,不建議生產環境使用。。。 -->
<plugin interceptor="com.baomidou.mybatisplus.plugins.SqlExplainInterceptor">
<property name="stopProceed" value="false" />
</plugin>
</plugins>
.
.
…
.
…
.
.
注意:執行分析攔截器和性能分析推薦只在開發時調試程序使用,爲保證程序性能和穩定性,建議在生產環境中註釋掉這兩個插件。
數據源:(此處使用druid)
<!-- 監控數據庫 -->
<!-- <property name="filters" value="stat" /> -->
<!-- <property name="filters" value="mergeStat" />-->
.
.
.
.
.
.
.
.
.
到此,MP已經集成進我們的項目中了,下面將介紹它是如何簡化我們的開發的。
.
.
.
.
.
.
**
三、 簡單的CURD操作↓:
**
假設我們有一張user表,且已經建立好了一個與此表對應的實體類User,我們來介紹對user的簡單增刪改查操作。
建立DAO層接口。我們在使用普通的mybatis時會建立一個DAO層接口,並對應一個xml用來寫SQL。在這裏我們同樣要建立一個DAO層接口,但是若無必要,我們甚至不需要建立xml,就可以進行資源的CURD操作了,我們只需要讓我們建立的DAO繼承MP提供的BaseMapper<?>即可:
public interface UserMapper extends BaseMapper { }
然後在我們需要做數據CURD時,像下邊這樣就好了:
Java代碼 收藏代碼
// 初始化 影響行數
int result = 0;
// 初始化 User 對象
User user = new User();
// 插入 User (插入成功會自動回寫主鍵到實體類)
user.setName(“Tom”);
result = userMapper.insert(user);
// 更新 User
user.setAge(18);
result = userMapper.updateById(user);//user要設置id哦,具體的在下邊我會詳細介紹
// 查詢 User
User exampleUser = userMapper.selectById(user.getId());
// 查詢姓名爲‘張三’的所有用戶記錄
List userList = userMapper.selectList(
new EntityWrapper().eq(“name”, “張三”)
);
// 刪除 User
result = userMapper.deleteById(user.getId());
方便吧?如果只使用mybatis可是要寫4個SQL和4個方法喔,當然了,僅僅上邊這幾個方法還遠遠滿足不了我們的需求,請往下看:
.
.
.
.
.
.
.
**
多條件分頁查詢:
**
Java代碼 收藏代碼
// 分頁查詢 10 條姓名爲‘張三’、性別爲男,且年齡在18至50之間的用戶記錄
List userList = userMapper.selectPage(
new Page(1, 10),
new EntityWrapper().eq(“name”, “張三”)
.eq(“sex”, 0)
.between(“age”, “18”, “50”)
);
.
.
.
.
.
.
/**等價於SELECT *
*FROM sys_user
*WHERE (name=‘張三’ AND sex=0 AND age BETWEEN ‘18’ AND ‘50’)
*LIMIT 0,10
*/
下邊這個,多條件構造器。其實對於條件過於複雜的查詢,筆者還是建議使用原生mybatis的方式實現,易於維護且邏輯清晰,如果所有的數據操作都強行使用MP,就失去了MP簡化開發的意義了。所以在使用時請按實際情況取捨,在這裏還是先介紹一下。
public Page selectPage(Page page, EntityWrapper entityWrapper) {
if (null != entityWrapper) {
entityWrapper.orderBy(page.getOrderByField(), page.isAsc());//排序
}
page.setRecords(baseMapper.selectPage(page, entityWrapper));//將查詢結果放入page中
return page;
}
.
.
.
.
.
.
.
** 條件構造一(上邊方法的entityWrapper參數):**
public void testTSQL11() {
/*
* 實體帶查詢使用方法 輸出看結果
/
EntityWrapper ew = new EntityWrapper();
ew.setEntity(new User(1));
ew.where(“user_name={0}”, “‘zhangsan’”).and(“id=1”)
.orNew(“user_status={0}”, “0”).or(“status=1”)
.notLike(“user_nickname”, “notvalue”)
.andNew(“new=xx”).like(“hhh”, “ddd”)
.andNew(“pwd=11”).isNotNull(“n1,n2”).isNull(“n3”)
.groupBy(“x1”).groupBy(“x2,x3”)
.having(“x1=11”).having(“x3=433”)
.orderBy(“dd”).orderBy(“d1,d2”);
System.out.println(ew.getSqlSegment());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
** 條件構造二(同上):*
int buyCount = selectCount(Condition.create()
.setSqlSelect(“sum(quantity)”)
.isNull(“order_id”)
.eq(“user_id”, 1)
.eq(“type”, 1)
.in(“status”, new Integer[]{0, 1})
.eq(“product_id”, 1)
.between(“created_time”, startDate, currentDate)
.eq(“weal”, 1));
自定義條件使用entityWrapper:
List selectMyPage(RowBounds rowBounds, @Param(“ew”) Wrapper wrapper);
SELECT * FROM user ${ew.sqlSegment} 注意:此處不用擔心SQL注入,MP已對ew做了字符串轉義處理。 其實在使用MP做數據CURD時,還有另外一個方法,AR(ActiveRecord ),很簡單,讓我們的實體類繼承MP提供Model<?>就好了,這和我們常用的方法可能會有些不同,下邊簡單說一下吧:
//實體類
@TableName(“sys_user”) // 註解指定表名
public class User extends Model {
… // fields
… // getter and setter
/** 指定主鍵 */
@Override
protected Serializable pkVal() { //一定要指定主鍵哦
return this.id;
}
}
下邊就是CURD操作了:
// 初始化 成功標識
boolean result = false;
// 初始化 User
User user = new User();
// 保存 User
user.setName(“Tom”);
result = user.insert();
// 更新 User
user.setAge(18);
result = user.updateById();
// 查詢 User
User exampleUser = t1.selectById();
// 查詢姓名爲‘張三’的所有用戶記錄
List userList1 = user.selectList(
new EntityWrapper().eq(“name”, “張三”)
);
// 刪除 User
result = t2.deleteById();
// 分頁查詢 10 條姓名爲‘張三’、性別爲男,且年齡在18至50之間的用戶記錄
List userList = user.selectPage(
new Page(1, 10),
new EntityWrapper().eq(“name”, “張三”)
.eq(“sex”, 0)
.between(“age”, “18”, “50”)
).getRecords();
就是這樣了,可能你會說MP封裝的有些過分了,這樣做會分散數據邏輯到不同的層面中,難以管理,使代碼難以理解。其實確實是這樣,這就需要你在使用的時候注意一下了,在簡化開發的同時也要保證你的代碼層次清晰,做一個戰略上的設計或者做一個取捨與平衡。
.
.
.
.
.
.
**
其實上邊介紹的功能也不是MP的全部啦,下邊介紹一下MP最有意思的模塊——代碼生成器。
**
步驟↓:
如上邊所說,使用代碼生成器一定要引入velocity-engine-core(模板引擎)這個依賴。
準備工作:
選擇主鍵策略,就是在上邊最開始時候我介紹MP配置時其中的這項配置,如果你不記得了,請上翻!MP提供瞭如下幾個主鍵策略: 值 描述
IdType.AUTO 數據庫ID自增
IdType.INPUT 用戶輸入ID
IdType.ID_WORKER 全局唯一ID,內容爲空自動填充(默認配置)
IdType.UUID 全局唯一ID,內容爲空自動填充
MP默認使用的是ID_WORKER,這是MP在Sequence的基礎上進行部分優化,用於產生全局唯一ID。
表及字段命名策略選擇,同上,還是在那個配置中。下邊這段複製至MP官方文檔:
在MP中,我們建議數據庫表名採用下劃線命名方式,而表字段名採用駝峯命名方式。
這麼做的原因是爲了避免在對應實體類時產生的性能損耗,這樣字段不用做映射就能直接和實體類對應。當然如果項目裏不用考慮這點性能損耗,那麼你採用下滑線也是沒問題的,只需要在生成代碼時配置dbColumnUnderline屬性就可以。
建表(命名規則依照剛纔你所配置的,這會影響生成的代碼的類名、字段名是否正確)。
執行下邊的main方法,生成代碼:
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
/**
-
- 代碼生成器演示
*/
public class MpGenerator {
/**
* <p>
* MySQL 生成演示
* </p>
*/
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("D://");
gc.setFileOverride(true);
gc.setActiveRecord(true);// 不需要ActiveRecord特性的請改爲false
gc.setEnableCache(false);// XML 二級緩存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
// .setKotlin(true) 是否生成 kotlin 代碼
gc.setAuthor("Yanghu");
// 自定義文件命名,注意 %s 會自動填充表實體屬性!
// gc.setMapperName("%sDao");
// gc.setXmlName("%sDao");
// gc.setServiceName("MP%sService");
// gc.setServiceImplName("%sServiceDiy");
// gc.setControllerName("%sAction");
mpg.setGlobalConfig(gc);
// 數據源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert(){
// 自定義數據庫表字段類型轉換【可選】
@Override
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("轉換類型:" + fieldType);
// 注意!!processTypeConvert 存在默認類型轉換,如果不是你要的效果請自定義返回、非如下直接返回。
return super.processTypeConvert(fieldType);
}
});
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("521");
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=utf8");
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// strategy.setCapitalMode(true);// 全局大寫命名 ORACLE 注意
strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此處可以修改爲您的表前綴
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
// strategy.setInclude(new String[] { "user" }); // 需要生成的表
// strategy.setExclude(new String[]{"test"}); // 排除生成的表
// 自定義實體父類
// strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
// 自定義實體,公共字段
// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
// 自定義 mapper 父類
// strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
// 自定義 service 父類
// strategy.setSuperServiceClass("com.baomidou.demo.TestService");
// 自定義 service 實現類父類
// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
// 自定義 controller 父類
// strategy.setSuperControllerClass("com.baomidou.demo.TestController");
// 【實體】是否生成字段常量(默認 false)
// public static final String ID = "test_id";
// strategy.setEntityColumnConstant(true);
// 【實體】是否爲構建者模型(默認 false)
// public User setName(String name) {this.name = name; return this;}
// strategy.setEntityBuilderModel(true);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.baomidou");
pc.setModuleName("test");
mpg.setPackageInfo(pc);
// 注入自定義配置,可以在 VM 中使用 cfg.abc 【可無】
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
this.setMap(map);
}
};
// 自定義 xxList.jsp 生成
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
focList.add(new FileOutConfig("/template/list.jsp.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸入文件名稱
return "D://my_" + tableInfo.getEntityName() + ".jsp";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 調整 xml 生成目錄演示
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 關閉默認 xml 生成,調整生成 至 根目錄
TemplateConfig tc = new TemplateConfig();
tc.setXml(null);
mpg.setTemplate(tc);
// 自定義模板配置,可以 copy 源碼 mybatis-plus/src/main/resources/templates 下面內容修改,
// 放置自己項目的 src/main/resources/templates 目錄下, 默認名稱一下可以不配置,也可以自定義模板名稱
// TemplateConfig tc = new TemplateConfig();
// tc.setController("...");
// tc.setEntity("...");
// tc.setMapper("...");
// tc.setXml("...");
// tc.setService("...");
// tc.setServiceImpl("...");
// 如上任何一個模塊如果設置 空 OR Null 將不生成該模塊。
// mpg.setTemplate(tc);
// 執行生成
mpg.execute();
// 打印注入設置【可無】
System.err.println(mpg.getCfg().getMap().get("abc"));
}
}
說明:中間的內容請自行修改,註釋很清晰。
成功生成代碼,將生成的代碼拷貝到你的項目中就可以了,這個東西節省了我們大量的時間和精力!
**
.
.
.
.
.
.
以下是註解說明,摘自官方文檔: 註解說明**
表名註解 @TableName
com.baomidou.mybatisplus.annotations.TableName
值 描述
value 表名( 默認空 )
resultMap xml 字段映射 resultMap ID
主鍵註解 @TableId
com.baomidou.mybatisplus.annotations.TableId
值 描述
value 字段值(駝峯命名方式,該值可無)
type 主鍵 ID 策略類型( 默認 INPUT ,全局開啓的是 ID_WORKER )
暫不支持組合主鍵
字段註解 @TableField
com.baomidou.mybatisplus.annotations.TableField
值 描述
value 字段值(駝峯命名方式,該值可無)
el 詳看註釋說明
exist 是否爲數據庫表字段( 默認 true 存在,false 不存在 )
strategy 字段驗證 ( 默認 非 null 判斷,查看 com.baomidou.mybatisplus.enums.FieldStrategy )
fill 字段填充標記 ( FieldFill, 配合自動填充使用 )
字段填充策略 FieldFill
值 描述
DEFAULT 默認不處理
INSERT 插入填充字段
UPDATE 更新填充字段
INSERT_UPDATE 插入和更新填充字段
序列主鍵策略 註解 @KeySequence
com.baomidou.mybatisplus.annotations.KeySequence
值 描述
value 序列名
clazz id的類型
樂觀鎖標記註解 @Version
com.baomidou.mybatisplus.annotations.Version
排除非表字段、查看文檔常見問題部分!
總結:MP的宗旨是簡化開發,但是它在提供方便的同時卻容易造成代碼層次混亂,我們可能會把大量數據邏輯寫到service層甚至contoller層中,使代碼難以閱讀。凡事過猶不及,在使用MP時一定要做分析,不要將所有數據操作都交給MP去實現。畢竟MP只是mybatis的增強工具,它並沒有侵入mybatis的原生功能,在使用MP的增強功能的同時,原生mybatis的功能依然是可以正常使用的