Backend/프로젝트
[SpringBoot JPA] PUT mapping을 사용한 API 작성하기
hsooooo
2022. 9. 13. 02:19
PlantLog에서 광합성, 물주기, 관찰, 분갈이 버튼을 누르면 true로 바뀌는 API를 설계해야한다.
1️⃣ domain (PlantLog, Log)
@Getter
@NoArgsConstructor
@Entity
public class PlantLog extends BaseTimeEntity {
@Embedded
private Log log;
@Builder
public PlantLog(Long plantId, MyPlant myPlant, Log log) {
this.plantId = plantId;
this.myPlant = myPlant;
this.log = log;
}
public void updateRepot(Boolean repot){ log.updateRepot(repot); }
public void updateSun(Boolean sun) { log.updateSun(sun); }
public void updateWater(Boolean water) { log.updateWater(water); }
public void updateLook(Boolean look) { log.updateLook(look); }
}
@Embeddable
@Getter
public class Log {
private boolean water;
private boolean look;
private boolean sun;
private boolean repot;
protected Log() {}
public Log(boolean water, boolean look, boolean sun, boolean repot) {
this.water = water;
this.look = look;
this.sun = sun;
this.repot = repot;
}
public void updateSun(Boolean sun) { this.sun = sun; }
public void updateRepot(Boolean repot){ this.repot = repot; }
public void updateWater(Boolean water) { this.water = water; }
public void updateLook(Boolean look) { this.look = look; }
}
2️⃣ MyPlantService
@RequiredArgsConstructor
@Service
public class MyPlantService {
private final PlantLogRepository plantLogRepository;
@Transactional
public Long updateSun(Long userId, Long myPlantId) {
PlantLog plantLog = plantLogRepository.findById(myPlantId).orElseThrow(
() -> new IllegalArgumentException("해당 식물이 없습니다.")
);
plantLog.updateSun(true);
return plantLog.getPlantId();
}
.......
}
3️⃣ MyPlantApiController
@RequiredArgsConstructor
@RestController
@RequestMapping("/myplant")
public class MyPlantApiController {
private final PlantLogRepository plantLogRepository;
@PutMapping("/sun/{userId}/{myPlantId}")
public ResponseEntity<MyPlantUpdateResponse> putSun(@PathVariable Long userId, @PathVariable Long myPlantId) {
myPlantService.updateSun(userId, myPlantId);
return MyPlantUpdateResponse.newResponse(UPDATE_SUNPLANTLOG_SUCCESS);
}
.......
}
📍 결과화면


📍 참고한 것들
책 스프링 부트와 AWS로 혼자 구현하는 웹 서비스