Skip to content

Commit bad771c

Browse files
committed
feat: 7단계 - 데이터 추가/삭제하기
- 예약 추가/취소 API 처리 로직에서 데이터베이스를 활용하도록 수정
1 parent dec3a7a commit bad771c

File tree

7 files changed

+161
-16
lines changed

7 files changed

+161
-16
lines changed

build.gradle

+3
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ dependencies {
1919

2020
implementation 'org.springframework.boot:spring-boot-starter-web'
2121
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
22+
23+
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
24+
runtimeOnly 'com.h2database:h2'
2225
}
2326

2427
test {

src/main/java/roomescape/controller/ReservationController.java

+11-16
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import roomescape.dto.Reservation;
1212
import roomescape.exception.InvalidValueException;
1313
import roomescape.exception.NotFoundReservationException;
14+
import roomescape.repository.ReservationRepository;
1415

1516
import java.net.URI;
1617
import java.util.ArrayList;
@@ -20,14 +21,11 @@
2021
@Controller
2122
public class ReservationController {
2223

23-
private List<Reservation> reservations = new ArrayList<>();
24-
private AtomicLong index = new AtomicLong(1);
25-
// 이단계
26-
// public ReservationController() {
27-
// reservations.add(new Reservation(1L, "브라운1", "2023-01-01", "10:00"));
28-
// reservations.add(new Reservation(2L, "브라운2", "2023-01-02", "11:00"));
29-
// reservations.add(new Reservation(3L, "브라운3", "2023-01-03", "12:00"));
30-
// }
24+
private final ReservationRepository reservationRepository;
25+
26+
public ReservationController(ReservationRepository repository) {
27+
this.reservationRepository = repository;
28+
}
3129

3230
// 홈화면
3331
@GetMapping("/reservation")
@@ -39,7 +37,7 @@ public String reservationPage() {
3937
@ResponseBody
4038
@GetMapping("/reservations")
4139
public List<Reservation> list() {
42-
return reservations;
40+
return reservationRepository.findAll();
4341
}
4442

4543
//예약 추가
@@ -52,8 +50,7 @@ public ResponseEntity<Reservation> create(@RequestBody Reservation newReservatio
5250
throw new InvalidValueException("예약 추가에 필요한 인자값이 비어있습니다.");
5351
}
5452

55-
Reservation reservation = new Reservation(index.getAndIncrement(), newReservation.getName(), newReservation.getDate(), newReservation.getTime());
56-
reservations.add(reservation);
53+
Reservation reservation = reservationRepository.insert(newReservation);
5754

5855
return ResponseEntity.created(URI.create("/reservations/" + reservation.getId()))
5956
.body(reservation);
@@ -62,12 +59,10 @@ public ResponseEntity<Reservation> create(@RequestBody Reservation newReservatio
6259
//예약 삭제
6360
@DeleteMapping("/reservations/{id}")
6461
public ResponseEntity<Void> delete(@PathVariable Long id) {
65-
Reservation reservation = reservations.stream()
66-
.filter(it -> it.getId().equals(id))
67-
.findFirst()
68-
.orElseThrow(() -> new NotFoundReservationException("예약을 찾을 수 없습니다."));
62+
// 수정예정 Reservation reservation = reservationRepository.fin
63+
// .orElseThrow(() -> new NotFoundReservationException("예약을 찾을 수 없습니다."));
6964

70-
reservations.remove(reservation);
65+
reservationRepository.delete(id);
7166
return ResponseEntity.noContent().build();
7267
}
7368
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package roomescape.repository;
2+
3+
import org.springframework.http.ResponseEntity;
4+
import org.springframework.jdbc.core.JdbcTemplate;
5+
import org.springframework.stereotype.Repository;
6+
import roomescape.dto.Reservation;
7+
8+
import java.util.List;
9+
10+
@Repository
11+
public class ReservationRepository {
12+
13+
private final JdbcTemplate jdbcTemplate;
14+
15+
public ReservationRepository(JdbcTemplate jdbcTemplate) {
16+
this.jdbcTemplate = jdbcTemplate;
17+
}
18+
19+
//예약 조회
20+
public List<Reservation> findAll() {
21+
String sql = "SELECT id, name, date, time FROM reservation";
22+
23+
return jdbcTemplate.query(
24+
sql, (resultSet, rowNum) -> new Reservation(
25+
resultSet.getLong("id"),
26+
resultSet.getString("name"),
27+
resultSet.getString("date"),
28+
resultSet.getString("time")
29+
));
30+
}
31+
32+
//예약 추가
33+
public Reservation insert(Reservation reservation) {
34+
try {
35+
String sql = "INSERT INTO reservation(name, date, time) VALUES (?, ?, ?)";
36+
jdbcTemplate.update(sql, reservation.getName(), reservation.getDate(), reservation.getTime());
37+
38+
String query = "SELECT id FROM reservation ORDER BY id DESC LIMIT 1";
39+
Long id = jdbcTemplate.queryForObject(query, Long.class);
40+
41+
return new Reservation(id, reservation.getName(), reservation.getDate(), reservation.getTime());
42+
} catch (Exception ex) {
43+
throw new RuntimeException("오류가 발생하였습니다.");
44+
}
45+
}
46+
47+
//예약 삭제
48+
public ResponseEntity<Object> delete(Long id) {
49+
String sql = "DELETE FROM reservation WHERE id = ?";
50+
jdbcTemplate.update(sql, Long.valueOf(id));
51+
return ResponseEntity.noContent().build();
52+
}
53+
}
54+
Original file line numberDiff line numberDiff line change
@@ -1 +1,4 @@
11
server.port=8080
2+
spring.h2.console.enabled=true
3+
spring.h2.console.path=/h2-console
4+
spring.datasource.url=jdbc:h2:mem:database

src/main/resources/schema.sql

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
CREATE TABLE reservation
2+
(
3+
id BIGINT NOT NULL AUTO_INCREMENT,
4+
name VARCHAR(255) NOT NULL,
5+
date VARCHAR(255) NOT NULL,
6+
time VARCHAR(255) NOT NULL,
7+
PRIMARY KEY (id)
8+
);

src/test/java/roomescape/MissionStepTest.java

+2
Original file line numberDiff line numberDiff line change
@@ -92,4 +92,6 @@ public class MissionStepTest {
9292
.then().log().all()
9393
.statusCode(400);
9494
}
95+
96+
9597
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package roomescape;
2+
3+
import io.restassured.RestAssured;
4+
import io.restassured.http.ContentType;
5+
import org.junit.jupiter.api.Test;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.boot.test.context.SpringBootTest;
8+
import org.springframework.jdbc.core.JdbcTemplate;
9+
import org.springframework.test.annotation.DirtiesContext;
10+
import roomescape.dto.Reservation;
11+
12+
import java.sql.Connection;
13+
import java.sql.SQLException;
14+
import java.util.HashMap;
15+
import java.util.List;
16+
import java.util.Map;
17+
18+
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
19+
import static org.hamcrest.Matchers.is;
20+
21+
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
22+
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
23+
public class MissionStepTest2 {
24+
25+
@Autowired
26+
private JdbcTemplate jdbcTemplate;
27+
28+
@Test
29+
void 오단계() {
30+
try (Connection connection = jdbcTemplate.getDataSource().getConnection()) {
31+
assertThat(connection).isNotNull();
32+
assertThat(connection.getCatalog()).isEqualTo("DATABASE");
33+
assertThat(connection.getMetaData().getTables(null, null, "RESERVATION", null).next()).isTrue();
34+
} catch (SQLException e) {
35+
throw new RuntimeException(e);
36+
}
37+
}
38+
39+
@Test
40+
void 육단계() {
41+
jdbcTemplate.update("INSERT INTO reservation (name, date, time) VALUES (?, ?, ?)", "브라운", "2023-08-05", "15:40");
42+
43+
List<Reservation> reservations = RestAssured.given().log().all()
44+
.when().get("/reservations")
45+
.then().log().all()
46+
.statusCode(200).extract()
47+
.jsonPath().getList(".", Reservation.class);
48+
49+
Integer count = jdbcTemplate.queryForObject("SELECT count(1) from reservation", Integer.class);
50+
51+
assertThat(reservations.size()).isEqualTo(count);
52+
}
53+
54+
@Test
55+
void 칠단계() {
56+
Map<String, String> params = new HashMap<>();
57+
params.put("name", "브라운");
58+
params.put("date", "2023-08-05");
59+
params.put("time", "10:00");
60+
61+
RestAssured.given().log().all()
62+
.contentType(ContentType.JSON)
63+
.body(params)
64+
.when().post("/reservations")
65+
.then().log().all()
66+
.statusCode(201)
67+
.header("Location", "/reservations/1");
68+
69+
Integer count = jdbcTemplate.queryForObject("SELECT count(1) from reservation", Integer.class);
70+
assertThat(count).isEqualTo(1);
71+
72+
RestAssured.given().log().all()
73+
.when().delete("/reservations/1")
74+
.then().log().all()
75+
.statusCode(204);
76+
77+
Integer countAfterDelete = jdbcTemplate.queryForObject("SELECT count(1) from reservation", Integer.class);
78+
assertThat(countAfterDelete).isEqualTo(0);
79+
}
80+
}

0 commit comments

Comments
 (0)