Java Spring Boot를 사용한 기본 CRUD
Source: Dev.to
Spring Boot란?
Spring Boot는 웹 및 백엔드 애플리케이션을 쉽게 만들 수 있게 해 주는 Java 프레임워크입니다. 대부분의 설정과 구성을 자동으로 처리해 주므로 복잡한 설정을 관리하는 대신 코드 작성에 집중할 수 있습니다.
시작하기
- 시스템에 Java (JDK)를 설치합니다.
- Spring Initializr에서 새 Spring Boot 프로젝트를 생성합니다. 이름, Java 버전, 필요한 의존성을 선택하고 Generate 버튼을 눌러 압축을 풀어 주세요.
- 생성된 폴더를 IDE(예: IntelliJ IDEA – 공식 사이트에서 Community 에디션을 다운로드)에서 엽니다.
프로젝트 구조 개요
CRUD 작업을 처리하는 일반적인 Spring Boot 애플리케이션은 계층형 아키텍처를 따릅니다:
| Layer | Description |
|---|---|
| Entity / Model | 데이터베이스 테이블을 나타내는 Java 클래스(예: User, Product). |
| Repository | 데이터베이스와 직접 상호작용하는 인터페이스(Sprint Data JPA). |
| Service | 비즈니스 로직을 포함하고 Repository를 사용해 데이터 작업을 수행합니다. |
| Controller | HTTP 요청을 받아 Service에 위임하고 응답을 반환합니다. |
CRUD 작업 매핑
| Operation | Function | HTTP Method | Spring Annotation | Repository Method | Purpose |
|---|---|---|---|---|---|
| Create | Insert Data | POST | @PostMapping | save(entity) | 데이터베이스에 새 레코드 추가. |
| Read | Retrieve Data | GET | @GetMapping | findAll(), findById(id) | 하나 또는 모든 레코드 조회. |
| Update | Modify Data | PUT | @PutMapping | save(entity) | 기존 레코드의 데이터를 변경. |
| Delete | Remove Data | DELETE | @DeleteMapping | deleteById(id) | 레코드를 영구 삭제. |
1. Create (C)
Goal: 새로운 엔티티(예: 새로운 학생)를 MySQL 데이터베이스에 저장합니다.
Controller
@PostMapping("/addStudent")
public String postDetails(@RequestBody StudentEntity studentEntity) {
System.out.println("Student entity received: " + studentEntity);
studentService.saveDetails(studentEntity);
return "ADDED TO TABLE SUCCESSFULLY";
}
Service
public StudentEntity saveDetails(StudentEntity studentEntity) {
return studentRepository.save(studentEntity);
}
Result: 해당 MySQL 테이블에 새 행이 삽입됩니다.
2. Read (R)
Goal: 데이터베이스에서 데이터를 조회합니다.
Read All
@GetMapping("/getStudent")
public List getDetails() {
return studentService.getAllDetails();
}
Read by ID
@GetMapping("/getStudent/{id}")
public StudentEntity getDetailsById(@PathVariable int id) {
return studentService.getAllDetailsById(id);
}
Service Methods
// Get all details
public List getAllDetails() {
return studentRepository.findAll();
}
// Get detail by ID
public StudentEntity getAllDetailsById(int id) {
return studentRepository.findById(id).orElse(null);
}
3. Update (U)
Goal: 기존 엔티티를 데이터베이스에서 수정합니다.
Controller
@PostMapping("/updateStudent")
public StudentEntity updateDetails(@RequestBody StudentEntity studentEntity) {
return studentService.updateAllDetail(studentEntity);
}
Service
public StudentEntity updateAllDetail(StudentEntity studentEntity) {
StudentEntity existing = studentRepository.findById(studentEntity.getId()).orElse(null);
if (existing != null) {
existing.setMark(studentEntity.getMark());
existing.setName(studentEntity.getName());
studentRepository.save(existing);
return existing;
}
return null;
}
4. Delete (D)
Goal: 데이터베이스에서 레코드를 삭제합니다.
Controller
@DeleteMapping("/deleteStudent/{id}")
public String deleteStudent(@PathVariable int id) {
if (studentService.deleteStudentById(id))
return "Deleted Successfully";
else
return "Can't Delete";
}
Service
public boolean deleteStudentById(int id) {
studentRepository.deleteById(id);
return true;
}
Result: 해당 레코드가 MySQL 테이블에서 영구적으로 삭제됩니다.
데이터베이스 설정
src/main/resources/application.properties 파일을 생성하거나 편집하여 MySQL 연결 정보를 입력합니다. 예시:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
위 설정은 Spring Boot가 MySQL에 연결하고 JPA 동작을 구성하는 방법을 지정합니다.