Fluent Mybatis快速入門詳細教程
使用fluent mybatis可以不用寫具體的xml文件,通過java api可以構造出比較復雜的業務sql語句,做到代碼邏輯和sql邏輯的合一。 不再需要在Dao中組裝查詢或更新操作,在xml或mapper中再組裝參數。喜歡的朋友可以閱讀這篇文章 http://www.jb51.net/article/218884.htm
對底層數據表關聯關系的處理,我們總是繞不開什么一對一,一對多,多對多這里比較煩人的關系。 業界優秀的ORM框架也都給出了自己的答案,簡單來說就以下幾種方式:
hibernate和JPA對開發基本屏蔽了底層數據的處理,只需要在model層設置數據級聯關系即可。但這種設置也往往是噩夢的開始。mybatis 提供了簡單的@One @Many注解,然后編寫xml映射關系來提供級聯處理。還有一種就是干脆不依賴框架,直接應用自己掌控。因為FluentMybatis是基于mybatis上做封裝和擴展的,所以這里主要聊聊mybatis處理的方式,以及給出FluentMybatis的解放方案。
那么就可以建以下3張表:
數據字典
CREATE TABLE t_member(id bigint(21) unsigned auto_increment primary key COMMENT ‘主鍵id’,user_name varchar(45) DEFAULT NULL COMMENT ‘名字’,is_girl tinyint(1) DEFAULT 0 COMMENT ‘0:男孩; 1:女孩’,age int DEFAULT NULL COMMENT ‘年齡’,school varchar(20) DEFAULT NULL COMMENT ‘學校’,gmt_created datetime DEFAULT NULL COMMENT ‘創建時間’,gmt_modified datetime DEFAULT NULL COMMENT ‘更新時間’,is_deleted tinyint(1) DEFAULT 0 COMMENT ‘是否邏輯刪除’) ENGINE = InnoDBCHARACTER SET = utf8 COMMENT = ‘成員表:女孩或男孩信息’;CREATE TABLE t_member_love(id bigint(21) unsigned auto_increment primary key COMMENT ‘主鍵id’,girl_id bigint(21) NOT NULL COMMENT ‘member表外鍵’,boy_id bigint(21) NOT NULL COMMENT ‘member表外鍵’,status varchar(45) DEFAULT NULL COMMENT ‘狀態’,gmt_created datetime DEFAULT NULL COMMENT ‘創建時間’,gmt_modified datetime DEFAULT NULL COMMENT ‘更新時間’,is_deleted tinyint(2) DEFAULT 0 COMMENT ‘是否邏輯刪除’) ENGINE = InnoDBCHARACTER SET = utf8 COMMENT = ‘成員戀愛關系’;CREATE TABLE t_member_favorite(id bigint(21) unsigned auto_increment primary key COMMENT ‘主鍵id’,member_id bigint(21) NOT NULL COMMENT ‘member表外鍵’,favorite varchar(45) DEFAULT NULL COMMENT ‘愛好: 電影, 爬山, 徒步…’,gmt_created datetime DEFAULT NULL COMMENT ‘創建時間’,gmt_modified datetime DEFAULT NULL COMMENT ‘更新時間’,is_deleted tinyint(2) DEFAULT 0 COMMENT ‘是否邏輯刪除’) ENGINE = InnoDBCHARACTER SET = utf8 COMMENT = ‘成員愛好’;
添加項目Maven依賴具體pom.xml文件
代碼生成
public class AppEntityGenerator {static final String url = “jdbc:mysql://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8”;/*** 生成代碼的package路徑*/static final String basePackage = “cn.org.fluent.mybatis.many2many.demo”;public static void main(String[] args) { FileGenerator.build(Noting.class);}@Tables( /** 數據庫連接信息 **/ url = url, username = 'root', password = 'password', /** Entity類parent package路徑 **/ basePack = basePackage, /** Entity代碼源目錄 **/ srcDir = 'example/many2many_demo/src/main/java', /** 如果表定義記錄創建,記錄修改,邏輯刪除字段 **/ gmtCreated = 'gmt_create', gmtModified = 'gmt_modified', logicDeleted = 'is_deleted', /** 需要生成文件的表 ( 表名稱:對應的Entity名稱 ) **/ tables = @Table(value = {'t_member', 't_member_love', 't_member_favorite'}, tablePrefix = 't_'))static class Noting {}}
這樣就生成了3個Entity類: MemberEntity, MemberFavoriteEntity, MemberLoveEntity。
關系分析現在我們來理一理這里面的關系
一對多: 一個成員可以有多個愛好多對多: 一個成員可以有多個男女朋友(前任+現任)一對一: 一個成員只能有一個現任男女朋友mybatis處理手法mybatis提供了@One 和 @Many的注解來處理簡單(只有主鍵和外鍵依賴)的一對一,和一對多的關系 具體到上面的關系,mybatis只能關聯查詢成員的愛好,對帶條件的(不是只通過外鍵)現任男女朋友的一對一也沒有辦法處理。
我這里就不具體展開mybatis的配置語法了,感興趣讀者可以看下下面文章:
Mybatis一對多、多對一處理
Mybatis傳遞多個參數進行SQL查詢的用法
MyBatis注解 & 多對一、一對多
MyBatis系列4:一對一,一對多,多對多查詢及延遲加載(N+1問題)分析
鑒于mybatis只能處理簡單的關聯關系,fluent mybatis就沒有直接封裝mybatis的處理方式,那fluent mybatis是如何處理上述的關聯關系的。 我們先從mybatis也可以處理的一對多的愛好列表入手
一對多的愛好列表處理fluent mybatis要根據MemberEntity自動返回對應的愛好列表,需要下面幾個設置:
MemberEntity繼承RichEntity基類在MemberEntity類里面增加方法 findMyFavorite()給findMyFavorite方法加上注解 @RefMethod在注解中增加關聯關系: “memberId=id”,意思是 MemberFavoriteEntity.memberId等于MemberEntity.id具體代碼片段如下, 所有這些操作都可以通過代碼生成,這里手工添加僅僅是為了講解
public class MemberEntity extends RichEntity implements IEntity {// …/*** 我的愛好列表** @return*/@RefMethod(“memberId=id”)public List findMyFavorite() {return super.loadCache(“findMyFavorite”, MemberEntity.class);}}
好了,我們已經建立好通過Member實例查詢愛好列表的功能了,重新編譯項目 在generated-sources目錄下面,會多出一個文件: Refs
/***Refs:o - 查詢器,更新器工廠類單例引用o - 應用所有Mapper Bean引用o - Entity關聯對象延遲加載查詢實現@author powered by FluentMybatis*/public abstract class Refs extends EntityRefQuery {public List findMyFavoriteOfMemberEntity(MemberEntity entity) {return memberFavoriteMapper.listEntity(new MemberFavoriteQuery().where.memberId().eq(entity.getId()).end());}}
在這個類里面自動生成了一個方法: findMyFavoriteOfMemberEntity, 入參是MemberEntity, 出參是List, 實現里面根據member的id查詢了成員的所有愛好。
增加Spring Bean我們新建一個類: AllRelationQuery (名稱根據你的喜好和業務隨便取), 繼承Refs, 并把AllRelationQuery加入Spring管理即可。
@Servicepublic class AllRelationQuery extends Refs {}
老套路,寫個測試驗證下
@RunWith(SpringRunner.class)@SpringBootTest(classes = Application.class)public class FindMemberFavoriteTest {@Autowiredprivate MemberMapper memberMapper;@Beforepublic void setup() { // 省略數據準備部分}@Testpublic void findMyFavorite() { MemberEntity member = memberMapper.findById(1L); List<MemberFavoriteEntity> favorites = member.findMyFavorite(); System.out.println('愛好項: ' + favorites.size());}}
查看控制臺log輸出
DEBUG - ==> Preparing: SELECT id, …, user_name FROM t_member WHERE id = ?DEBUG - > Parameters: 1(Long)DEBUG - < Total: 1DEBUG - ==> Preparing: SELECT id, …, member_id FROM t_member_favorite WHERE member_id = ?DEBUG - > Parameters: 1(Long)DEBUG - < Total: 2愛好項: 2
如日志所示,Fluent Mybatis按照預期返回了愛好列表。
給一對多關系添點油加點醋做過業務系統的同學都知道,數據庫中業務數據一般會有一個邏輯刪除標識,按照上述邏輯查詢出來的數據,我們會把已經廢棄(邏輯刪除掉)的愛好也一并查詢出來了,那我們如何只查詢出未邏輯刪除(is_deleted=0)的愛好列表呢。
如果采用mybatis的方案,那我們只能聳聳肩,攤開雙手說: “愛莫能助,你自己寫SQL實現吧”, 但fluent mybatis對這類場景的支持的很好,我們只要給@RefMethod注解值加點條件就可以了, MemberFavoriteEntity.memberId=MemberEntity.id并且Favorite的邏輯刪除標識和Member表一樣,具體定義如下:
public class MemberEntity extends RichEntity implements IEntity {@RefMethod(“memberId=id && isDeleted=isDeleted”)public List findMyFavorite() {return super.loadCache(“findMyFavorite”, MemberEntity.class);}}
重新編譯項目,觀察Refs代碼
public abstract class Refs extends EntityRefQuery {public List findMyFavoriteOfMemberEntity(MemberEntity entity) {return memberFavoriteMapper.listEntity(new MemberFavoriteQuery().where.isDeleted().eq(entity.getIsDeleted()).and.memberId().eq(entity.getId()).end());}}
查詢條件上帶上了邏輯刪除條件
跑測試,看log
DEBUG - ==> Preparing: SELECT id, …, user_name FROM t_member WHERE id = ?DEBUG - > Parameters: 1(Long)DEBUG - < Total: 1DEBUG - ==> Preparing: SELECT id, …, member_id FROM t_member_favoriteWHERE is_deleted = ?AND member_id = ?DEBUG - > Parameters: false(Boolean), 1(Long)DEBUG - < Total: 2愛好項: 2
FluentMybatis輕松處理了多條件關聯的一對多關系, 這個在業務中不僅僅限定于邏輯刪除, 還可以推廣到部署環境標識(deploy_env), 租戶關系等條件上,還有只有你業務中才用到的狀態相關的關系上。
Fluent Mybatis對多對多關系處理fluent mybatis可以輕松處理一對一,一對多的簡單和多條件的關聯關系,但對多對多也沒有提供自動化代碼生成的處理手段。 因為多對多,本質上涉及到3張表, A表, B表,AB關聯表。 但fluent mybatis還是提供了半自動手段,對這類場景進行了支持,比如我們需要MemberEntity中返回所有前任戀人列表。
在MemberEntity中定義方法: exFriends()
public class MemberEntity extends RichEntity implements IEntity {/*** 前任男(女)朋友列表** @return*/@RefMethodpublic List findExFriends() {return super.loadCache(“findExFriends”, MemberEntity.class);}}
和上面的自動化的一對多關系有個區別,@RefMethod上沒有設置查詢條件,我們重新編譯項目。 我們觀察Refs類,除了剛才的findMyFavoriteOfMemberEntity方法實現外,還多出一個抽象方法: findExFriendsOfMemberEntity
public abstract class Refs extends EntityRefQuery {/*** 返回前任男(女)朋友列表*/public abstract List findExFriendsOfMemberEntity(MemberEntity entity);}
在動手實現代碼前,我們先分析一下混亂的男女朋友關系在member表上,我們使用了一個性別字段 is_girl來區別是男的還是女的, 在戀愛關系表上,分別有2個外鍵girl_id, boy_id來標識一對戀人關系。 這樣,如果member是女的,要查詢所有前任男朋友,那么sql語句就如下:
select * from t_memberwhere is_deleted=0and id in (select boy_id from t_memeber_lovewhere status = ‘前任’and girl_id = ? – 女孩idand is_deleted = 0)
如果member是男的,要查詢所有前任女朋友,那么sql語句條件就要倒過來:
select * from t_memberwhere is_deleted=0and id in (select girl_id from t_memeber_lovewhere status = ‘前任’and boy_id= ? – 男孩idand is_deleted = 0)
實現查詢前男(女)朋友列表功能一般來說,為了實現上面的分支查詢,在mybatis的xml文件中需要配置 這樣的標簽代碼分支, 或者在java代碼中實現 if(…){}else{}的代碼邏輯分支。 那我們來看看fluent mybatis時如何實現上述查詢的呢?我們就可以在剛才定義的Refs子類上實現findExFriendsOfMemberEntity自己的邏輯。
@Servicepublic class AllRelationQuery extends Refs {@Overridepublic List findExFriendsOfMemberEntity(MemberEntity entity) {MemberQuery query = new MemberQuery().where.isDeleted().isFalse().and.id().in(MemberLoveQuery.class, q -> q.select(entity.getIsGirl() ? boyId.column : girlId.column).where.status().eq(“前任”).and.isDeleted().isFalse().and.girlId().eq(entity.getId(), o -> entity.getIsGirl()).and.boyId().eq(entity.getId(), o -> !entity.getIsGirl()).end()).end();return memberMapper.listEntity(query);}}
寫測試看log
@RunWith(SpringRunner.class)@SpringBootTest(classes = Application.class)public class FindExFriendsTest {@Autowiredprivate MemberMapper memberMapper;@Testpublic void findExBoyFriends() { MemberEntity member = memberMapper.findById(1L); System.out.println('是否女孩:' + member.getIsGirl()); List<MemberEntity> boyFriends = member.findExFriends(); System.out.println(boyFriends);}}
控制臺日志
DEBUG - ==> Preparing: SELECT id, …, user_name FROM t_member WHERE id = ?DEBUG - > Parameters: 1(Long)DEBUG - < Total: 1是否女孩:trueDEBUG - ==> Preparing: SELECT id, …, user_name FROM t_memberWHERE is_deleted = ?AND id IN (SELECT boy_idFROM t_member_loveWHERE status = ?AND is_deleted = ?AND girl_id = ?)DEBUG - > Parameters: false(Boolean), 前任(String), false(Boolean), 1(Long)DEBUG - < Total: 1[MemberEntity(id=2, gmtModified=Sun Nov 08 12:31:57 CST 2020, isDeleted=false, age=null, gmtCreated=null, isGirl=false, school=null, userName=mike)]
如日志所示,在查詢前男友列表是,條件會根據Member的是否是女孩進行分支切換,這也是fluent mybatis動態條件強大的地方。
到此這篇關于FluentMybatis快速入門詳細教程的文章就介紹到這了,更多相關Fluent Mybatis入門內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
