feat: 完成对学生表的基本CRUD

backend/dev
Spark 2 months ago
parent 461d9fc87c
commit d1208401fe

@ -0,0 +1,77 @@
package cc.aspark.controller;
import cc.aspark.domain.dto.PageQueryDTO;
import cc.aspark.domain.dto.StudentDTO;
import cc.aspark.domain.entity.Student;
import cc.aspark.result.PageResult;
import cc.aspark.result.Result;
import cc.aspark.service.StudentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/student")
@RequiredArgsConstructor
@Builder
@Tag(name = "学生表相关操作")
public class StudentController {
private final StudentService studentService;
@Operation(summary = "查询全部学生信息")
@GetMapping
public Result<List<Student>> list() {
List<Student> studentList = studentService.list();
return Result.success(studentList);
}
@Operation(summary = "根据 id 查询学生信息")
@GetMapping("/{id}")
public Result<Student> getStuInfoById(@PathVariable Integer id) {
Student stuInfo = studentService.getById(id);
return Result.success(stuInfo);
}
@Operation(summary = "学生信息分页查询")
@GetMapping("/page")
public Result<PageResult<Student>> pageStuInfo(PageQueryDTO pageQueryDTO) {
log.info("学生信息分页查询: {}", pageQueryDTO);
PageResult<Student> pageResult = studentService.page(pageQueryDTO);
return Result.success(pageResult);
}
@Operation(summary = "新增学生信息")
@PostMapping
public Result save(@RequestBody StudentDTO studentDTO) {
studentService.save(studentDTO);
return Result.success();
}
@Operation(summary = "更新学生信息")
@PutMapping
public Result updateStu(@RequestBody StudentDTO studentDTO) {
studentService.updateStu(studentDTO);
return Result.success();
}
@Operation(summary = "删除学生信息")
@DeleteMapping("/{ids}")
public Result deleteStus(@PathVariable List<Integer> ids) {
studentService.removeByIds(ids);
return Result.success();
}
}

@ -0,0 +1,18 @@
package cc.aspark.mapper;
import cc.aspark.domain.entity.Student;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @author night
* @description tb_stu()Mapper
* @createDate 2024-10-02 16:31:44
* @Entity generator.domain.TbStu
*/
public interface StudentMapper extends BaseMapper<Student> {
}

@ -0,0 +1,24 @@
package cc.aspark.service;
import cc.aspark.domain.dto.PageQueryDTO;
import cc.aspark.domain.dto.StudentDTO;
import cc.aspark.domain.entity.Student;
import cc.aspark.result.PageResult;
import com.baomidou.mybatisplus.extension.service.IService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
/**
* @author night
* @description tb_stu()Service
* @createDate 2024-10-02 16:31:44
*/
public interface StudentService extends IService<Student> {
void updateStu(StudentDTO studentDTO);
PageResult<Student> page(PageQueryDTO pageQueryDTO);
void save(StudentDTO studentDTO);
}

