Week 1-8: Spring Boot 学习计划完整项目

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-04-29 23:45:17 +08:00
commit f95aa18724
201 changed files with 18595 additions and 0 deletions

View File

@@ -0,0 +1,76 @@
package com.learn.service;
import com.learn.model.Student;
import com.learn.repository.StudentRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
/**
* 第 5 天:业务逻辑层 —— 学生服务
*
* 负责业务规则的校验和处理,介于 Controller 和 Repository 之间。
* Controller 只负责接收请求和返回响应,业务逻辑全部在 Service 中。
*
* @Service 注解:标记这是业务逻辑层组件,被 Spring 扫描并管理
*/
@Service
public class StudentService {
private final StudentRepository repository;
/**
* 构造方法注入(推荐方式,比 @Autowired 字段注入更安全,也更容易测试)
* Spring 会自动从容器中找到 StudentRepository 并传入
*/
public StudentService(StudentRepository repository) {
this.repository = repository;
}
/** 新增学生 */
public Student add(Student student) {
// 业务校验可以放在这里,例如检查邮箱是否已注册等
return repository.save(student);
}
/** 查询全部 */
public List<Student> list() {
return repository.findAll();
}
/** 根据 ID 查询 */
public Optional<Student> getById(Long id) {
return repository.findById(id);
}
/** 模糊搜索 */
public List<Student> search(String keyword) {
if (keyword == null || keyword.trim().isEmpty()) {
return List.of();
}
return repository.findByName(keyword);
}
/** 更新学生 */
public Optional<Student> update(Long id, Student updated) {
return repository.findById(id).map(existing -> {
// 只更新非 null 的字段
if (updated.getName() != null) existing.setName(updated.getName());
if (updated.getAge() > 0) existing.setAge(updated.getAge());
if (updated.getEmail() != null) existing.setEmail(updated.getEmail());
if (updated.getScore() >= 0) existing.setScore(updated.getScore());
return repository.save(existing);
});
}
/** 删除学生 */
public boolean delete(Long id) {
return repository.deleteById(id);
}
/** 总数 */
public long count() {
return repository.count();
}
}