Repository 负责“怎么取数据”,Service 负责“取出来之后按什么规则处理”。把这两层混在一起,代码会变成一坨:Controller 里写 SQL,Repository 里判断权限,最后谁都不敢改。
图 8-1 Controller → Service → Repository → Entity → MySQL
11.1 Service 的职责
一个 Service 方法通常做四件事:
- 校验业务条件(课程是否存在、用户是否有权限);
- 组合多个 Repository 的数据;
- 在事务里修改多张表;
- 把 Entity 转成 DTO 返回。
@Service
public class CourseService {
private final CourseRepository courseRepository;
private final ChapterRepository chapterRepository;
public CourseService(CourseRepository courseRepository,
ChapterRepository chapterRepository) {
this.courseRepository = courseRepository;
this.chapterRepository = chapterRepository;
}
public List<CourseBrief> listForMenu() {
return courseRepository.findByValidOrderBySortNoAscIdAsc("1")
.stream()
.map(c -> new CourseBrief(c.getId(), c.getName(), c.getBref()))
.toList();
}
}
11.2 构造器注入
用构造器注入,不要用字段上的 @Autowired。原因:依赖一目了然、方便单元测试、不会出现循环依赖时偷偷创建半成品对象。
private final CourseRepository repository;
public CourseService(CourseRepository repository) {
this.repository = repository;
}
@Autowired
private CourseRepository repository;
11.3 DTO:不要直接返回 Entity
Entity 是数据库结构,可能包含密码、内部状态、懒加载关联。直接返回会给前端多余字段,还可能触发序列化异常。
public record CourseBrief(Integer id, String name, String bref) {}
public record CourseDetail(Integer id, String name, String intro, int chapterCount) {}
Java 17 的 record 很适合做只读 DTO。需要可变对象时用普通类。
public CourseDetail detail(int id) {
Course c = courseRepository.findById(id)
.orElseThrow(() -> new BizException("课程不存在"));
int count = chapterRepository.countByCourseId(String.valueOf(id));
return new CourseDetail(c.getId(), c.getName(), c.getIntro(), count);
}
11.4 业务异常
不要用 return null 表示失败。定义自己的异常,让全局异常处理器统一转成 JSON。
public class BizException extends RuntimeException {
private final String code;
public BizException(String message) {
this("400", message);
}
public BizException(String code, String message) {
super(message);
this.code = code;
}
public String getCode() { return code; }
}
@ExceptionHandler(BizException.class)
public Result<Void> handleBiz(BizException e) {
return Result.fail(e.getCode(), e.getMessage());
}
11.5 事务边界放在 Service
Controller 不开启事务,Repository 不负责事务。一个业务动作在 Service 的一个方法里完成。
@Transactional
public void saveCourse(CourseForm form) {
Course c = new Course();
c.setName(form.name());
c.setValid("0");
courseRepository.save(c);
Chapter first = new Chapter();
first.setCourseId(String.valueOf(c.getId()));
first.setCode("010000");
first.setName("课程介绍");
chapterRepository.save(first);
}
事务方法里不要做远程调用、发消息、写文件。这些操作不会跟着数据库回滚,失败后数据会不一致。
11.6 查询与组装的边界
列表页只需要少量字段时,不要让 Repository 查完整实体。章节正文可能几十 KB,列表一次查几百条会把内存和网络打满。
@Query("select new cn.jssp.demo.dto.ChapterBrief(c.id, c.code, c.name, c.score) " +
"from Chapter c where c.courseId = ?1 order by c.code")
List<ChapterBrief> findBriefByCourse(String courseId);
这就是本站章节接口从 6 秒降到 0.1 秒的关键:列表不查 content 大字段。
11.7 缓存要谨慎
课程菜单、配置这类“读多写少”的数据可以缓存。但缓存一上,就要回答:什么时候失效?更新后怎么通知?多台机器怎么一致?
@Cacheable("courseMenu")
public List<CourseBrief> listForMenu() { ... }
@CacheEvict(value = "courseMenu", allEntries = true)
public void saveCourse(CourseForm form) { ... }
初学阶段先用数据库查询,确认慢在哪,再加缓存。不要为了“看起来专业”引入 Redis,最后数据不一致更难查。
11.8 单元测试
Service 是最值得测试的一层:不依赖 HTTP,也不依赖浏览器。用 Mockito 模拟 Repository。
@ExtendWith(MockitoExtension.class)
class CourseServiceTest {
@Mock CourseRepository repository;
@InjectMocks CourseService service;
@Test
void detailThrowsWhenMissing() {
when(repository.findById(1)).thenReturn(Optional.empty());
assertThrows(BizException.class, () -> service.detail(1));
}
}
11.9 本章练习
- 把课程列表改成返回
CourseBrief,不暴露 intro 大字段。
- 给“保存课程并创建第一章”加事务,故意让第二步抛异常,确认第一步回滚。
- 为
detail 写两个测试:存在、不存在。
下一章讲登录与权限:session、token、密码存储、越权。