@ -6,7 +6,9 @@ import cc.aspark.domain.dto.PageQueryDTO;
import cc.aspark.domain.dto.StudentDTO; import cc.aspark.domain.dto.StudentDTO;
import cc.aspark.domain.entity.Student; import cc.aspark.domain.entity.Student;
import cc.aspark.exception.BaseException; import cc.aspark.exception.BaseException;
import cc.aspark.mapper.StudentMapper;
import cc.aspark.result.PageResult; import cc.aspark.result.PageResult;
import cc.aspark.service.StudentService;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader; import cn.hutool.poi.excel.ExcelReader;
@ -125,152 +127,5 @@ public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
baseMapper.insert(student); baseMapper.insert(student);
} }
@Override
public Student rollCall() {
List<Student> studentList = this.list();
if (studentList.isEmpty()) {
throw new RuntimeException("学生列表为空");
}
// 找出最高积分,用于计算反向权重
final double maxPoints = studentList.stream()
.mapToDouble(Student::getPoints)
.max()
.orElse(0.0) + 1.0;
// 计算总的反向权重
double totalInverseWeights = studentList.stream()
.mapToDouble(student -> maxPoints - student.getPoints())
.sum();
// 生成一个0到总反向权重之间的随机数
Random random = new Random();
double randomValue = random.nextDouble() * totalInverseWeights;
// 使用累加器方法选择学生
double accumulatedWeight = 0;
for (Student student : studentList) {
// 计算该学生的反向权重
double inverseWeight = maxPoints - student.getPoints();
accumulatedWeight += inverseWeight;
if (accumulatedWeight >= randomValue) {
return student;
}
}
// 以防万一,返回最后一个学生
return studentList.get(studentList.size() - 1);
}
@Override
public void importStudentsByExcel(MultipartFile file) {
try {
ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
reader .addHeaderAlias("学号", "no")
.addHeaderAlias("姓名", "name")
.addHeaderAlias("性别", "gender")
.addHeaderAlias("班级", "className")
.addHeaderAlias("积分", "credits")
.addHeaderAlias("创建时间", "createTime")
.addHeaderAlias("最后操作时间", "updateTime");
List<Map<String, Object>> rows = reader.readAll();
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
List<Student> studentList = rows.stream().map(row -> {
Student student = new Student();
student.setNo(row.get("no").toString());
student.setName(row.get("name").toString());
student.setGender("男".equals(row.get("gender")) ? (short) 0 : (short) 1);
student.setClassName(row.get("className").toString());
student.setCreator(Integer.valueOf(BaseContext.getCurrentId().toString()));
if (row.get("credits") == null) {
student.setPoints(0.00);
} else {
student.setPoints(Double.valueOf(row.get("credits").toString()));
}
if (row.get("createTime") == null) {
student.setCreateTime(now);
} else {
String createTimeStr = row.get("createTime").toString();
student.setCreateTime(LocalDateTime.parse(createTimeStr, formatter));
}
if (row.get("updateTime") == null) {
student.setUpdateTime(now);
} else {
String updateTimeStr = row.get("updateTime").toString();
student.setUpdateTime(LocalDateTime.parse(updateTimeStr, formatter));
}
return student;
}).toList();
try {
baseMapper.insertOrUpdate(studentList);
} catch (Exception e) {
log.info(e.getMessage());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void exportStudentsToExcel(HttpServletResponse response) {
try {
LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(Student::getCreator, BaseContext.getCurrentId());
List<Student> studentList = baseMapper.selectList(wrapper);
// 创建一个Excel写入器
ExcelWriter writer = ExcelUtil.getWriter(true);
// 设置表头别名
writer.addHeaderAlias("no", "学号");
writer.addHeaderAlias("name", "姓名");
writer.addHeaderAlias("gender", "性别");
writer.addHeaderAlias("className", "班级");
writer.addHeaderAlias("points", "积分");
writer.addHeaderAlias("createTime", "创建时间");
writer.addHeaderAlias("updateTime", "最后操作时间");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 将性别的数字转换为文字
List<Map<String, Object>> rows = studentList.stream().map(student -> {
Map<String, Object> row = new HashMap<>();
row.put("no", student.getNo());
row.put("name", student.getName());
row.put("gender", student.getGender() == 0 ? "男" : "女");
row.put("className", student.getClassName());
row.put("points", student.getPoints());
row.put("createTime", student.getCreateTime().format(formatter));
row.put("updateTime", student.getUpdateTime().format(formatter));
return row;
}).collect(Collectors.toList());
// 写入数据
writer.write(rows, true);
// 设置响应头
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=students.xlsx");
// 输出Excel文件
ServletOutputStream out = response.getOutputStream();
writer.flush(out, true);
writer.close();
IoUtil.close(out);
} catch (Exception e) {
log.error("导出Excel失败", e);
throw new BaseException(e.getMessage());
}
}
@Override
public void updatePoints(Integer id, Double points) {
Student student = baseMapper.selectById(id);
student.setPoints(student.getPoints() + points);
baseMapper.updateById(student);
}
} }

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cc.aspark.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="cc.aspark.domain.entity.Student">
<id property="id" column="id" jdbcType="INTEGER"/>
<result property="name" column="name" jdbcType="VARCHAR"/>
<result property="gender" column="gender" jdbcType="TINYINT"/>
<result property="major" column="major" jdbcType="VARCHAR"/>
<result property="class" column="class" jdbcType="INTEGER"/>
<result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
<result property="updateTime" column="update_time" jdbcType="TIMESTAMP"/>
</resultMap>
<sql id="Base_Column_List">
id,name,gender,
major,class,create_time,
update_time
</sql>
</mapper>
Loading…
Cancel
Save