外观
练习 — Repository 与 ORM
对应知识点:
Repository Pattern·ORM·sqlc对应文档:docs/phase-04-database/repository-orm.md代码目录:workspace/phase-04/repository/
前置条件:完成 database/sql 练习。
Level 1 — 基础
练习 1.1 · Repository 接口
在 workspace/phase-04/repository/ 定义:
要求:
internal/domain/device.go:Device实体internal/domain/repository.go:DeviceRepositoryinterfaceGetByID(ctx, id) (Device, error)List(ctx, filter ListFilter) ([]Device, error)Create(ctx, Device) error
练习 1.2 · Postgres 实现
要求:
internal/repository/postgres/device_repo.go实现 interface- 构造函数
NewDeviceRepository(db *sql.DB) DeviceRepository - service 层只依赖 interface
练习 1.3 · 内存实现(测试用)
要求:
internal/repository/memory/device_repo.go- 与 postgres 实现相同 interface
- main 或测试可切换注入
Level 2 — 应用
练习 2.1 · 领域模型与 DB 模型分离
要求:
dbDevicestruct 对应表字段(可含 sql.NullString)- 转换函数
toDomain(dbDevice) Device - Repository 内部转换,对外只暴露 domain.Device
练习 2.2 · GORM 初体验(可选)
要求:
go get gorm.io/gorm+ postgres driver- 定义 GORM model 对应 devices 表
- AutoMigrate + Find / First / Create 基本操作
- 对比 raw SQL 写法,记录 3 点优劣
练习 2.3 · 查询封装
要求:
ListFilter支持:Status、WarehouseID、Page、PageSize- Repository 动态构建 WHERE(手写或 ORM)
- 返回
([]Device, total int, error)
Level 3 — 综合
练习 3.1 · 多 Repository 组合
要求:
TelemetryRepository:ListByDevice(ctx, deviceID, limit)AlertRepository:ListCritical(ctx)DeviceService组合多个 repo 提供GetDeviceDashboard(ctx, id)
练习 3.2 · sqlc 概念(可选)
要求:
- 在
queries/devices.sql写命名查询 - 了解 sqlc 生成 Go 代码的流程(可只写 SQL + 文档说明,不强制生成)
- 说明 sqlc 与 GORM 选型场景
Level 4 — 项目实践
练习 4.1 · 数字孪生数据访问层
在 workspace/phase-04/repository/ 完成完整 DAL:
目录:
internal/
├── domain/ # Device, Telemetry, Alert, Repository interfaces
├── repository/
│ ├── postgres/ # 生产实现
│ └── memory/ # 测试实现
└── service/ # 业务编排
cmd/server/main.go # 注入 postgres repo要求:
- 覆盖 devices CRUD + telemetry 查询 + critical alerts
- 单元测试使用 memory repo
- 集成测试使用 testcontainers 或 docker postgres(可选)
- README:架构图、切换 memory/postgres 方式
- 为 Phase 05 Redis 缓存层预留
CachedDeviceRepository装饰器接口(可只定义不实现)
学习检查
- [ ] Repository 模式解决什么问题?
- [ ] ORM 的 N+1 问题是什么?
- [ ] domain 模型与 DB model 为何要分离?
- [ ] 何时选手写 SQL vs ORM vs sqlc?
提交方式
检查答案 — repository orm 练习 X.X