웹개발/SpringBoot

Spring Boot + MySQL로 구현한 Student CRUD

bergerac 2025. 5. 30. 09:11

https://github.com/seoyoonchoi/Korea_sleep_Tech_springBoot/tree/main/src/main/java/com/example/korea_sleepTech_springboot

 

Korea_sleep_Tech_springBoot/src/main/java/com/example/korea_sleepTech_springboot at main · seoyoonchoi/Korea_sleep_Tech_springB

Contribute to seoyoonchoi/Korea_sleep_Tech_springBoot development by creating an account on GitHub.

github.com

실제 코드를 더 확인하고 싶다면 위 링크를 통해서 확인할 수 있다.

📁 프로젝트 구조

com.example.korea_sleepTech_springboot
├── controller
│   └── StudentController.java
├── dto
│   ├── request
│   │   ├── StudentCreateRequestDto.java
│   │   └── StudentUpdateRequestDto.java
│   └── response
│       ├── StudentResponseDto.java
│       └── ResponseDto.java
├── entity
│   └── B_Student.java
├── repository
│   └── StudentRepository.java
└── service
    └── StudentService.java

Entity Class : B_Student

@Entity
@Table(name = "student")
public class B_Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @Column(unique = true)
    private String email;
    
    public B_Student(String name, String email) {
        this.name = name;
        this.email = email;
    }
}

 

  • @Entity: JPA에서 해당 클래스가 DB 테이블과 매핑되는 객체임을 의미한다.
  • @Table(name = "student"): 테이블 이름을 명시적으로 지정.
  • @Column(unique = true): 이메일은 중복 불가하도록 제약 설정.

 DTO (Data Transfer Object)

  • StudentCreateRequestDto: 학생 생성 요청 시 사용
  • StudentUpdateRequestDto: 이름만 수정 가능
  • StudentResponseDto: 응답 시 이메일은 제외
  • ResponseDto: 요청 성공 여부 + 메시지 + 데이터 포장

 Service 클래스 핵심 동작

public StudentResponseDto createStudent(StudentCreateRequestDto studentDto) {
    B_Student student = new B_Student(studentDto.getName(), studentDto.getEmail());
    B_Student savedStudent = studentRepository.save(student);
    return new StudentResponseDto(savedStudent.getId(), savedStudent.getName());
}

 

  • 클라이언트가 전달한 DTO를 바탕으로 Entity 객체 생성
  • studentRepository.save()를 통해 DB에 저장
  • 저장된 Entity를 Response DTO로 변환하여 반환

이 흐름은 다른 메서드들(getAllStudents, getStudentById, updateStudent, deleteStudent)에서도 동일하게 적용된다.

Controller - RESTful API 설계

@RestController
@RequestMapping("/student")
public class StudentController {
    @GetMapping
    public List<StudentResponseDto> getAllStudents() { ... }

    @GetMapping("/{id}")
    public StudentResponseDto getStudentById(@PathVariable Long id) { ... }

    @PostMapping
    public StudentResponseDto createStudent(@RequestBody StudentCreateRequestDto student) { ... }

    @PutMapping("/{id}")
    public StudentResponseDto updateStudent(@PathVariable Long id, @RequestBody StudentUpdateRequestDto dto) { ... }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteStudent(@PathVariable Long id) { ... }
}

 

  • GET /student → 전체 조회
  • GET /student/{id} → 단건 조회
  • POST /student → 학생 등록
  • PUT /student/{id} → 학생 정보 수정
  • DELETE /student/{id} → 삭제

예외처리

catch (Exception e) {
    throw new ResponseStatusException(
        HttpStatus.INTERNAL_SERVER_ERROR,
        "Error occurred while fetching student",
        e
    );
}

 

서비스 계층에서 예외를 감싸서 ResponseStatusException으로 변환함으로써 클라이언트에게 적절한 HTTP 상태 코드와 메시지를 제공한다.