feature(demo): 新增student表插入数据

This commit is contained in:
ClovertaTheTrilobita 2025-07-01 01:42:00 +08:00
parent cf8403e5ed
commit d152f39a80
4 changed files with 56 additions and 4 deletions

View file

@ -1,14 +1,14 @@
package com.cloverta.webapi.controller;
import com.cloverta.webapi.mapper.StudentMapper;
import com.cloverta.webapi.model.Student;
import com.cloverta.webapi.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/demo")
@ -23,4 +23,33 @@ public class DemoController {
public List<Student> fetch() {
return studentService.findAll();
}
@PostMapping("/insert")
public ResponseEntity<?> insert(@RequestParam String name,
@RequestParam(required = false) String email,
@RequestParam(required = false) String phone) {
Student student = new Student();
student.setName(name);
student.setEmail(email);
student.setPhone(phone);
if (studentService.insert(student)) {
// 成功返回201 Created和资源位置
return ResponseEntity.status(HttpStatus.CREATED)
.header("Location", "/students/" + student.getId())
.body(Map.of(
"status", "success",
"message", "学生创建成功",
"studentId", student.getId()
));
} else {
// 失败返回500错误
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of(
"status", "error",
"message", "学生创建失败",
"error", "数据库操作失败"
));
}
}
}

View file

@ -9,4 +9,6 @@ import java.util.List;
public interface StudentMapper {
List<Student> findAll();
void insert(Student student);
}

View file

@ -16,4 +16,17 @@ public class StudentService {
public List<Student> findAll() {
return studentMapper.findAll();
}
public boolean insert(Student student) {
if (student == null) {
return false;
}
if (student.getName() == null) {
return false;
}
studentMapper.insert(student);
return true;
}
}

View file

@ -6,4 +6,12 @@
<select id="findAll" resultType="Student">
SELECT * FROM student;
</select>
<insert id="insert" parameterType="com.cloverta.webapi.model.Student" useGeneratedKeys="true" keyProperty="id">
INSERT INTO student (
name, email, phone
) VALUES (
#{name}, #{email}, #{phone}
)
</insert>
</mapper>