Mybatis Flex 常见用法

文章目录

  • Mybatis Flex 常见用法
    • 一、枚举
    • 二、自动填充
      • 2.1 方式一:@Table 配置
      • 2.2 方式二:@Column 配置
    • 三、分页
      • 3.1 分页统一接口
      • 3.2 实现分页接口
      • 3.3 使用
    • 四、关联查询
      • 4.1 @RelationOneToOne:一对一
        • 4.1.1 单向关联
        • 4.1.2 双向关联
      • 4.2 @RelationOneToMany && @RelationManyToOne:一对多 和 多对一
        • 4.2.1 单向关联
        • 4.2.2 双向关联
      • 4.3 @RelationManyToMany:多对多
        • 4.3.1 单向关联
        • 4..3.2 双向关联
      • 4.4 ByQuery
    • 五、多数据源
      • 5.1 配置
        • 5.1.1 application.yml (必须)
        • 5.1.2 @Table(dataSource = "slave01")(选择配置)
        • 5.1.2 @UseDataSource(选择配置)
      • 5.3 使用
    • 六、读写分离
      • 6.1 读写分离策略
      • 6.2 配置
    • 七、其他
      • 5.1 逻辑删除
      • 5.2 数据脱敏

Mybatis Flex 常见用法

一、枚举

  • 枚举类

    @Getter
    @AllArgsConstructor
    public enum GradeEnum {UNKNOWN(0, "未知"),SECONDARY(2, "中学"),PRIMARY(1, "小学"),HIGH(3, "高中");@EnumValue // 数据库存储字段private final Integer code;@JsonValue // 转 Json 字段private final String  name;
    }
    
  • 使用

    @Data
    @Table(value = "t_student")
    public class Student {@Id(keyType = KeyType.Auto)private Integer id;// 枚举private GradeEnum grade;
    }
    

二、自动填充

