web大作业开发记录03
学生后台spring接口实现:
GoalsController:
package com.example.demo.controller;
import com.example.demo.common.Result;
import com.example.demo.entity.Goals;
import com.example.demo.entity.SubGoals;
import com.example.demo.mapper.SubGoalsMapper;
import com.example.demo.service.GoalsService;
import com.example.demo.service.SubGoalsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/goals")
public class GoalsController {
@Autowired
private GoalsService goalsService;
@Autowired // 添加 @Autowired 注解
private SubGoalsService subGoalsService;
@PostMapping("/add")
public Result addGoal(@RequestBody Map<String, Object> params) {
try {
Goals goal = new Goals();
goal.setStudentId((String) params.get("studentId"));
goal.setTitle((String) params.get("title"));
goal.setStartDate(new java.text.SimpleDateFormat("yyyy-MM-dd").parse((String) params.get("startDate")));
goal.setEndDate(new java.text.SimpleDateFormat("yyyy-MM-dd").parse((String) params.get("endDate")));
goal.setStatus(1); // 设置为活跃状态
String[] subGoalContents = ((java.util.List<String>) params.get("subGoals")).toArray(new String[0]);
return goalsService.addGoalWithSubGoals(goal, subGoalContents);
} catch (Exception e) {
e.printStackTrace();
return Result.fail("添加目标失败: " + e.getMessage());
}
}
@GetMapping("/list/{studentId}")
public Result getGoalsByStudentId(@PathVariable String studentId) {
return goalsService.getGoalsByStudentId(studentId);
}
@PostMapping("/subgoals/update")
public Result updateSubGoalStatus(@RequestBody Map<String, Object> params) {
try {
Integer subgoalId = (Integer) params.get("subgoalId");
Boolean completed = (Boolean) params.get("completed");
return subGoalsService.updateSubGoalStatus(subgoalId, completed);
} catch (Exception e) {
return Result.fail("更新失败: " + e.getMessage());
}
}
@PostMapping("/subgoals/batch-update")
public Result batchUpdateSubGoals(@RequestBody Map<String, Object> params) {
try {
List<Integer> subgoalIds = (List<Integer>) params.get("subgoalIds");
Boolean completed = (Boolean) params.get("completed");
return subGoalsService.batchUpdateStatus(subgoalIds, completed);
} catch (Exception e) {
return Result.fail("批量更新失败: " + e.getMessage());
}
}
@PostMapping("/update-status/{studentId}")
public Result updateGoalsStatus(@PathVariable String studentId) {
return goalsService.updateGoalsStatus(studentId);
}
@PostMapping("/complete/{goalId}")
public Result completeGoal(@PathVariable Integer goalId) {
return goalsService.completeGoal(goalId);
}
@PostMapping("/update-title/{goalId}")
public Result updateGoalTitle(@PathVariable Integer goalId, @RequestBody Map<String, String> params) {
return goalsService.updateGoalTitle(goalId, params.get("title"));
}
@DeleteMapping("/subgoals/delete/{subgoalId}")
public Result deleteSubGoal(@PathVariable Integer subgoalId) {
return subGoalsService.deleteSubGoal(subgoalId);
}
@PostMapping("/subgoals/add")
public Result addSubGoal(@RequestBody Map<String, Object> params) {
try {
SubGoals subGoal = new SubGoals();
subGoal.setGoalId((Integer) params.get("goalId"));
subGoal.setContent((String) params.get("content"));
subGoal.setCompleted(false);
return subGoalsService.addSubGoal(subGoal);
} catch (Exception e) {
return Result.fail("添加子目标失败: " + e.getMessage());
}
}
@DeleteMapping("/delete/{goalId}")
public Result deleteGoal(@PathVariable Integer goalId) {
return goalsService.deleteGoalWithSubGoals(goalId);
}
@PostMapping("/search")
public Result searchGoals(@RequestBody Map<String, Object> params) {
String studentId = (String) params.get("studentId");
String title = (String) params.get("title");
String startDate = (String) params.get("startDate");
String endDate = (String) params.get("endDate");
return goalsService.searchGoals(studentId, title, startDate, endDate);
}
@GetMapping("/statistics/{studentId}")
public Result getGoalsStatistics(@PathVariable String studentId) {
return goalsService.getGoalsStatistics(studentId);
}
}
BlogLinkController:
package com.example.demo.controller;
import com.example.demo.common.Result;
import com.example.demo.entity.BlogLink;
import com.example.demo.service.BlogLinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/blog-links")
public class BlogLinkController {
@Autowired
private BlogLinkService blogLinkService;
@PostMapping("/add")
public Result addBlogLink(@RequestBody BlogLink blogLink) {
return blogLinkService.addBlogLink(blogLink);
}
@GetMapping("/list/{studentId}")
public Result getBlogLinksByStudentId(@PathVariable String studentId) {
return blogLinkService.getBlogLinksByStudentId(studentId);
}
@GetMapping("/week/{studentId}")
public Result getWeekBlogsByStudentId(@PathVariable String studentId) {
return blogLinkService.getWeekBlogsByStudentId(studentId);
}
@PutMapping("/update")
public Result updateBlogLink(@RequestBody BlogLink blogLink) {
return blogLinkService.updateBlogLink(blogLink);
}
@DeleteMapping("/delete/{id}")
public Result deleteBlogLink(@PathVariable Long id) {
return blogLinkService.deleteBlogLink(id);
}
@GetMapping("/search")
public Result searchBlogLinks(
@RequestParam String studentId,
@RequestParam(required = false) String title,
@RequestParam(required = false) String category,
@RequestParam(required = false) String startDate,
@RequestParam(required = false) String endDate) {
return blogLinkService.searchBlogLinks(studentId, title, category, startDate, endDate);
}
@GetMapping("/categories/{studentId}")
public Result getAllCategories(@PathVariable String studentId) {
return blogLinkService.getAllCategories(studentId);
}
@GetMapping("/statistics/{studentId}")
public Result getBlogStatistics(@PathVariable String studentId) {
return blogLinkService.getBlogStatistics(studentId);
}
}
StudentHonorController:
package com.example.demo.controller;
import com.example.demo.common.Result;
import com.example.demo.entity.StudentHonor;
import com.example.demo.service.StudentHonorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/student-honors")
public class StudentHonorController {
@Autowired
private StudentHonorService studentHonorService;
@PostMapping("/add")
public Result addStudentHonor(@RequestBody StudentHonor studentHonor) {
return studentHonorService.addStudentHonor(studentHonor);
}
@GetMapping("/list/{studentId}")
public Result getStudentHonorsByStudentId(@PathVariable String studentId) {
return studentHonorService.getStudentHonorsByStudentId(studentId);
}
@PutMapping("/update")
public Result updateStudentHonor(@RequestBody StudentHonor studentHonor) {
return studentHonorService.updateStudentHonor(studentHonor);
}
@DeleteMapping("/delete/{id}")
public Result deleteStudentHonor(@PathVariable Integer id) {
return studentHonorService.deleteStudentHonor(id);
}
@GetMapping("/category/{studentId}/{category}")
public Result getStudentHonorsByCategory(@PathVariable String studentId, @PathVariable String category) {
return studentHonorService.getStudentHonorsByCategory(studentId, category);
}
@PostMapping("/search")
public Result searchStudentHonors(@RequestBody Map<String, Object> params) {
String studentId = (String) params.get("studentId");
String semester = (String) params.get("semester");
String category = (String) params.get("category");
String startDate = (String) params.get("startDate");
String endDate = (String) params.get("endDate");
return studentHonorService.searchStudentHonors(studentId, semester, category, startDate, endDate);
}
}
GoalsServiceImpl:
package com.example.demo.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.Result;
import com.example.demo.entity.Goals;
import com.example.demo.entity.SubGoals;
import com.example.demo.mapper.GoalsMapper;
import com.example.demo.service.GoalsService;
import com.example.demo.service.SubGoalsService;
import com.example.demo.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class GoalsServiceImpl extends ServiceImpl<GoalsMapper, Goals> implements GoalsService {
@Autowired
private SubGoalsService subGoalsService;
@Override
@Transactional
public Result addGoalWithSubGoals(Goals goal, String[] subGoalContents) {
// 检查是否已存在活跃目标
QueryWrapper<Goals> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("student_id", goal.getStudentId())
.eq("status", 1);
if (count(queryWrapper) > 0) {
return Result.fail("当前已有进行中的周目标,无法添加新目标");
}
// 保存主目标
boolean saved = save(goal);
if (!saved) {
return Result.fail("添加目标失败");
}
// 保存子目标
if (subGoalContents != null && subGoalContents.length > 0) {
List<SubGoals> subGoalsList = new ArrayList<>();
for (String content : subGoalContents) {
if (content != null && !content.trim().isEmpty()) {
SubGoals subGoal = new SubGoals();
subGoal.setGoalId(goal.getGoalId());
subGoal.setContent(content);
subGoal.setCompleted(false);
subGoalsList.add(subGoal);
}
}
if (!subGoalsList.isEmpty()) {
boolean subGoalsSaved = subGoalsService.saveBatch(subGoalsList);
if (!subGoalsSaved) {
return Result.fail("添加子目标失败");
}
}
}
return Result.success();
}
@Override
public Result getGoalsByStudentId(String studentId) {
try {
// 查询用户的所有目标
QueryWrapper<Goals> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("student_id", studentId)
.orderByDesc("start_date");
List<Goals> goals = list(queryWrapper);
// 构建返回结果
List<Map<String, Object>> resultList = new ArrayList<>();
for (Goals goal : goals) {
Map<String, Object> goalMap = new HashMap<>();
goalMap.put("goal", goal);
// 获取并分类子目标
QueryWrapper<SubGoals> subWrapper = new QueryWrapper<>();
subWrapper.eq("goal_id", goal.getGoalId())
.orderByAsc("subgoal_id"); // 按创建顺序排序
List<SubGoals> allSubGoals = subGoalsService.list(subWrapper);
// 分类子目标并确保不为 null
Map<String, List<SubGoals>> subGoalsMap = new HashMap<>();
List<SubGoals> incomplete = allSubGoals.stream()
.filter(sg -> sg.getCompleted() == null || !sg.getCompleted())
.collect(Collectors.toList());
List<SubGoals> completed = allSubGoals.stream()
.filter(sg -> sg.getCompleted() != null && sg.getCompleted())
.collect(Collectors.toList());
subGoalsMap.put("incomplete", incomplete);
subGoalsMap.put("completed", completed);
goalMap.put("subGoals", subGoalsMap);
resultList.add(goalMap);
}
return Result.success(resultList);
} catch (Exception e) {
log.error("获取目标失败", e);
return Result.fail("获取目标失败: " + e.getMessage());
}
}
@Override
@Transactional
public Result updateGoalsStatus(String studentId) {
try {
// 获取该用户的所有目标
QueryWrapper<Goals> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("student_id", studentId);
List<Goals> goals = list(queryWrapper);
Date now = new Date();
Date weekStart = DateUtils.getWeekStart();
Date weekEnd = DateUtils.getWeekEnd();
boolean hasActiveGoal = false;
List<Goals> goalsToUpdate = new ArrayList<>();
for (Goals goal : goals) {
// 检查是否需要更新状态
if (goal.getStatus() == 1) { // 当前活跃目标
if (goal.getEndDate().before(now)) {
// 如果结束时间已过,标记为已完成
goal.setStatus(2);
goalsToUpdate.add(goal);
} else {
hasActiveGoal = true;
}
} else if (goal.getStatus() == 0) { // 未开始的目标
// 检查是否是本周目标
if (!hasActiveGoal &&
!goal.getStartDate().after(weekEnd) &&
!goal.getEndDate().before(weekStart)) {
goal.setStatus(1);
goalsToUpdate.add(goal);
hasActiveGoal = true;
}
}
}
// 批量更新状态
if (!goalsToUpdate.isEmpty()) {
updateBatchById(goalsToUpdate);
}
return Result.success();
} catch (Exception e) {
log.error("更新目标状态失败", e);
return Result.fail("更新目标状态失败: " + e.getMessage());
}
}
@Override
@Transactional
public Result completeGoal(Integer goalId) {
try {
Goals goal = getById(goalId);
if (goal == null) {
return Result.fail("目标不存在");
}
// 检查是否为进行中的目标
if (goal.getStatus() != 1) {
return Result.fail("只能完成进行中的目标");
}
// 更新目标状态为已完成
goal.setStatus(2);
boolean updated = updateById(goal);
if (updated) {
return Result.success();
} else {
return Result.fail("更新目标状态失败");
}
} catch (Exception e) {
return Result.fail("完成目标失败: " + e.getMessage());
}
}
@Override
public Result updateGoalTitle(Integer goalId, String title) {
if (title == null || title.trim().isEmpty()) {
return Result.fail("标题不能为空");
}
Goals goal = getById(goalId);
if (goal == null) {
return Result.fail("目标不存在");
}
goal.setTitle(title.trim());
if (updateById(goal)) {
return Result.success();
}
return Result.fail("更新失败");
}
@Override
@Transactional
public Result deleteGoalWithSubGoals(Integer goalId) {
try {
// 删除所有相关的子目标
QueryWrapper<SubGoals> subGoalsWrapper = new QueryWrapper<>();
subGoalsWrapper.eq("goal_id", goalId);
subGoalsService.remove(subGoalsWrapper);
// 删除主目标
if (removeById(goalId)) {
return Result.success();
}
return Result.fail("删除失败");
} catch (Exception e) {
return Result.fail("删除失败: " + e.getMessage());
}
}
@Override
public Result searchGoals(String studentId, String title, String startDate, String endDate) {
try {
QueryWrapper<Goals> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("student_id", studentId);
// 标题模糊查询
if (title != null && !title.trim().isEmpty()) {
queryWrapper.like("title", title.trim());
}
// 时间范围查询
if (startDate != null && endDate != null) {
queryWrapper.between("start_date", startDate, endDate);
}
// 如果只有时间查询条件,必须确保时间范围非空
if ((title == null || title.trim().isEmpty()) &&
(startDate == null || endDate == null)) {
return Result.fail("请至少输入标题或完整的时间范围");
}
queryWrapper.orderByDesc("start_date");
List<Goals> goals = list(queryWrapper);
// 构建返回结果(与 getGoalsByStudentId 方法类似的逻辑)
List<Map<String, Object>> resultList = new ArrayList<>();
for (Goals goal : goals) {
Map<String, Object> goalMap = new HashMap<>();
goalMap.put("goal", goal);
QueryWrapper<SubGoals> subWrapper = new QueryWrapper<>();
subWrapper.eq("goal_id", goal.getGoalId())
.orderByAsc("subgoal_id");
List<SubGoals> allSubGoals = subGoalsService.list(subWrapper);
Map<String, List<SubGoals>> subGoalsMap = new HashMap<>();
List<SubGoals> incomplete = allSubGoals.stream()
.filter(sg -> sg.getCompleted() == null || !sg.getCompleted())
.collect(Collectors.toList());
List<SubGoals> completed = allSubGoals.stream()
.filter(sg -> sg.getCompleted() != null && sg.getCompleted())
.collect(Collectors.toList());
subGoalsMap.put("incomplete", incomplete);
subGoalsMap.put("completed", completed);
goalMap.put("subGoals", subGoalsMap);
resultList.add(goalMap);
}
return Result.success(resultList);
} catch (Exception e) {
log.error("搜索目标失败", e);
return Result.fail("搜索目标失败: " + e.getMessage());
}
}
@Override
public Result getGoalsStatistics(String studentId) {
try {
// 获取所有目标
QueryWrapper<Goals> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("student_id", studentId);
List<Goals> goals = list(queryWrapper);
Map<String, Object> statistics = new HashMap<>();
Map<String, Double> monthlyCompletion = new HashMap<>();
// 按月统计目标完成情况
for (Goals goal : goals) {
String month = new SimpleDateFormat("yyyy-MM").format(goal.getStartDate());
// 获取该目标的子目标
QueryWrapper<SubGoals> subWrapper = new QueryWrapper<>();
subWrapper.eq("goal_id", goal.getGoalId());
List<SubGoals> subGoals = subGoalsService.list(subWrapper);
if (!subGoals.isEmpty()) {
long completedCount = subGoals.stream()
.filter(sg -> sg.getCompleted() != null && sg.getCompleted())
.count();
double completionRate = (double) completedCount / subGoals.size() * 100;
monthlyCompletion.merge(month, completionRate, (existing, newRate) ->
(existing + newRate) / 2); // 平均完成率
}
}
statistics.put("monthlyCompletion", monthlyCompletion);
statistics.put("totalGoals", goals.size());
statistics.put("completedGoals", goals.stream()
.filter(g -> g.getStatus() == 2).count());
return Result.success(statistics);
} catch (Exception e) {
log.error("获取目标统计失败", e);
return Result.fail("获取统计数据失败: " + e.getMessage());
}
}
}
SubGoalsServiceImpl:
package com.example.demo.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.Result;
import com.example.demo.entity.SubGoals;
import com.example.demo.mapper.SubGoalsMapper;
import com.example.demo.service.SubGoalsService;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class SubGoalsServiceImpl extends ServiceImpl<SubGoalsMapper, SubGoals> implements SubGoalsService {
@Override
public Result getSubGoalsByStatus(Integer goalId) {
QueryWrapper<SubGoals> wrapper = new QueryWrapper<>();
wrapper.eq("goal_id", goalId)
.orderByAsc("completed") // 未完成的在前
.orderByAsc("subgoal_id"); // 按创建顺序排序
List<SubGoals> allSubGoals = list(wrapper);
Map<String, List<SubGoals>> result = new HashMap<>();
result.put("incomplete", allSubGoals.stream()
.filter(sg -> !sg.getCompleted())
.collect(Collectors.toList()));
result.put("completed", allSubGoals.stream()
.filter(SubGoals::getCompleted)
.collect(Collectors.toList()));
return Result.success(result);
}
@Override
public Result updateSubGoalStatus(Integer subgoalId, Boolean completed) {
SubGoals subGoal = getById(subgoalId);
if (subGoal == null) {
return Result.fail("子目标不存在");
}
subGoal.setCompleted(completed);
if (updateById(subGoal)) {
return Result.success();
}
return Result.fail("更新失败");
}
@Override
public Result batchUpdateStatus(List<Integer> subgoalIds, Boolean completed) {
if (subgoalIds == null || subgoalIds.isEmpty()) {
return Result.fail("未选择要更新的子目标");
}
try {
// 获取所有需要更新的子目标
List<SubGoals> subGoals = listByIds(subgoalIds);
// 更新状态
for (SubGoals subGoal : subGoals) {
subGoal.setCompleted(completed);
}
// 批量更新
boolean success = updateBatchById(subGoals);
if (success) {
return Result.success();
} else {
return Result.fail("更新失败");
}
} catch (Exception e) {
e.printStackTrace();
return Result.fail("更新过程中发生错误");
}
}
@Override
public Result deleteSubGoal(Integer subgoalId) {
if (removeById(subgoalId)) {
return Result.success();
}
return Result.fail("删除失败");
}
@Override
public Result addSubGoal(SubGoals subGoal) {
if (subGoal.getContent() == null || subGoal.getContent().trim().isEmpty()) {
return Result.fail("子目标内容不能为空");
}
subGoal.setContent(subGoal.getContent().trim());
if (save(subGoal)) {
return Result.success();
}
return Result.fail("添加失败");
}
}
BlogLinkServiceImpl:
package com.example.demo.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.Result;
import com.example.demo.entity.BlogLink;
import com.example.demo.mapper.BlogLinkMapper;
import com.example.demo.service.BlogLinkService;
import com.example.demo.utils.DateUtils;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class BlogLinkServiceImpl extends ServiceImpl<BlogLinkMapper, BlogLink> implements BlogLinkService {
@Override
public Result addBlogLink(BlogLink blogLink) {
try {
// 设置发布时间为当前时间
blogLink.setPublishTime(new Date());
// 保存博客链接
boolean success = save(blogLink);
if (success) {
return Result.success();
} else {
return Result.fail("添加失败");
}
} catch (Exception e) {
log.error("添加博客链接失败", e);
return Result.fail("系统错误");
}
}
@Override
public Result getWeekBlogsByStudentId(String studentId) {
try {
QueryWrapper<BlogLink> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("student_id", studentId)
.between("publish_time", DateUtils.getWeekStart(), DateUtils.getWeekEnd())
.orderByDesc("publish_time");
List<BlogLink> blogLinks = list(queryWrapper);
return Result.success(blogLinks);
} catch (Exception e) {
log.error("获取学生本周博客列表失败", e);
return Result.fail("获取数据失败");
}
}
@Override
public Result getBlogLinksByStudentId(String studentId) {
try {
QueryWrapper<BlogLink> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("student_id", studentId)
.orderByDesc("publish_time");
List<BlogLink> blogLinks = list(queryWrapper);
return Result.success(blogLinks);
} catch (Exception e) {
log.error("获取博客链接列表失败", e);
return Result.fail("获取数据失败");
}
}
@Override
public Result updateBlogLink(BlogLink blogLink) {
try {
if (blogLink.getId() == null) {
return Result.fail("ID不能为空");
}
boolean success = updateById(blogLink);
if (success) {
return Result.success();
} else {
return Result.fail("更新失败");
}
} catch (Exception e) {
log.error("更新博客链接失败", e);
return Result.fail("系统错误");
}
}
@Override
public Result deleteBlogLink(Long id) {
try {
if (id == null) {
return Result.fail("ID不能为空");
}
boolean success = removeById(id);
if (success) {
return Result.success();
} else {
return Result.fail("删除失败");
}
} catch (Exception e) {
log.error("删除博客链接失败", e);
return Result.fail("系统错误");
}
}
@Override
public Result searchBlogLinks(String studentId, String title, String category, String startDate, String endDate) {
try {
if (studentId == null || studentId.isEmpty()) {
return Result.fail("学生ID不能为空");
}
QueryWrapper<BlogLink> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("student_id", studentId);
// 添加标题搜索条件
if (title != null && !title.isEmpty()) {
queryWrapper.like("title", title);
}
// 添加分类搜索条件
if (category != null && !category.isEmpty()) {
queryWrapper.eq("category", category);
}
// 添加时间范围搜索条件
if (startDate != null && !startDate.isEmpty()) {
queryWrapper.ge("publish_time", startDate + " 00:00:00");
}
if (endDate != null && !endDate.isEmpty()) {
queryWrapper.le("publish_time", endDate + " 23:59:59");
}
// 按发布时间倒序排序
queryWrapper.orderByDesc("publish_time");
List<BlogLink> blogLinks = list(queryWrapper);
return Result.success(blogLinks);
} catch (Exception e) {
log.error("搜索博客链接失败", e);
return Result.fail("搜索失败");
}
}
@Override
public Result getAllCategories(String studentId) {
try {
QueryWrapper<BlogLink> queryWrapper = new QueryWrapper<>();
queryWrapper.select("DISTINCT category")
.eq("student_id", studentId);
List<BlogLink> blogLinks = list(queryWrapper);
List<String> categories = blogLinks.stream()
.map(BlogLink::getCategory)
.filter(category -> category != null && !category.isEmpty())
.distinct()
.collect(Collectors.toList());
// 确保默认分类始终存在
if (!categories.contains("默认")) {
categories.add("默认");
}
return Result.success(categories);
} catch (Exception e) {
log.error("获取分类列表失败", e);
return Result.fail("获取分类列表失败");
}
}
@Override
public Result getBlogStatistics(String studentId) {
try {
QueryWrapper<BlogLink> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("student_id", studentId);
List<BlogLink> blogLinks = list(queryWrapper);
Map<String, Object> statistics = new HashMap<>();
Map<String, Integer> monthlyCount = new HashMap<>();
Map<String, Map<String, Integer>> weeklyCount = new HashMap<>();
// 按月和周统计博客数量
for (BlogLink blog : blogLinks) {
String month = new SimpleDateFormat("yyyy-MM").format(blog.getPublishTime());
String week = new SimpleDateFormat("yyyy-MM-dd").format(blog.getPublishTime());
// 计算周数
Calendar cal = Calendar.getInstance();
cal.setTime(blog.getPublishTime());
int weekOfMonth = cal.get(Calendar.WEEK_OF_MONTH);
String weekKey = month + "-W" + weekOfMonth;
monthlyCount.merge(month, 1, Integer::sum);
weeklyCount.computeIfAbsent(month, k -> new HashMap<>())
.merge(weekKey, 1, Integer::sum);
}
statistics.put("monthlyCount", monthlyCount);
statistics.put("weeklyCount", weeklyCount);
statistics.put("totalBlogs", blogLinks.size());
// 按分类统计
Map<String, Long> categoryCount = blogLinks.stream()
.collect(Collectors.groupingBy(
blog -> blog.getCategory() != null ? blog.getCategory() : "未分类",
Collectors.counting()
));
statistics.put("categoryCount", categoryCount);
return Result.success(statistics);
} catch (Exception e) {
log.error("获取博客统计失败", e);
return Result.fail("获取统计数据失败: " + e.getMessage());
}
}
}
StudentHonorServiceImpl:
package com.example.demo.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.Result;
import com.example.demo.entity.StudentHonor;
import com.example.demo.mapper.StudentHonorMapper;
import com.example.demo.service.StudentHonorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class StudentHonorServiceImpl extends ServiceImpl<StudentHonorMapper, StudentHonor> implements StudentHonorService {
@Override
public Result addStudentHonor(StudentHonor studentHonor) {
try {
if (studentHonor.getStudentId() == null || studentHonor.getStudentId().isEmpty()) {
return Result.fail("学号不能为空");
}
if (studentHonor.getCategory() == null || studentHonor.getCategory().isEmpty()) {
return Result.fail("奖项类别不能为空");
}
if (studentHonor.getHonorTime() == null) {
studentHonor.setHonorTime(new Date());
}
// 设置创建时间和更新时间为当前日期(不含时分秒)
Date currentDate = new Date();
studentHonor.setCreateTime(currentDate);
studentHonor.setUpdateTime(currentDate);
boolean success = save(studentHonor);
if (success) {
return Result.success();
} else {
return Result.fail("添加失败");
}
} catch (Exception e) {
log.error("添加学生荣誉失败", e);
return Result.fail("系统错误");
}
}
@Override
public Result getStudentHonorsByStudentId(String studentId) {
try {
if (studentId == null || studentId.isEmpty()) {
return Result.fail("学号不能为空");
}
QueryWrapper<StudentHonor> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("student_id", studentId)
.orderByDesc("honor_time"); // 按获奖时间降序排序
List<StudentHonor> honors = list(queryWrapper);
return Result.success(honors);
} catch (Exception e) {
log.error("获取学生荣誉列表失败", e);
return Result.fail("系统错误");
}
}
@Override
public Result updateStudentHonor(StudentHonor studentHonor) {
try {
if (studentHonor.getId() == null) {
return Result.fail("ID不能为空");
}
if (studentHonor.getStudentId() == null || studentHonor.getStudentId().isEmpty()) {
return Result.fail("学号不能为空");
}
if (studentHonor.getCategory() == null || studentHonor.getCategory().isEmpty()) {
return Result.fail("奖项类别不能为空");
}
// 设置更新时间为当前时间
studentHonor.setUpdateTime(new Date());
boolean success = updateById(studentHonor);
if (success) {
return Result.success();
} else {
return Result.fail("更新失败");
}
} catch (Exception e) {
log.error("更新学生荣誉失败", e);
return Result.fail("系统错误");
}
}
@Override
public Result deleteStudentHonor(Integer id) {
try {
if (id == null) {
return Result.fail("ID不能为空");
}
boolean success = removeById(id);
if (success) {
return Result.success();
} else {
return Result.fail("删除失败,记录不存在");
}
} catch (Exception e) {
log.error("删除学生荣誉失败", e);
return Result.fail("系统错误");
}
}
@Override
public Result getStudentHonorsByCategory(String studentId, String category) {
// 实现根据类别获取学生荣誉的逻辑
return Result.success();
}
@Override
public Result searchStudentHonors(String studentId, String semester, String category, String startDate, String endDate) {
// 实现搜索学生荣誉的逻辑
return Result.success();
}
}

浙公网安备 33010602011771号