π PUT, PATCH, JPA λ³κ²½ κ°μ§!
β μ ꡬνλ λΆλΆ
1. λͺ νν κ³μΈ΅ ꡬ쑰
- Controller: HTTP μμ² μ²λ¦¬
- Service: λΉμ¦λμ€ λ‘μ§ μν
- Repository: λ°μ΄ν° μ κ·Ό
-
Entity: μ체 μν κ΄λ¦¬ (
updateStudentName
)
κ° κ³μΈ΅μ μ± μμ΄ λͺ ννκ² λΆλ¦¬λμ΄ μμ΅λλ€.
2. μ μ ν μμΈ μ²λ¦¬
studentRepository.findByStudentId(studentId)
.orElseThrow(() -> new IllegalArgumentException("μ‘΄μ¬νμ§ μλ νμμ
λλ€."));
μ‘΄μ¬νμ§ μλ 리μμ€μ λν μμ μ μ¬μ μ λ°©μ§ν©λλ€.
3. μ§κ΄μ μΈ λ©μλ λͺ λͺ
changeStudentName
μ²λΌ κΈ°λ₯μ λͺ
ννκ² νννλ λ©μλλͺ
μ μ¬μ©νμ΅λλ€.
π§ κ°μ μ μ
μ μ 1: HTTP λ©μλ λ³κ²½ (PUT
β PATCH
)
π λ¬Έμ μ
νμ¬ @PutMapping
μ μ¬μ© μ€μ
λλ€. REST μ€κ³ μμΉμμ:
- PUT: 리μμ€ μ 체λ₯Ό κ΅μ²΄ (λͺ¨λ νλ νμ)
- PATCH: 리μμ€ μΌλΆλ§ μμ (λ³κ²½ν νλλ§)
νμ¬ κ΅¬νμ βμ΄λ¦β νλλ§ μμ νλ―λ‘ λΆλΆ μμ μ ν΄λΉν©λλ€.
β¨ κ°μ μ½λ
Before (νμ¬)
@PutMapping("/change/student/name/{studentId}")
public ResponseEntity<StudentResponseDto> changeStudentName(
@PathVariable String studentId,
@RequestBody StudentRequestDto requestDto
) {
return ResponseEntity.ok(studentService.updateStudentName(studentId, requestDto));
}
After (κ°μ )
import org.springframework.web.bind.annotation.PatchMapping;
@PatchMapping("/change/student/name/{studentId}")
public ResponseEntity<StudentResponseDto> changeStudentName(
@PathVariable String studentId,
@RequestBody StudentRequestDto requestDto
) {
return ResponseEntity.ok(studentService.updateStudentName(studentId, requestDto));
}
μ μ 2: JPA λ³κ²½ κ°μ§(Dirty Checking) νμ©
π λ¬Έμ μ
@Transactional
λ©μλ λ΄μμ λΆνμν save()
νΈμΆμ΄ μμ΅λλ€.
π‘ ν΅μ¬ κ°λ
JPAλ μμμ± μ»¨ν
μ€νΈμμ κ΄λ¦¬λλ μν°ν°μ λ³κ²½μ μλμΌλ‘ κ°μ§ν©λλ€.
νΈλμμ
μ΄ μ»€λ°λ λ λ³κ²½λ λ΄μ©μ΄ μλμΌλ‘ DBμ λ°μλ©λλ€.
β¨ κ°μ μ½λ
Before (νμ¬)
@Transactional
public StudentResponseDto updateStudentName(String studentId, StudentRequestDto requestDto) {
Student findStudent = studentRepository.findByStudentId(studentId)
.orElseThrow(() -> new IllegalArgumentException("μ‘΄μ¬νμ§ μλ νμμ
λλ€."));
findStudent.updateStudentName(requestDto.getName());
// λΆνμν save νΈμΆ
Student savedStudent = studentRepository.save(findStudent);
return StudentResponseDto.fromEntity(savedStudent);
}
After (κ°μ )
@Transactional
public StudentResponseDto updateStudentName(String studentId, StudentRequestDto requestDto) {
// 1. μν°ν° μ‘°ν β μμμ± μ»¨ν
μ€νΈκ° κ΄λ¦¬ μμ
Student findStudent = studentRepository.findByStudentId(studentId)
.orElseThrow(() -> new IllegalArgumentException("μ‘΄μ¬νμ§ μλ νμμ
λλ€."));
// 2. μν°ν° μν λ³κ²½
findStudent.updateStudentName(requestDto.getName());
// 3. save() μμ΄λ νΈλμμ
μ»€λ° μ μλμΌλ‘ UPDATE 쿼리 μ€ν
return StudentResponseDto.fromEntity(findStudent);
}
π κ°μ ν¨κ³Ό
- μ½λ κ°κ²°μ± ν₯μ
- JPAμ λ³κ²½ κ°μ§ λ©μ»€λμ¦ νμ©
- λΆνμν λ©μλ νΈμΆ μ κ±°
π μμ½
νλͺ© | νμ¬ | κ°μ ν |
---|---|---|
HTTP λ©μλ | @PutMapping |
@PatchMapping |
Repository νΈμΆ |
save() λͺ
μμ νΈμΆ |
λ³κ²½ κ°μ§λ‘ μλ μ μ₯ |
RESTful μ€κ³ | λΆλΆμ μΌλ‘ μ€μ | μμ ν μ€μ |