package com.learn.service.mp; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.learn.entity.Student; import com.learn.repository.mp.StudentMapper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; @Service public class StudentMpService { private final StudentMapper mapper; public StudentMpService(StudentMapper mapper) { this.mapper = mapper; } @Transactional public Student add(Student s) { mapper.insert(s); return s; } @Transactional(readOnly = true) public List list() { LambdaQueryWrapper w = new LambdaQueryWrapper<>(); w.orderByDesc(Student::getScore); return mapper.selectList(w); } @Transactional(readOnly = true) public Optional getById(Long id) { return Optional.ofNullable(mapper.selectById(id)); } @Transactional(readOnly = true) public List search(String keyword) { LambdaQueryWrapper w = new LambdaQueryWrapper<>(); w.like(Student::getName, keyword).or().like(Student::getEmail, keyword); w.orderByDesc(Student::getScore); return mapper.selectList(w); } @Transactional public Optional update(Long id, Student updated) { Student existing = mapper.selectById(id); if (existing == null) return Optional.empty(); 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()); mapper.updateById(existing); return Optional.of(existing); } @Transactional public boolean delete(Long id) { return mapper.deleteById(id) > 0; } @Transactional(readOnly = true) public IPage page(int pageNum, int pageSize, String keyword) { Page page = new Page<>(pageNum, pageSize); LambdaQueryWrapper w = new LambdaQueryWrapper<>(); if (keyword != null && !keyword.trim().isEmpty()) { w.like(Student::getName, keyword).or().like(Student::getEmail, keyword); } w.orderByDesc(Student::getScore); return mapper.selectPage(page, w); } @Transactional(readOnly = true) public long count() { return mapper.selectCount(null); } @Transactional(readOnly = true) public long countExcellent(int minScore) { LambdaQueryWrapper w = new LambdaQueryWrapper<>(); w.ge(Student::getScore, minScore); return mapper.selectCount(w); } @Transactional public Student updateAvatar(Long id, String filename) { Student s = mapper.selectById(id); if (s == null) throw new RuntimeException("学生不存在"); s.setAvatar(filename); mapper.updateById(s); return s; } }