美文网首页
Mybatis-plus 注解实现多表关联查询的最佳实践

Mybatis-plus 注解实现多表关联查询的最佳实践

作者: 催化剂 | 来源:发表于2021-09-16 14:58 被阅读0次

    要用到Diboot开源包,https://github.com/dibo-software

    https://github.com/dibo-software/diboot-example

    原文地址

    1. 注解自动绑定数据字典(自定义枚举)的显示值Label

    开发过程中的枚举值,比如用户状态(ACTIVE:激活,LOCKED:锁定 ...)、身份证类型等,我们会将其名称name和值value定义在数据字典表,以支持扩展不改代码以及用户可编辑。其他数据表中关联该字典时,存储对应的value,显示时又需要查询字典表将value转换为对应的name。

    通过注解绑定,我希望简单使用如这样:

    @BindDict(type="USER_STATUS", field = "status")

    private String statusLabel;

    2. 注解自动绑定其他表的字段

    如部门实体Department(department表的Java映射对象)对应的VO对象中需要关联组织Organization实体(organization表的映射对象)。

    我希望简单使用如这样:

    // 支持关联条件+附加条件绑定字段

    @BindField(entity=Department.class, field="name", condition="department_id=id AND parent_id>=0")

    private String deptName;

    // 支持通过中间表的级联关联绑定字段

    @BindField(entity = Organization.class, field="name", condition="this.department_id=department.id AND department.org_id=id")

    private String orgName;

    3. 注解自动绑定其他表实体Entity

    如部门实体Department(department表的Java映射对象)对应的VO对象中需要关联组织Organization实体(organization表的映射对象)。

    我希望简单使用如这样:

    // 支持关联条件+附加条件绑定Entity

    @BindEntity(entity = Department.class, condition="department_id=id")

    private Department department;

    // 通过中间表的级联关联绑定Entity(支持附加条件)

    @BindEntity(entity = Organization.class, condition = "this.department_id=department.id AND department.org_id=id AND department.deleted=0")

    private Organization organization;

    4. 注解自动绑定其他表实体集合List<Entity>

    如部门实体Department对应的VO对象中需要关联多个子部门Department实体。

    我希望简单使用如这样:

    // 支持关联条件+附加条件绑定多个Entity

    @BindEntityList(entity = Department.class, condition = "id=parent_id")

    private List<Department> children;

    // 通过中间表的 多对多关联 绑定Entity(支持附加条件)

    @BindEntityList(entity = Role.class, condition="this.id=user_role.user_id AND user_role.role_id=id")

    private List<Role> roleList;

    实现以上方案,开发过程中的大部分关联场景SQL都可以大大简化,使代码具备极好的可维护性。另外以上方案实现需要拆解成单表查询SQL通过主键去查询,可以充分利用数据库缓存,提高性能。

    作者:一个鸡蛋壳儿

    链接:https://www.jianshu.com/p/b68a142509e7

    来源:简书

    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    相关文章

      网友评论

          本文标题:Mybatis-plus 注解实现多表关联查询的最佳实践

          本文链接:https://www.haomeiwen.com/subject/whokgltx.html