package com.example.schedule.service;
import com.example.schedule.dto.ScheduleRequestDto;
import com.example.schedule.dto.ScheduleResponseDto;
import com.example.schedule.entity.Schedule;
import com.example.schedule.repository.ScheduleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
@Service
public class ScheduleServiceImpl implements ScheduleService{
private final ScheduleRepository scheduleRepository;
@Autowired
public ScheduleServiceImpl(ScheduleRepository scheduleRepository){
this.scheduleRepository = scheduleRepository;
}
@Override
public ScheduleResponseDto saveSchedule(ScheduleRequestDto dto) {
//요청받은 데이터를 스케쥴 객체 생성 id없이
Schedule schedule = new Schedule(dto.getName(), dto.getPassword(), dto.getTodo(), LocalDateTime.now());
return scheduleRepository.saveSchedule(schedule);
}
//다찾는거
@Override
public List<ScheduleResponseDto> findAllSchedules(){
return scheduleRepository.findAllSchedules();
}
//일부찾기
@Override
public ScheduleResponseDto findScheduleById(Long id){
//없는거 방지
Optional<Schedule> optionalSchedule = scheduleRepository.findScheduleById(id);
//npe방지
if(optionalSchedule.isEmpty()){
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Does not exist id = " + id);
}
return new ScheduleResponseDto(optionalSchedule.get());
}
//수정
@Transactional
@Override
public ScheduleResponseDto updateSchedule(Long id, String name, String todo){
if(name == null || todo == null ){
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "잘못된 설정");
}
int updatedRow = scheduleRepository.updateSchedule(id, name, todo);
if(updatedRow == 0){
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "변경 사항 없음");
}
Optional<Schedule> optionSchedule = scheduleRepository.findScheduleById(id);
if (optionSchedule.isEmpty()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "스케줄을 찾을 수 없습니다.");
}
return new ScheduleResponseDto(optionSchedule.get());
}
//삭제
public int deleteSchedule(Long id,String password){
int deletedRow = scheduleRepository.deleteSchedule(id, password);
if (deletedRow == 0){
throw new ResponseStatusException(HttpStatus.NOT_FOUND, " 잘못된 패스워드입니다");
}
return deletedRow;
}
}
package com.example.schedule.dto;
import com.example.schedule.entity.Schedule;
import lombok.Getter;
import java.time.LocalDateTime;
@Getter
public class ScheduleResponseDto {
// id, `할일`, `작성자명`, `비밀번호`, `작성/수정일`(형식 : YYYY-MM-DD)을 저장 id는 자동생성
//주의: `작성/수정일`은 날짜와 시간을 모두 포함한 형태 최초 입력 시, 수정일은 작성일과 동일
private final long id; //만들때 따로 지정안하도록 주의해야함
private final String name;//이름
private final String password;//비번
private final String todo;//할일
private final LocalDateTime createday;//최초
private final LocalDateTime reportingday;//수정
public ScheduleResponseDto(Schedule schedule){
this.id = schedule.getId();
this.name = schedule.getName();
this.password = schedule.getPassword();
this.todo = schedule.getTodo();
this.createday = schedule.getCreateday();
this.reportingday = schedule.getReportingday();
}
public ScheduleResponseDto(long id, String name, String password, String todo, LocalDateTime createday, LocalDateTime reportingday) {
this.id = id;
this.name = name;
this.password = password;
this.todo = todo;
this.createday = createday;
this.reportingday = reportingday;
}
}
package com.example.schedule.repository;
import com.example.schedule.dto.ScheduleResponseDto;
import com.example.schedule.entity.Schedule;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Repository
public class JdbcTemplateScheduleRepository implements ScheduleRepository {
private final JdbcTemplate jdbcTemplate;
public JdbcTemplateScheduleRepository(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
//생성
@Override
public ScheduleResponseDto saveSchedule(Schedule schedule){
//insert 퀴리 문자열 직접 작성안해도되게해줌 그리고 자동증가 ID
SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
jdbcInsert.withTableName("schedule").usingGeneratedKeyColumns("id");
//현재시간 가져옴
LocalDateTime now = LocalDateTime.now();
Map<String, Object> parameters = new HashMap<>();
parameters.put("name", schedule.getName());
parameters.put("password", schedule.getPassword());
parameters.put("todo", schedule.getTodo());
parameters.put("createday", now);
parameters.put("reportingday", now);//최초값은 수정일과 작성일 같으므로 이렇게 작성
//저장후 생성된 key값 number 타입으로 반환
Number key = jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(parameters));
Schedule savedSchedule = new Schedule(key.longValue(), schedule.getName(),schedule.getPassword(), schedule.getTodo(), now, now);
return new ScheduleResponseDto(savedSchedule);
}
//전체 조회
@Override
public List<ScheduleResponseDto> findAllSchedules() {
return jdbcTemplate.query("select * from schedule ORDER BY reportingday ", scheduleRowMapper());
}
//일부 조회
@Override
public Optional<Schedule> findScheduleById(long id) {
List<Schedule> result = jdbcTemplate.query("select * from schedule where id = ?", scheduleRowMapperV2(), id);
return result.stream().findAny();
}
//수정
@Override
public int updateSchedule(Long id, String name, String todo){
return jdbcTemplate.update("update schedule set name = ?, todo = ?, reportingday =? where id = ?",name,todo,LocalDateTime.now(),id);
}
//삭제
@Override
public int deleteSchedule(Long id,String password) {
return jdbcTemplate.update("delete from schedule where id = ? and password = ?", id, password);
}
private RowMapper<ScheduleResponseDto> scheduleRowMapper(){
return (rs, rowNum) -> new ScheduleResponseDto(
rs.getLong("id"),
rs.getString("name"),
rs.getString("password"),
rs.getString("todo"),
rs.getTimestamp("createday").toLocalDateTime(),
rs.getTimestamp("reportingday").toLocalDateTime()
);
}
private RowMapper<Schedule> scheduleRowMapperV2(){
return (rs, rowNum) -> new Schedule(
rs.getString("name"),
rs.getString("password"),
rs.getString("todo"),
rs.getTimestamp("reportingday").toLocalDateTime()
);
}
}
package com.example.schedule.controller;
import com.example.schedule.dto.ScheduleResponseDto;
import com.example.schedule.dto.ScheduleRequestDto;
import com.example.schedule.service.ScheduleService;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping("/schedules")
public class ScheduleController {
private final ScheduleService scheduleService;
public ScheduleController(ScheduleService scheduleService) {
this.scheduleService = scheduleService;
}
//일단 생성
@PostMapping
public ScheduleResponseDto createSchedule(@RequestBody ScheduleRequestDto dto) {
return scheduleService.saveSchedule(dto);
}
//모든 목록조회
@GetMapping
public List<ScheduleResponseDto> getAllSchedules() {
return scheduleService.findAllSchedules();
}
//단일 목록 조회
@GetMapping("/{id}")
public ScheduleResponseDto findScheduleById(@PathVariable("id") Long id) {
return scheduleService.findScheduleById(id);
}
//업데이트
@PatchMapping("/{id}")
public ScheduleResponseDto updateSchedule(
@PathVariable("id") Long id,
@RequestBody ScheduleRequestDto dto) {
return scheduleService.updateSchedule(id, dto.getName(), dto.getTodo());
}
//삭제
@DeleteMapping("/{id}")
public int deleteSchedule(
@PathVariable("id") Long id,
@RequestBody Map<String, String> request) {
String password = request.get("password");
{
return scheduleService.deleteSchedule(id, password);
}
}
}
post man으로 실행결과
생성
조회
수정
삭제가 가능하였다.
'스프링' 카테고리의 다른 글
SOLID 원칙 (0) | 2025.03.26 |
---|---|
트러블 슈팅 (0) | 2025.03.25 |
스프링 부트 설정 (0) | 2025.03.20 |
@Component (0) | 2025.03.18 |
start.spring.io (0) | 2025.02.12 |