Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Spring Core] 남해윤 미션 제출합니다. #391

Open
wants to merge 19 commits into
base: haeyoon1
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public ReservationController(ReservationService reservationService) {
// 홈화면
@GetMapping("/reservation")
public String reservationPage() {
return "reservation";
return "new-reservation";
}

//예약 조회
Expand Down
51 changes: 49 additions & 2 deletions src/main/java/roomescape/controller/TimeController.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,52 @@
package roomescape.controller;

public class ReservationTimeController {

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import roomescape.dto.TimeRequestDto;
import roomescape.dto.TimeResponseDto;
import roomescape.service.TimeService;

import java.net.URI;
import java.time.LocalDateTime;
import java.util.List;

@Controller
public class TimeController {
Comment on lines +18 to +19

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Controller는 전체적으로 깔끔하네요!👍👍


private final TimeService timeService;

public TimeController(TimeService timeService) {
this.timeService = timeService;
}

// 홈화면
@GetMapping("/time")
public String reservationPage() {
return "time";
}

@PostMapping("/times") //시간 추가
public ResponseEntity<TimeResponseDto> createTime(@RequestBody TimeRequestDto requestDto){
TimeResponseDto newTime = timeService.createTime(requestDto);
URI location = URI.create("/times/" + newTime.getId());

return ResponseEntity.created(location)
.body(newTime);
}
@GetMapping("/times") //시간 조회
public ResponseEntity<List<TimeResponseDto>> findTimes(){
List<TimeResponseDto> timeList = timeService.findAllTimes();
return ResponseEntity.ok(timeList);
}

@DeleteMapping("/times/{id}") // 시간 삭제
public ResponseEntity<TimeResponseDto> deleteTime(@PathVariable Long id){
timeService.deleteTime(id);
return ResponseEntity.noContent().build();
}
}
Empty file.
30 changes: 19 additions & 11 deletions src/main/java/roomescape/dao/ReservationDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import roomescape.entity.Reservation;
import roomescape.entity.Time;

import java.util.List;

Expand All @@ -15,21 +16,28 @@ public ReservationDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public List<Reservation> findAll(){
String sql = "SELECT id, name, date, time FROM reservation";

return jdbcTemplate.query(
sql, (resultSet, rowNum) -> new Reservation(
resultSet.getLong("id"),
resultSet.getString("name"),
resultSet.getString("date"),
resultSet.getTimestamp("time").toLocalDateTime()
));
public List<Reservation> findAll() {
String sql = """
SELECT r.id AS reservation_id, r.name, r.date, t.id AS time_id, t.time AS time_value
FROM reservation r
INNER JOIN time t ON r.time_id = t.id
""";

return jdbcTemplate.query(sql, (rs, rowNum) -> new Reservation(
rs.getLong("reservation_id"),
rs.getString("name"),
rs.getString("date"),
new Time(
rs.getLong("time_id"),
rs.getString("time_value")
)
));
}


public Reservation insert(Reservation reservation) {
String sql = "INSERT INTO reservation(name, date, time) VALUES (?, ?, ?)";
jdbcTemplate.update(sql, reservation.getName(), reservation.getDate(), reservation.getTime());
jdbcTemplate.update(sql, reservation.getName(), reservation.getDate(), reservation.getTime().getId());

String query = "SELECT id FROM reservation ORDER BY id DESC LIMIT 1";
Long id = jdbcTemplate.queryForObject(query, Long.class);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

방금 저장된 저장한 예약의 id를 조회하는 것 같아요.
이 방식은 여러 저장이 이루어지는 환경에서 문제가 생길 수 있어요.

저장과 동시에 DB에서 생성된 id를 반환하는 방식을 활용해보세요!

  • jdbcTemplate에서는 KeyHolder를 사용해볼 수 있어요

Expand Down
39 changes: 39 additions & 0 deletions src/main/java/roomescape/dao/TimeDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package roomescape.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import roomescape.entity.Time;

import java.util.List;

@Repository
public class TimeDao {
public final JdbcTemplate jdbcTemplate;

public TimeDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public List<Time> findAll() {
String sql = "SELECT id, time FROM time";
return jdbcTemplate.query(sql, (rs, rowNum) -> new Time(
rs.getLong("id"),
rs.getString("time")
));
}

public Time insert(Time time) {
String sql = "INSERT INTO time(time) VALUES (?)";
jdbcTemplate.update(sql, time.getTime());

String query = "SELECT id FROM time ORDER BY id DESC LIMIT 1";
Long id = jdbcTemplate.queryForObject(query, Long.class);

return new Time(id, time.getTime());
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

방금 저장한 시간의 id를 조회하는 것 같아요.
이 방식은 여러 저장이 이루어지는 환경에서 문제가 생길 수 있습니다.

27번 라인 이후 30번 라인의 실행 되지 전에 다른 쓰레드에서 저장이 이루어졌다면...?

저장과 동시에 DB에서 생성된 id를 반환하는 방식을 활용해보세요!

  • jdbcTemplate에서는 KeyHolder를 사용해볼 수 있어요


public void delete(Long id) {
String sql = "DELETE FROM time WHERE id = ?";
jdbcTemplate.update(sql, id);
}
}
12 changes: 8 additions & 4 deletions src/main/java/roomescape/dto/ReservationRequestDto.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package roomescape.dto;

import java.time.LocalDateTime;
import roomescape.entity.Time;

public class ReservationRequestDto {
private String name;
private String date;
private LocalDateTime time;
private String time;

public ReservationRequestDto(String name, String date, LocalDateTime time) {
public ReservationRequestDto(String name, String date, String time) {
this.name = name;
this.date = date;
this.time = time;
Expand All @@ -21,7 +21,11 @@ public String getDate() {
return date;
}

public LocalDateTime getTime() {
public String getTime() {
return time;
}

public Time getStringTimeAsTime(){ //string -> time
return new Time(time);
}
}
7 changes: 4 additions & 3 deletions src/main/java/roomescape/dto/ReservationResponseDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class ReservationResponseDto {
private Long id;
private String name;
private String date;
private LocalDateTime time;
private LocalTime time;

public ReservationResponseDto(Long id, String name, String date, LocalDateTime time) {
public ReservationResponseDto(Long id, String name, String date, LocalTime time) {
this.id = id;
this.name = name;
this.date = date;
Expand All @@ -28,7 +29,7 @@ public String getDate() {
return date;
}

public LocalDateTime getTime() {
public LocalTime getTime() {
return time;
}
}
16 changes: 12 additions & 4 deletions src/main/java/roomescape/dto/TimeRequestDto.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
package roomescape.dto;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class TimeRequestDto {
public LocalDateTime time;
private String time;

public TimeRequestDto(LocalDateTime time) {
public TimeRequestDto() {}

public TimeRequestDto(String time) {
this.time = time;
}

public LocalDateTime getTime() {
public String getTime() {
return time;
}

public LocalTime toLocalTime() { //string -> localTime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
return LocalTime.parse(time, formatter);
}
}
22 changes: 21 additions & 1 deletion src/main/java/roomescape/dto/TimeResponseDto.java
Original file line number Diff line number Diff line change
@@ -1,2 +1,22 @@
package roomescape.controller;public class TimeResponseDto {
package roomescape.dto;

import java.time.LocalTime;

public class TimeResponseDto {

public Long id;
public String time;

public TimeResponseDto(Long id, LocalTime time) {
this.id = id;
this.time = time.toString();
}

public Long getId() {
return id;
}

public String getTime() {
return time;
}
}
14 changes: 9 additions & 5 deletions src/main/java/roomescape/entity/Reservation.java
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
package roomescape.entity;

import java.time.LocalDateTime;
import java.time.LocalTime;

public class Reservation {
private Long id;
private String name;
private String date;
private LocalDateTime time;
private Time time;

public Reservation(Long id, String name, String date, LocalDateTime time) {
public Reservation(Long id, String name, String date, Time time) {
this.id = id;
this.name = name;
this.date = date;
this.time = time;
}

public Reservation(String name, String date, LocalDateTime time) {
public Reservation(String name, String date, Time time) {
this(null, name, date, time);
}

Expand All @@ -31,7 +31,11 @@ public String getDate() {
return date;
}

public LocalDateTime getTime() {
public Time getTime() {
return time;
}

public LocalTime getTimeAsLocalTime() {
return time.getTimeASALocalTime();
}
}
29 changes: 29 additions & 0 deletions src/main/java/roomescape/entity/Time.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package roomescape.entity;

import java.time.LocalTime;

public class Time {
public Long id;
public String time;

public Time(Long id, String time) {
this.id = id;
this.time = time;
}

public Time(String time) {
this(null, time);
}

public Long getId() {
return id;
}

public String getTime() {
return time;
}

public LocalTime getTimeASALocalTime(){ //string->LocalTime

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

메서드 네이밍 컨벤션에 맞춰주세요!

Suggested change
public LocalTime getTimeASALocalTime(){ //string->LocalTime
public LocalTime getTimeAsLocalTime(){ //string->LocalTime

return LocalTime.parse(time);
}
}
10 changes: 5 additions & 5 deletions src/main/java/roomescape/repository/TimeRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,23 @@
import java.util.List;

@Repository
public class TimeRespository {
public class TimeRepository {

private final TimeDao timeDao;

public TimeRespository(TimeDao timeDao) {
public TimeRepository(TimeDao timeDao) {
this.timeDao = timeDao;
}

public List<Time> findTime() {
public List<Time> findAll() {
return timeDao.findAll();
}

public Time insertTime(Time time) {
public Time save(Time time) {
return timeDao.insert(time);
}

public void deleteTime(Long id) {
public void deleteById(Long id) {
timeDao.delete(id);
}
}
7 changes: 5 additions & 2 deletions src/main/java/roomescape/service/ReservationService.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package roomescape.service;

import org.springframework.stereotype.Service;
import roomescape.dao.ReservationDao;
import roomescape.dto.ReservationRequestDto;
import roomescape.dto.ReservationResponseDto;
import roomescape.entity.Reservation;
import roomescape.entity.Time;
import roomescape.repository.ReservationRepository;
import roomescape.repository.TimeRepository;

import java.util.List;
import java.util.stream.Collectors;
Expand All @@ -30,7 +33,7 @@ public ReservationResponseDto createReservation(ReservationRequestDto requestDto
Reservation reservation = new Reservation(
requestDto.getName(),
requestDto.getDate(),
requestDto.getTime()
requestDto.getStringTimeAsTime()
);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dto -> Entity로의 변환 작업을 dto에 편의 메서드를 추가해볼 수도 있을 것 같아요.

class ReservationRequestDto {
// ...

    public Reservation toReservation() {
         // 변환 로직
    }
}

Dto 객체에 변환 로직을 추가하여 getStringTimeAsTime() 메서드를 굳이 제공하지 않아도 될거 같네요!

Copy link
Author

@haeyoon1 haeyoon1 Dec 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ReservationService 클래스의 createReservation 메서드에

        Long timeId = parseTimeId(requestDto.getTime());
        Time time = findTimeById(timeId);

        Reservation reservation = new Reservation(
                requestDto.getName(),
                requestDto.getDate(),
                time
        );

이렇게 수정했는데 처음에 코멘트 남겨주신대로 dto에 변환 로직을 만들어서 작성하는 것이 나을까요?

Reservation savedReservation = reservationRepository.insert(reservation);
return toResponseDto(savedReservation);
Expand All @@ -45,7 +48,7 @@ private ReservationResponseDto toResponseDto(Reservation reservation) {
reservation.getId(),
reservation.getName(),
reservation.getDate(),
reservation.getTime()
reservation.getTime().getTimeASALocalTime()
);
}
}
Loading