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] 김서현 미션 제출합니다. #277

Open
wants to merge 3 commits into
base: seobbang
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
6 changes: 3 additions & 3 deletions src/main/java/roomescape/Reservation.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ public class Reservation {
@NotBlank(message = "날짜는 필수 입력 값입니다.")
private String date;
@NotBlank(message = "시간은 필수 입력 값입니다.")
private String time;
private Time time;

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 @@ -31,7 +31,7 @@ public String getName() {
return name;
}

public String getTime() {
public Time getTime() {
return time;
}
}
7 changes: 3 additions & 4 deletions src/main/java/roomescape/ReservationController.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public ReservationController(ReservationQueryingDAO queryingDAO) {
this.queryingDAO = queryingDAO;
}

@GetMapping("/reservation")
@GetMapping("/new-reservation")
public void reservation () {
}
Copy link

Choose a reason for hiding this comment

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

미션 요구사항은 request mapping의 uri를 바꾸는 것이 아니었습니다. 다시 확인해주세요!

그리고! 저번에 제가 코드만 슥 봐서 리뷰를 못드렸는데 이렇게 아무것도 반환하지 않으면 테스트가 통과하지 못합니다. -> thymeleaf 사용법에 대해 알아보세요!


Expand All @@ -34,13 +34,12 @@ public ResponseEntity<List<Reservation>> read() {
public ResponseEntity<ResponseDto> create (@RequestBody ReservationRequestDto request) {
Copy link

Choose a reason for hiding this comment

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

여기도 마찬가지! API 스펙을 보고 시그니처를 고쳐주세요.

String name = request.getName();
String date = request.getDate();
String time = request.getTime();

Long time = request.getTime();

long id = queryingDAO.createReservation(name, date, time);
Copy link

Choose a reason for hiding this comment

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

DAO 에서 create 연산 시 reservation을 반환하는 것이 자연스러울 것 같아요.

(TimeController에서는 불편을 못느꼈겠지만) 여기서는 Reservation 객체, 그 안의 Time 객체를 직접 생성해서 반환하는 것이 불편하다는 것을 아실 수 있을거예요.


URI location = URI.create("/reservations/" + id);
Reservation newReservation = new Reservation(id, name, date, time);
ReservationRequestDto newReservation = new ReservationRequestDto(id, name, date, time);
Copy link

Choose a reason for hiding this comment

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

응답에 RequestDto를 넣는 것이 부자연스럽게 느껴져요..! 공용으로 사용한다면 ReservationDto 라고 이름을 바꾸는 것이 어떨까요?


ResponseDto response = new ResponseDto(HttpStatus.CREATED.value(), "예약이 성공적으로 추가되었습니다.", newReservation);
return ResponseEntity.created(location).body(response);
Expand Down
17 changes: 11 additions & 6 deletions src/main/java/roomescape/ReservationQueryingDAO.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,16 @@ public class ReservationQueryingDAO {
private JdbcTemplate jdbcTemplate;

private final RowMapper<Reservation> actorRowMapper = (resultSet, rowNum) -> {
Time time = new Time(
resultSet.getLong("time_id"),
resultSet.getString("time_value")
);

Reservation reservation = new Reservation(
resultSet.getLong("id"),
resultSet.getLong("reservation_id"),
resultSet.getString("name"),
resultSet.getString("date"),
resultSet.getString("time")
time
);
return reservation;
};
Expand All @@ -30,18 +35,18 @@ public ReservationQueryingDAO(JdbcTemplate jdbcTemplate) {


public List<Reservation> getReservations() {
String sql = "SELECT id, name, date, time FROM reservation";
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, actorRowMapper);
}

public long createReservation(String name, String date, String time) {
String sql = "INSERT INTO reservation(name, date, time) VALUES (?, ?, ?)";
public long createReservation(String name, String date, Long time) {
String sql = "INSERT INTO reservation(name, date, time_id) VALUES (?, ?, ?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, name);
ps.setString(2, date);
ps.setString(3, time);
ps.setObject(3, time);
Copy link

Choose a reason for hiding this comment

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

데이터베이스 스키마를 보면 time_id 는 BIGINT 타입이죠, 그럼 java의 Long 으로 사용할 수 있습니당. 제 생각에는 별도로 변환이 필요하지 않은 setLong 메서드를 사용하는 것이 더 효율적일 것 같습니다. 또한 타입을 명시하면 이 코드만으로도 데이터베이스 스키마를 유추할 수 있게 되는 건 덤일 것 같습니다.

return ps;
}, keyHolder);

Expand Down
12 changes: 6 additions & 6 deletions src/main/java/roomescape/ReservationRequestDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,26 @@
import org.thymeleaf.util.StringUtils;

public class ReservationRequestDto {
private Long id;
private String name;
private String date;
private String time;
private Long time;

public ReservationRequestDto(String name, String date, String time) {
public ReservationRequestDto(Long id, String name, String date, Long time) {
if (StringUtils.isEmpty(name)) {
throw new BadRequestCreateReservationException("The 'name' field is missing.");
}
if (StringUtils.isEmpty(date)) {
throw new BadRequestCreateReservationException("The 'date' field is missing.");
}
if (StringUtils.isEmpty(time)) {
throw new BadRequestCreateReservationException("The 'time' field is missing.");
}
this.id = id;
this.name = name;
this.date = date;
this.time = time;
}
public Long getId() {return id;}

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

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


public class Time {
private long id;
// @NotBlank(message = "시간은 필수 입력 값입니다.")
private String time;

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

public long getId() {
return id;
}

public String getTime() {
return time;
}

// public Time(long id, String name, String date, String time) {
// this.id = id;
// this.name = name;
// this.date = date;
// this.time = time;
// }

Copy link

Choose a reason for hiding this comment

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

사용하지 않는 코드는 지워주세요!

Copy link

Choose a reason for hiding this comment

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

마찬가지!

}
54 changes: 54 additions & 0 deletions src/main/java/roomescape/TimeController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package roomescape;

import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

@Controller
public class TimeController {
private TimeQueryingDAO queryingDAO;
Copy link

Choose a reason for hiding this comment

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

멤버변수에 final 키워드를 적용했을 때의 장점을 찾아보고 적용해볼까요?


public TimeController(TimeQueryingDAO queryingDAO) {
this.queryingDAO = queryingDAO;
}
@GetMapping("/time")
public void time () {
Copy link

Choose a reason for hiding this comment

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

위에도 코멘트 드렸는데 연결을 위해서는 시그니처와 반환값을 변경해주셔야합니다! (thymeleaf)


}
@GetMapping("/times")
public ResponseEntity<List<Time>> read() {
return ResponseEntity.ok(queryingDAO.getTimes());
}

@PostMapping("/times")
public ResponseEntity<ResponseDto> create (@RequestBody TimeRequestDto request) {

Copy link

Choose a reason for hiding this comment

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

시간 생성 API 응답 스펙을 보고 리턴 타입을 고쳐주시길 바랍니다!

String time = request.getTime();
long id = queryingDAO.createTime(time);
Copy link

Choose a reason for hiding this comment

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

DAO에서 Time을 반환하는 것이 자연스럽지 않을까요? 그렇지 않으면 DAO를 사용하는 코드에서 항상 Time 객체를 손수 만들어줘야해요


URI location = URI.create("/times/" + id);
Time newTime = new Time(id, time);

ResponseDto response = new ResponseDto(HttpStatus.CREATED.value(), "시간이 성공적으로 추가되었습니다.", newTime);
return ResponseEntity.created(location).body(response);
}

@DeleteMapping("/times/{id}")
public ResponseEntity<Void> delete (@PathVariable Long id) {
int rowsAffected = queryingDAO.deleteTimeById(id);

if(rowsAffected > 0){
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}else {
throw new NotFoundReservationException("Time with id " + id + " not found." );
}
}
Copy link

Choose a reason for hiding this comment

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

Suggested change
}
if (rowsAffected == 0) {
throw new NotFoundReservationException();
}
return ResponseEntity.noContent().build();

그냥 생각나서 적어보는 것인데요 저는 보통 else 를 쓰지 않는 것이 가독성이 좋다고 느껴지더라구요.
+) 그리고 미션 제출 전 포맷팅 한 번씩 해주세요~

}


53 changes: 53 additions & 0 deletions src/main/java/roomescape/TimeQueryingDAO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package roomescape;

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 java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.List;

@Repository
public class TimeQueryingDAO {
private JdbcTemplate jdbcTemplate;
private final RowMapper<Time> actorRowMapper = (resultSet, rowNum) -> {
Time time = new Time(
resultSet.getLong("id"),
resultSet.getString("time")
);
return time;
};
public TimeQueryingDAO(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public List<Time> getTimes() {
String sql = "SELECT id, time FROM time";
return jdbcTemplate.query(sql, actorRowMapper);
}
public long createTime(String time) {
String sql = "INSERT INTO time (time) VALUES (?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, time);
return ps;
}, keyHolder);

return keyHolder.getKey().longValue();
}

/**
*
* @param id
* @return delete된 id값
*/

public int deleteTimeById(long id) {
String sql = "DELETE FROM time WHERE id = ?";
return jdbcTemplate.update(sql, id);
}
}
17 changes: 17 additions & 0 deletions src/main/java/roomescape/TimeRequestDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package roomescape;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.thymeleaf.util.StringUtils;

public class TimeRequestDto {
private String time;
@JsonCreator
public TimeRequestDto(@JsonProperty("time") String time) {
this.time = time;
}

public String getTime() {
return time;
}
}
20 changes: 14 additions & 6 deletions src/main/resources/schema.sql
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
CREATE TABLE reservation
CREATE TABLE time
(
id BIGINT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
date VARCHAR(255) NOT NULL,
time VARCHAR(255) NOT NULL,
id BIGINT NOT NULL AUTO_INCREMENT,
time VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
);

CREATE TABLE reservation
(
id BIGINT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
date VARCHAR(255) NOT NULL,
time_id BIGINT,
PRIMARY KEY (id),
FOREIGN KEY (time_id) REFERENCES time(id)
);
Loading