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] 이준민 미션 제출합니다 :) #384

Open
wants to merge 6 commits into
base: jermany17
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
63 changes: 14 additions & 49 deletions src/main/java/roomescape/controller/ReservationController.java
Original file line number Diff line number Diff line change
@@ -1,85 +1,50 @@
package roomescape.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import roomescape.exception.NotFoundReservationException;
import roomescape.model.Reservation;
import roomescape.model.ReservationRequest;
import roomescape.model.ReservationRequest;;
import roomescape.service.ReservationService;

import java.net.URI;
import java.sql.PreparedStatement;
import java.util.List;

@Controller
public class ReservationController {

private final JdbcTemplate jdbcTemplate;
private final ReservationService reservationService;

public ReservationController(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
public ReservationController(ReservationService reservationService) {
this.reservationService = reservationService;
}

private final RowMapper<Reservation> reservationRowMapper = (rs, rowNum) -> new Reservation(
rs.getLong("id"),
rs.getString("name"),
rs.getString("date"),
rs.getString("time")
);

// 예약 관리 페이지
@GetMapping("/reservation")
public String reservationPage() {
return "reservation";
return "new-reservation";
}

// 예약 조회
@GetMapping("/reservations")
@ResponseBody
public List<Reservation> getReservations() {
String sql = "SELECT id, name, date, time FROM reservation";
return jdbcTemplate.query(sql, reservationRowMapper);
public ResponseEntity<List<Reservation>> getReservations() {
List<Reservation> reservations = reservationService.getReservations();
return ResponseEntity.ok(reservations);
}

// 예약 추가
@PostMapping("/reservations")
@ResponseBody
public ResponseEntity<Reservation> addReservation(@RequestBody ReservationRequest request) {
request.validate();

Reservation newReservation = new Reservation(null, request.getName(), request.getDate(), request.getTime());

String sql = "INSERT INTO reservation (name, date, time) VALUES (?, ?, ?)";
KeyHolder keyHolder = new GeneratedKeyHolder();

jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, new String[] {"id"});
ps.setString(1, newReservation.getName());
ps.setString(2, newReservation.getDate());
ps.setString(3, newReservation.getTime());
return ps;
}, keyHolder);

Long id = keyHolder.getKey().longValue();
newReservation.setId(id);

return ResponseEntity.created(URI.create("/reservations/" + id)).body(newReservation);
Reservation newReservation = reservationService.addReservation(request);
return ResponseEntity.created(URI.create("/reservations/" + newReservation.getId())).body(newReservation);

Choose a reason for hiding this comment

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

괄호가 깊게 중첩되어 있어요.
풀어내면 가독성이 좋아질 것 같아요

}

// 예약 삭제
@DeleteMapping("/reservations/{id}")
public ResponseEntity<Void> deleteReservation(@PathVariable Long id) {
String sql = "DELETE FROM reservation WHERE id = ?";
int rowsAffected = jdbcTemplate.update(sql, id);

if (rowsAffected > 0) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

throw new NotFoundReservationException("삭제할 예약이 없습니다.");
reservationService.deleteReservation(id);
return ResponseEntity.noContent().build();
}
}
50 changes: 50 additions & 0 deletions src/main/java/roomescape/controller/TimeController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package roomescape.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import roomescape.model.Time;
import roomescape.service.TimeService;

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

@Controller
public class TimeController {

private final TimeService timeService;

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

// 시간 관리 페이지
@GetMapping("/time")
public String reservationPage() {
return "time";
}

// 시간 조회
@GetMapping("/times")
@ResponseBody
public ResponseEntity<List<Time>> getTimes() {
List<Time> times = timeService.getAllTimes();
return ResponseEntity.ok(times);
}

// 시간 추가
@PostMapping("/times")
@ResponseBody
public ResponseEntity<Time> addTime(@RequestBody Time request) {
Time newTime = timeService.addTime(request);
return ResponseEntity.created(URI.create("/times/" + newTime.getId())).body(newTime);
}

// 시간 삭제
@DeleteMapping("/times/{id}")
@ResponseBody
public ResponseEntity<Void> deleteTime(@PathVariable Long id) {
timeService.deleteTime(id);
return ResponseEntity.noContent().build();
}
}
74 changes: 74 additions & 0 deletions src/main/java/roomescape/dao/ReservationDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package roomescape.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import roomescape.model.Reservation;
import roomescape.model.ReservationRequest;
import roomescape.model.Time;