2.1 方式一:@Table 配置

  • 监听器

    public class AutoFillListener implements InsertListener, UpdateListener {@Overridepublic void onInsert(Object o) {BaseEntity baseEntity = (BaseEntity) o;// TODO 获取当前用户String username = "测试用户";Date now = new Date();baseEntity.setCreatedBy(username);baseEntity.setCreatedTime(now);baseEntity.setUpdatedBy(username);baseEntity.setUpdatedTime(now);}@Overridepublic void onUpdate(Object o) {BaseEntity baseEntity = (BaseEntity) o;// TODO 获取当前用户String username = "测试用户";Date now = new Date();baseEntity.setUpdatedBy(username);baseEntity.setUpdatedTime(now);}
    }
    
  • 注解配置

    @EqualsAndHashCode(callSuper = true)
    @Data
    @Table(value = "t_product", onInsert = AutoFillListener.class, onUpdate = AutoFillListener.class)
    public class Product extends BaseEntity {@Id(keyType = KeyType.Auto)private Integer id;private String name;private GradeEnum grade;
    }
    @Data
    public abstract class BaseEntity implements Serializable {// 创建人private String createdBy;// 创建时间private Date createdTime;// 更新人private String updatedBy;// 更新时间private Date updatedTime;
    }
    

2.2 方式二:@Column 配置

@Data
public abstract class BaseEntity implements Serializable {@Column(onInsertValue = "'测试'")// 创建人private String createdBy;// 创建时间@Column(onInsertValue = "now()")private Date createdTime;// 更新人@Column(onInsertValue = "'测试'", onUpdateValue = "'测试'")private String updatedBy;// 更新时间@Column(onInsertValue = "now()", onUpdateValue = "now()")private Date updatedTime;
}

三、分页

3.1 分页统一接口

public interface AppPage<T> {/*** 当前页页码*/long getPageNum();/*** 每页条数*/long getPageSize();/*** 总条数*/long getTotal();/*** 总页数*/long getTotalPages();/*** 分页对象记录*/List<T> getItems();
}

3.2 实现分页接口

@AllArgsConstructor
public class MybatisFlexPageImpl<T> implements AppPage<T> {private Page<T> page;@Overridepublic long getPageNum() {if (page == null) return  0;return page.getPageNumber();}@Overridepublic long getPageSize() {if (page == null ) return 0;return page.getPageSize();}@Overridepublic long getTotal() {if (page == null ) return 0;return page.getTotalRow();}@Overridepublic long getTotalPages() {if (page == null ) return 0;return page.getTotalPage();}@Overridepublic List<T> getItems() {return page.getRecords();}
}

3.3 使用

@RestController
@RequestMapping("product")
public class ProductController {@GetMapping("page")public AppPage<Product> page (){Page<Product> paginate = productRepo.paginate(1, 2, QueryCondition.createEmpty());return new MybatisFlexPageImpl<Product>(paginate);}
}

四、关联查询

4.1 @RelationOneToOne:一对一

4.1.1 单向关联
  • User

    @Data
    @Table(value = "t_user")
    public class User {@Id(keyType = KeyType.Auto)private Integer id;@RelationOneToOne(selfField = "id", targetField = "userId") // selfField 为主键可省略private UserInfo userInfo;
    }
    
  • UserInfo

    @Data
    @Table(value = "t_user_info")
    public class UserInfo {@Id(keyType = KeyType.Auto)private Integer id;private Integer userId; // 一对一关系,对应的关联字段
    }
    
4.1.2 双向关联
  • User

    @Data
    @Table(value = "t_user")
    public class User {@Id(keyType = KeyType.Auto)private Integer id;@RelationOneToOne(selfField = "id", targetField = "userId") // selfField 为主键可省略private UserInfo userInfo;
    }
    
  • UserInfo

    @Data
    @Table(value = "t_user_info")
    public class UserInfo {@Id(keyType = KeyType.Auto)private Integer id;@RelationOneToOne(selfField = "userId", targetField = "id")private User user;private Integer userId;
    }
    

4.2 @RelationOneToMany && @RelationManyToOne:一对多 和 多对一

4.2.1 单向关联
  • @RelationOneToMany

    Group

    @Data
    @Table(value = "t_group")
    public class Group {@Id(keyType = KeyType.Auto)private Integer id;// 单向关联@RelationOneToMany(selfField = "id", targetField = "groupId")List<Student> studentList;
    }
    

    Student

    @Data
    @Table(value = "t_student")
    public class Student {@Id(keyType = KeyType.Auto)private Integer id;private Integer groupId; // 单向关联字段
    }
    
  • @RelationManyToOne

    Student

    @Data
    @Table(value = "t_student")
    public class Student {@Id(keyType = KeyType.Auto)private Integer id;// 单向关联@RelationManyToOne(selfField = "groupId", targetField = "id")private Group group;private Integer groupId;
    }
    

    Group

    @Data
    @Table(value = "t_group")
    public class Group {@Id(keyType = KeyType.Auto)private Integer id;
    }
    
4.2.2 双向关联
  • Student

    @Data
    @Table(value = "t_student")
    public class Student {@Id(keyType = KeyType.Auto)private Integer id;// 双向关联@RelationManyToOne(selfField = "groupId", targetField = "id")private Group group;private Integer groupId;
    }
    
  • Group

    @Data
    @Table(value = "t_group")
    public class Group {@Id(keyType = KeyType.Auto)private Integer id;// 单向关联@RelationOneToMany(selfField = "id", targetField = "groupId")List<Student> studentList;
    }
    

4.3 @RelationManyToMany:多对多

4.3.1 单向关联
@Data
@Table(value = "t_user")
public class User {@Id(keyType = KeyType.Auto)private Integer id;@RelationManyToMany(joinTable = "t_user_role",  // 中间表selfField = "id", joinSelfColumn = "user_id", // selfField 为主键时可省略targetField = "id", joinTargetColumn = "role_id") // targetField 为主键时可省略private List<Role> roles;
}
4…3.2 双向关联
  • User

    @Data
    @Table(value = "t_user")
    public class User {@Id(keyType = KeyType.Auto)private Integer id;@RelationManyToMany(joinTable = "t_user_role", // 中间表selfField = "id", joinSelfColumn = "user_id", // selfField 为主键时可省略targetField = "id", joinTargetColumn = "role_id") // targetField 为主键时可省略private List<Role> roles;
    }
    
  • Role

    @Data
    @Table(value = "t_role")
    public class Role {@Id(keyType = KeyType.Auto)private Integer id;@RelationManyToMany(joinTable = "t_user_role",joinSelfColumn = "role_id",joinTargetColumn = "user_id")private List<User> userList;
    }
    

4.4 ByQuery

@SpringBootTest
public class TableAssociation {   @Autowiredprivate StudentMapper studentMapper;@Autowiredprivate GroupMapper groupMapper;@Test // 关联查询public void associationQuery() {// 查询 Student 及对应的 GroupList<Student> students = studentMapper.selectListByQuery(QueryWrapper.create(),fb -> fb.field(Student::getGroup).queryWrapper(student ->{Group group = new Group();group.setId(student.getId());return QueryWrapper.create(group);}));System.out.println(students);// 查询 Group 及对应的 StudentList<Group> groups = groupMapper.selectListByQuery(QueryWrapper.create(),f -> f.field(Group::getStudentList).queryWrapper(group -> {Student student = new Student();student.setGroupId(group.getId());return QueryWrapper.create(student);}));System.out.println(groups);}
}

五、多数据源

DataSourceKey.use() > @UseDataSource()在方法上 > @UseDataSource()在类上 >@Table(dataSource=“…”)

5.1 配置

5.1.1 application.yml (必须)
mybatis-flex:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpldatasource:master:url: jdbc:mysql://localhost:3336/test?serverTimezone=UTCusername: rootpassword: 123456slave01:url: jdbc:mysql://localhost:3337/test?serverTimezone=UTCusername: rootpassword: 123456
5.1.2 @Table(dataSource = “slave01”)(选择配置)
@Data
@Table(value = "t_student",dataSource = "slave01")
public class Student {}
5.1.2 @UseDataSource(选择配置)
@Mapper
@UseDataSource("slave01") // 用于类
public interface GroupMapper extends BaseMapper<Group> {}@Mapper
public interface ProductMapper extends BaseMapper<Product> {@UseDataSource("master") // 用于方法@Select("select * from t_product") List<Product> findAll();
}

5.3 使用

@SpringBootTest
public class MoreSourceTest {@Autowiredprivate StudentMapper studentMapper;@Autowiredprivate UserMapper userMapper;@Autowiredprivate GroupMapper groupMapper;/*** 使用 @Table(dataSource = "master")*/@Testpublic void get() {List<Student> students = studentMapper.selectAll();System.out.println(students);List<User> users = userMapper.selectAll();System.out.println(users);}/*** 使用 @UseDataSource("master")*/@Testpublic void get2 (){List<Group> groups = groupMapper.selectAll();System.out.println(groups);}/*** 使用 DataSourceKey.use("master")*/@Testpublic void get3 (){List<Group> groups = groupMapper.selectAll();System.out.println(groups);try {DataSourceKey.use("master");List<Row> rows = Db.selectAll("t_Group");List<Group> groupList = rows.stream().map(e -> {Group group = new Group();BeanUtil.copyProperties(e, group);return group;}).toList();System.out.println(groupList);}finally {DataSourceKey.clear();}}
}

六、读写分离

6.1 读写分离策略

@Slf4j
public class ReaderAndWriterStrategy implements DataSourceShardingStrategy {private static final String MASTER = "master";private static final String SLAVE = "slave*";@Overridepublic String doSharding(String currentDataSourceKey, Object mapper, Method mapperMethod, Object[] methodArgs) {// 增删改 用 masterif (StringUtil.startsWithAny(mapperMethod.getName(),"insert","delete","update")){return MASTER;}// 其他场景使用 slave开头 的数据源进行负载均衡return SLAVE;}
}

6.2 配置

@Configuration
public class ReaderAndWriterConfig {@Beanpublic DataSourceManager dataSourceManager(){DataSourceManager dataSourceManager = new DataSourceManager();dataSourceManager.setDataSourceShardingStrategy(new ReaderAndWriterStrategy());return dataSourceManager;}
}

七、其他

5.1 逻辑删除

@Data
@Table(value = "t_student")
public class Student {@Id(keyType = KeyType.Auto)private Integer id;@Column(isLogicDelete = true)private boolean deleted;
}

5.2 数据脱敏

@Data
@Table(value = "t_student")
public class Student {@Id(keyType = KeyType.Auto)private Integer id;@ColumnMask(Masks.CHINESE_NAME) // 自带脱敏private String name;@ColumnMask("sexMask") // 自定义脱敏private String sex;static { // 自定义脱敏逻辑MaskManager.registerMaskProcessor("sexMask", data -> "*");}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/238248.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在laravel 项目中 composer.json 中 autoload 配置是什么作用

在 Laravel 项目中&#xff0c;composer.json 文件是一个重要的文件&#xff0c;它用于定义项目依赖以及一些 Composer 的配置。其中 autoload 是一个键&#xff08;key&#xff09;&#xff0c;其下定义了如何自动加载 PHP 类库。 autoload 的作用是告诉 Composer 和 PHP 解释…

【krita】实时绘画 入门到精通 海报+电商+装修+修复手部

安装插件 首先打开comfyUI&#xff0c;再打开krita&#xff0c;出现问题提示&#xff0c; 打开 cd custom_nodes 输入命令 安装控件 git clone https://github.com/Acly/comfyui-tooling-nodes.git krita基础设置 设置模型 设置lora &#xff08;可设置lora强度 增加更多…

华纳云:怎么用python实现进程,线程和协程

在Python中&#xff0c;可以使用multiprocessing模块来创建进程&#xff0c;使用threading模块来创建线程&#xff0c;以及使用asyncio模块来创建协程。以下是简单的示例代码演示如何使用Python实现进程、线程和协程&#xff1a; 进程&#xff08;multiprocessing&#xff09;…

网站使用https认证

随着网络的普及和依赖程度的增加&#xff0c;网站安全性问题也日益凸显。为了确保用户和网站之间的数据传输安全&#xff0c;采用HTTPS认证已经变得至关重要。 1.数据安全是首要任务 在互联网上&#xff0c;信息传输是网站运作的基础。然而&#xff0c;未加密的传输容易受到中…

嵌入式中的基本定时器

学习目标 理解基本定时器的作用掌握定时器开发流程掌握基本定时器中断处理的操作流程掌握AHB和APB时钟查询方式理解周期,分频系数,周期计数,分频计数。掌握调试策略学习内容 基本定时器 只能用于定时计时操作,没有输出引脚通道的定时器,在GD32中, TIMER5和TIMER6为基本…

电子科大软件测试~第三次作业

第三次作业 第一题 采用JUnit软件测试框架进行测试程序编程&#xff0c;实现对下面java程序进行单元测试&#xff0c;找出其中缺陷。然后修改缺陷&#xff0c;直到通过单元测试&#xff0c;给出测试程序脚本和运行结果界面。 public class getMax {public int get_max(int x…

读取导入的excel表格内容,插入到表格,同时做去重,j前端通过js实现模糊查询

1.导入的excel模版 2.点击导入&#xff0c;显示excel导入弹窗 3.点击选择文件&#xff0c;会调用本地文件夹里面的excel文件 4.选中文件&#xff0c;点击 导入 html部分 <a-button type"primary" click"onImportXls">导入</a-button><…

初识Python之Networkx模块

初识Python之Networkx模块 文章目录 初识Python之Networkx模块简介安装Networkx导入模块、查看版本信息一些基本操作创建Graph添加边&#xff08;节点&#xff09;获取Graph的基本信息Graph的基本绘图 简单应用案例使用内置的Graph数据创建一个无向图创建一个有向图在计算机网络…

leetCode算法—14. 最长公共前缀

14.编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀&#xff0c;返回空字符串 “”。 难度&#xff1a;简单 * 示例 1&#xff1a; 输入&#xff1a;strs [“flower”,“flow”,“flight”] 输出&#xff1a;“fl” 示例 2&#xff1a; 输入&#xff1a…

LeetCode239. Sliding Window Maximum

文章目录 一、题目二、题解 一、题目 You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window m…

【halcon深度学习之那些封装好的库函数】find_dl_samples

函数简介 find_dl_samples 是一个用于检索满足特定条件的深度学习数据集样本索引的过程。让我们逐步详细解释它的输入参数和功能&#xff1a; Samples: 这是包含样本字典或样本字典元组的输入参数。这些样本是将要被搜索的对象。 KeyName: 用于指定要查找的条目的键名。在样本…

关于“Python”的核心知识点整理大全35

目录 13.3.4 重构 create_fleet() game_functions.py 13.3.5 添加行 game_functions.py alien_invasion.py 13.4 让外星人群移动 13.4.1 向右移动外星人 settings.py alien.py alien_invasion.py game_functions.py 13.4.2 创建表示外星人移动方向的设置 13.4.3 检…

【第七在线】可持续时尚与商品计划:减少库存浪费的方法

随着可持续时尚的崭露头角&#xff0c;服装企业越来越重视减少库存浪费。库存浪费不仅对环境造成负面影响&#xff0c;还对企业的经济可持续性产生负面影响。本文将深入探讨可持续时尚与商品计划之间的关系&#xff0c;以及一些减少库存浪费的方法&#xff0c;有助于改进商品计…

源码订货系统的优势

源码订货系统是一种企业购买后可以获得源代码的订货系统&#xff0c;它可以不受软件厂商的规模、发展而修改和使用。与SaaS订货系统相比&#xff0c;核货宝为您分享源码订货系统的四大优势&#xff1a; 一是开放性&#xff1a;源码订货系统是开源的&#xff0c;用户可以掌握源代…

解决IDEA编译/启动报错:Abnormal build process termination

报错信息 报错信息如下&#xff1a; Abnormal build process termination: "D:\Software\Java\jdk\bin\java" -Xmx3048m -Djava.awt.headlesstrue -Djava.endorsed.dirs\"\" -Djdt.compiler.useSingleThreadtrue -Dpreload.project.path………………很纳…

【Python百宝箱】时序之美:Python 时间序列探秘与创新

时光漫游&#xff1a;Python 时间序列分析全指南 前言 在数字化时代&#xff0c;时间序列数据扮演着关键的角色&#xff0c;从金融到气象再到生产制造。本文将引导你穿越Python丰富的时间序列分析工具&#xff0c;探索从基础统计到机器学习和深度学习的各个层面。无论你是初学…

MySQL概括与SQL分类

文章目录 一、计算机语言二、SQL语言三、数据库系统四、MySQL简介 一、计算机语言 二、SQL语言 三、数据库系统 四、MySQL简介

ZZ014城市轨道交通运营与维护赛题第5套

ZZ014城市轨道交通运营与维护赛题第5套 模块1赛题 模块序号 模块1 对应赛项编号 ZZ014 模块名称 城市轨道交通运营服务 子任务数量 12 竞赛时间 60分钟 任务描述 行车组织作业、票务设备故障处置以及突发事件应急处理 职业要素 R基本专业素养 R专业实践技能 R协…

【MySQL】事务、事务隔离级别、死锁

文章目录 1. 事务1.1 事务的属性 ACID1.2 创建事务1.3 autocommit 2. 并发和锁定2.1 并发问题 3. 事务隔离级别3.1 读未提交3.2 读已提交3.3 可重复读&#xff1a;MySQL的默认事务隔离级别3.4 序列化 4. 死锁 1. 事务 事务&#xff1a;单个工作单元的一组SQL语句。事务中的所有…

Python的环境搭建环境配置()

Python 环境搭建 一,下载Python 1.去官网 www.python.org 下载环境 2.如图点击Download 3.选择Windows 4.如图直接下载 5.直接勾选 6.后面就一直默认选项 Win11 安装目录 不能放在C盘的ProgramFIle路径下 二,测试环境是否安装成功 1.winR 输入cmd 2.输入python --versio…