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 1 commit
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
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.

마찬가지!

}
50 changes: 50 additions & 0 deletions src/main/java/roomescape/TimeController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
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("/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;
}
}
7 changes: 7 additions & 0 deletions src/main/resources/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,11 @@ CREATE TABLE reservation
date VARCHAR(255) NOT NULL,
time VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);

CREATE TABLE time
(
id BIGINT NOT NULL AUTO_INCREMENT,
time VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
25 changes: 25 additions & 0 deletions src/test/java/roomescape/MissionStepTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -154,4 +154,29 @@ void CREATE_AND_DELETE_RESERVATION() {
Integer countAfterDelete = jdbcTemplate.queryForObject("SELECT count(1) from reservation", Integer.class);
assertThat(countAfterDelete).isEqualTo(0);
}

@Test
void 팔단계() {
Map<String, String> params = new HashMap<>();
params.put("time", "10:00");

RestAssured.given().log().all()
.contentType(ContentType.JSON)
.body(params)
.when().post("/times")
.then().log().all()
.statusCode(201)
.header("Location", "/times/1");

RestAssured.given().log().all()
.when().get("/times")
.then().log().all()
.statusCode(200)
.body("size()", is(1));

RestAssured.given().log().all()
.when().delete("/times/1")
.then().log().all()
.statusCode(204);
}
}