import java.sql.PreparedStatement;
import java.util.List;

@Repository
public class ReservationDao {
Comment on lines +15 to +16

Choose a reason for hiding this comment

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

어노테이션은 Repository를,
클래스는 Dao라는 네이밍을 사용하셨군요.

둘의 차이가 어떤것이라 생각하시고, Dao라는 네이밍을 적용하신 이유가 궁금해요


private final JdbcTemplate jdbcTemplate;

private final RowMapper<Reservation> reservationRowMapper = (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 ReservationDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}

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 as r
INNER JOIN time as t
ON r.time_id = t.id
""";
return jdbcTemplate.query(sql, reservationRowMapper);
}

public Reservation save(ReservationRequest request) {
String sql = "INSERT INTO reservation (name, date, time_id) VALUES (?, ?, ?)";
KeyHolder keyHolder = new GeneratedKeyHolder();

jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, new String[]{"id"});
ps.setString(1, request.getName());
ps.setString(2, request.getDate());
ps.setLong(3, request.getTimeId());
return ps;
}, keyHolder);

Long id = keyHolder.getKey().longValue();

String timeQuery = "SELECT time FROM time WHERE id = ?";
String timeValue = jdbcTemplate.queryForObject(timeQuery, String.class, request.getTimeId());

return new Reservation(id, request.getName(), request.getDate(), new Time(request.getTimeId(), timeValue));
}

public int deleteById(Long id) {
String sql = "DELETE FROM reservation WHERE id = ?";
return jdbcTemplate.update(sql, id);
}
}
50 changes: 50 additions & 0 deletions src/main/java/roomescape/dao/TimeDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package roomescape.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import roomescape.model.Time;

import java.sql.PreparedStatement;
import java.util.List;

@Repository
public class TimeDao {

private final JdbcTemplate jdbcTemplate;

private final RowMapper<Time> timeRowMapper = (rs, rowNum) -> new Time(
rs.getLong("id"),
rs.getString("time")
);

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

public List<Time> findAll() {
String sql = "SELECT id, time FROM time";
return jdbcTemplate.query(sql, timeRowMapper);
}

public Time save(Time time) {
String sql = "INSERT INTO time (time) VALUES (?)";
KeyHolder keyHolder = new GeneratedKeyHolder();

jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, new String[]{"id"});
ps.setString(1, time.getTime());
return ps;
}, keyHolder);

Long id = keyHolder.getKey().longValue();
return new Time(id, time.getTime());
}

public int deleteById(Long id) {
String sql = "DELETE FROM time WHERE id = ?";
return jdbcTemplate.update(sql, id);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
public class GlobalExceptionHandler {

// 특정 예외를 처리하는 메서드를 정의

@ExceptionHandler(NotFoundReservationException.class)
public ResponseEntity<String> handleNotFoundReservationException(NotFoundReservationException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
Expand All @@ -20,4 +21,9 @@ public ResponseEntity<String> handleNotFoundReservationException(NotFoundReserva
public ResponseEntity<String> handleInvalidReservationException(InvalidReservationException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}

@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
22 changes: 15 additions & 7 deletions src/main/java/roomescape/model/Reservation.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,12 @@ public class Reservation {
private Long id;
private String name;
private String date;
private String time;
private Time time;

// 기본 생성자를 추가 하는 이유
// 1. Jackson과의 호환성 및 역직렬화 원활
// 2. 객체를 생성할 때 기본 생서자로 빈 객체를 만든 후 필드를 하나씩 채워 넣는다.
// 기본 생성자를 추가하지 않고 @JsonCreator와 @JsonProperty를 사용하는 방법도 있음.
public Reservation() {
}

public Reservation(Long id, String name, String date, String time) {
public Reservation(Long id, String name, String date, Time time) {
this.id = id;
this.name = name;
this.date = date;
Expand All @@ -32,12 +28,24 @@ public String getName() {
return name;
}

public void setName(String name) {

Choose a reason for hiding this comment

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

setter는 어떤 이유로 추가되었나요?

this.name = name;
}

public String getDate() {
return date;
}

public String getTime() {
public void setDate(String date) {
this.date = date;
}

public Time getTime() {
return time;
}

public void setTime(Time time) {
this.time = time;
}
}

Loading