Expand description
Entity Graph + @BatchSize 批量抓取
对应文档 6.8 节改进项 27(Entity Graph)+ 28(@BatchSize 批量抓取)。
§核心概念
- EntityGraph:实体图,定义一组关联关系一起抓取,避免 N+1 查询
- BatchSizeConfig:批量抓取配置(大小 + 策略)
- BatchLoader:通用批量加载器,将 N 次单条查询合并为 ⌈N/batch_size⌉ 次批量查询
- BatchStrategy:批量策略(IN / JOIN / SUBQUERY)
§设计灵感
- Hibernate
@NamedEntityGraph/@BatchSize - Doctrine
FetchMode::EAGER/ partial - Django
select_related/prefetch_related - Sequelize
include+separate: true
§使用示例
use sz_orm_query::entity_graph::{EntityGraph, BatchLoader, BatchSizeConfig, BatchStrategy};
use std::collections::HashMap;
// 1. 定义 EntityGraph:抓取 user.posts.comments
let mut graph = EntityGraph::new();
graph.add_edge("user", "posts");
graph.add_edge_with_graph("posts", "comments", {
let mut sub = EntityGraph::new();
sub.add_edge("comments", "author");
sub
});
// 2. 使用 BatchLoader 批量加载用户
fn load_users(ids: &[i64]) -> HashMap<i64, String> {
ids.iter().map(|id| (*id, format!("user_{}", id))).collect()
}
let loader = BatchLoader::new(100, Box::new(load_users));
let users = loader.load_many(&[1, 2, 3, 4, 5]);
assert_eq!(users.len(), 5);
assert_eq!(users.get(&3), Some(&"user_3".to_string()));Structs§
- Batch
Loader - 批量加载器
- Batch
Size Config - 批量大小配置
- Entity
Graph - 实体图
- Graph
Edge - 实体图边(关联关系)
- N1Alert
- N+1 查询告警
- N1Detection
Config - N+1 检测配置
- N1Query
Detector - N+1 查询检测器
Enums§
- Batch
Strategy - 批量抓取策略
Type Aliases§
- Batch
Loader Fn - 批量加载函数类型