上一篇 無SQL實現單表CRUD中咱們已經經過Mybatis-plus插件的通用Mapper實現了單表的CRUD的無SQL化,已經能夠有效減小Mybatis的代碼量。但實際開發場景下,多數業務需求實現要涉及關聯查詢,你能夠經過本身寫SQL的方式去作,或者再深刻思考一下有沒有更方便的實現方案呢?
如department表中有org_id字段,關聯organization表的id字段,前端顯示Department部門信息時須要顯示組織名稱organization.name。前端
class DepartmentVO{ String orgName; //關聯organization表的name字段 }
如department表中有狀態字段status,存儲值是"A","I"...,顯示時須要轉換爲"正常","無效"...。java
class DepartmentVO{ String statusLabel; //關聯字典錶轉換爲顯示值 }
如部門實體Department(department表的Java映射對象)對應的VO對象中須要關聯組織Organization實體(organization表的映射對象)。git
class DepartmentVO { Organization organization; //1對1關聯另外的實體 }
如部門實體Department對應的VO對象中須要關聯多個子部門Department實體。github
class DepartmentVO{ List<Department> children; //1對多關聯另外的實體 }
Mybatis-plus並未實現關聯查詢的解決方案:
對於字段關聯,一般的解決方案是SQL關聯查詢,如:sql
SELECT d.*, o.name as orgName, m.item_label as statusLabel FROM department d LEFT JOIN organization o ON d.org_id=o.id LEFT JOIN metadata m ON u.status=m.item_value AND m.type='STATUS'
或者經過另一種不太優雅的方式:查詢整個表獲得id-name的Map,而後經過Java代碼去綁定。segmentfault
對於關聯一個或多個實體的狀況,通常經過Mybatis的association實現:app
<resultMap type="XX" id="xx"> <association select="..."> </resultMap>
不寫SQL,不經過Mybatis的association,要更優雅的實現關聯的自動綁定,一個主流的方案就是相似JPA的註解了。JPA的註解須要複雜的設置,咱們能夠只借鑑其思想,將註解儘量的簡化。框架
首先,須要明確關聯到哪一個表(實體),另外無論是哪一種關聯都必需要有關聯條件condition,而後是字段關聯呢咱們須要指定字段名field。this
那麼咱們能夠將註解定義簡化以下:插件
public class DepartmentVO { ... // 關聯Entity中的某字段 @BindField(entity=Organization.class, field="name", condition="this.org_id=id") private String orgName; // 關聯Entity @BindEntity(entity=Organization.class, condition="this.org_id=id") private Organization organization; // 關聯多個Entity @BindEntityList(entity=Department.class, condition="this.id=parent_id") private List<Department> children; }
簡化的使用意味着要有完善的實現邏輯,後續的章節咱們將具體講解這些關聯綁定註解的實現方案。