大家好,我是程序员柏风,AI 最全的 Vibecoding 学习地图 http://coderoadmap.cn 作者。
Spring Data 家族
Spring Data 不是单一项目,而是一组 Repository 抽象:JPA、MongoDB、Redis、Elasticsearch 等共享相似的 findByXxx 模式。
学习目标
- 区分 Spring Data JPA / MongoDB / Redis 职责
- 理解 CodeRoadMap「MySQL 主库 + 可选文档库」分工
- 与 mongo-spring 对照
家族一览
| 模块 | 存储 | 典型注解 | 本站角色 |
|---|---|---|---|
| Spring Data JPA | MySQL | @Entity | 主数据 cf_* |
| Spring Data MongoDB | MongoDB | @Document | 日志、实验 collection |
| Spring Data Redis | Redis | @RedisHash | 缓存、会话(若启用) |
关系型课程/进度 必须在 MySQL;Mongo 适合嵌套、写入频繁的辅助数据。
JPA Repository(主路径)
public interface LessonRepository extends JpaRepository<Lesson, Long> {
List<Lesson> findByTrackIdAndStatus(Long trackId, String status);
@Query("SELECT l FROM Lesson l JOIN FETCH l.track WHERE l.slug = :slug")
Optional<Lesson> findWithTrackBySlug(@Param("slug") String slug);
}
JOIN FETCH 缓解 N+1,详见 orm-nplus1。
MongoDB Repository(附加)
@Document(collection = "lesson_edit_logs")
public class LessonEditLog {
@Id private String id;
private Long lessonId;
private String diff;
}
public interface LessonEditLogRepository
extends MongoRepository<LessonEditLog, String> {}
不要把 cf_lesson.content_md 整体迁到 Mongo 除非有明确产品需求——会破坏 sql-essentials 主线一致性。
配置共存
spring:
datasource:
url: jdbc:mysql://localhost:3306/codeforge
data:
mongodb:
uri: mongodb://127.0.0.1:27017/coderoadmap_lab
两套 Repository 包路径分开,Service 层明确调用哪条存储。
相关课程
练习
- 列举三条适合 MySQL、三条适合 Mongo 的数据(本站语境)
- 解释为何
JpaRepository与MongoRepository不能混继承 - 读 mongo-spring 的配置段
小结
Spring Data 用统一 Repository 风格对接多种存储;本站以 JPA+MySQL 为权威。 下一课讲 Schema 迁移。