Skip to content

Commit 944254c

Browse files
committed
스프링jdbc변환
1 parent 065ec38 commit 944254c

File tree

6 files changed

+103
-119
lines changed

6 files changed

+103
-119
lines changed

build.gradle

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,11 @@ dependencies {
1919
testImplementation 'org.springframework.boot:spring-boot-starter-test'
2020
testImplementation 'io.rest-assured:rest-assured:5.3.1'
2121
runtimeOnly 'com.h2database:h2'
22+
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
2223
}
2324

2425
test {
2526
useJUnitPlatform()
2627
}
28+
29+
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
distributionBase=GRADLE_USER_HOME
22
distributionPath=wrapper/dists
3-
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
3+
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-all.zip
44
zipStoreBase=GRADLE_USER_HOME
55
zipStorePath=wrapper/dists
Lines changed: 32 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -1,121 +1,55 @@
11
package roomescape.dao;
22

3-
import jakarta.annotation.PostConstruct;
4-
import java.sql.Connection;
5-
import java.sql.DriverManager;
6-
import java.sql.PreparedStatement;
7-
import java.sql.SQLException;
83
import java.time.LocalDate;
94
import java.time.LocalTime;
105
import java.time.format.DateTimeFormatter;
11-
import org.springframework.stereotype.Component;
6+
import java.util.List;
7+
import java.util.Optional;
8+
import org.springframework.jdbc.core.JdbcTemplate;
9+
import org.springframework.jdbc.core.RowMapper;
10+
import org.springframework.stereotype.Repository;
1211
import roomescape.domain.Reservation;
1312

14-
@Component
13+
@Repository
1514
public class ReservationDAO {
1615

17-
private static final String URL = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";
18-
private static final String USERNAME = "sa";
19-
private static final String PASSWORD = "";
16+
private final JdbcTemplate jdbcTemplate;
2017

21-
public Connection getConnection() {
22-
try {
23-
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
24-
} catch (final SQLException e) {
25-
throw new RuntimeException("DB 연결 실패: " + e.getMessage(), e);
26-
}
18+
public ReservationDAO(JdbcTemplate jdbcTemplate) {
19+
this.jdbcTemplate = jdbcTemplate;
2720
}
2821

22+
public Reservation addReservation(final Reservation reservation) {
23+
final var query = "INSERT INTO reservation (name, date, time) VALUES (?, ?, ?)";
24+
jdbcTemplate.update(query,
25+
reservation.getName(),
26+
reservation.getDate().toString(),
27+
reservation.getTime().toString());
2928

30-
@PostConstruct
31-
public void createTable() {
32-
33-
final var query = "CREATE TABLE IF NOT EXISTS RESERVATION (" +
34-
"ID BIGINT PRIMARY KEY, " +
35-
"NAME VARCHAR(50), " +
36-
"DATE VARCHAR(20), " +
37-
"TIME VARCHAR(20))";
38-
39-
try (
40-
final var connection = getConnection();
41-
) {
42-
connection.createStatement().execute(query);
43-
} catch (final SQLException e) {
44-
throw new RuntimeException(e);
45-
}
29+
final var fetchSql = "SELECT * FROM reservation ORDER BY id DESC LIMIT 1";
30+
return jdbcTemplate.queryForObject(fetchSql, reservationRowMapper);
4631
}
4732

48-
public void addReservation(final Reservation reservation) {
49-
final var query = "INSERT INTO RESERVATION VALUES(?, ?, ?, ?)";
50-
try (
51-
final var connection = getConnection();
52-
final var preparedStatement = connection.prepareStatement(query);
53-
) {
54-
preparedStatement.setLong(1, reservation.getId());
55-
preparedStatement.setString(2, reservation.getName());
56-
preparedStatement.setString(3, reservation.getDate().toString());
57-
preparedStatement.setString(4, reservation.getTime().toString());
58-
preparedStatement.executeUpdate();
59-
} catch (final SQLException e) {
60-
throw new RuntimeException(e);
61-
}
62-
}
63-
64-
public Reservation findReservation(final int id) {
65-
final var query = "SELECT * FROM RESERVATION WHERE ID = ?";
66-
try (
67-
final var connection = getConnection();
68-
final var preparedStatement = connection.prepareStatement(query);
69-
) {
70-
preparedStatement.setLong(1, id);
71-
72-
final var resultSet = preparedStatement.executeQuery();
73-
74-
if (resultSet.next()) {
75-
LocalDate date = LocalDate.parse(resultSet.getString("DATE"), DateTimeFormatter.ISO_DATE);
76-
LocalTime time = LocalTime.parse(resultSet.getString("TIME"), DateTimeFormatter.ISO_TIME);
77-
78-
System.out.println(date + " " + time);
79-
return new Reservation(
80-
resultSet.getInt("ID"),
81-
resultSet.getString("NAME"),
82-
date, time
83-
);
84-
}
85-
86-
87-
} catch (final SQLException e) {
88-
throw new RuntimeException(e);
89-
}
90-
91-
return null;
33+
public Optional<Reservation> findByID(final int id) {
34+
final var query = "SELECT * FROM reservation WHERE id = ?";
35+
List<Reservation> results = jdbcTemplate.query(query, reservationRowMapper, id);
36+
return results.stream().findFirst();
9237
}
9338

9439
public void deleteReservation(final int id) {
95-
final var query = "DELETE FROM RESERVATION WHERE ID = ?";
96-
try (
97-
final var connection = getConnection();
98-
final var preparedStatement = connection.prepareStatement(query)
99-
) {
100-
preparedStatement.setLong(1, id);
101-
preparedStatement.executeUpdate();
102-
} catch (final SQLException e) {
103-
throw new RuntimeException(e);
104-
}
40+
final var query = "DELETE FROM reservation WHERE id = ?";
41+
jdbcTemplate.update(query, id);
10542
}
10643

107-
public void resetTable() {
108-
try (var connection = getConnection()) {
109-
var stmt = connection.createStatement();
110-
stmt.execute("DROP TABLE IF EXISTS RESERVATION");
111-
stmt.execute("CREATE TABLE RESERVATION (" +
112-
"ID BIGINT PRIMARY KEY, " +
113-
"NAME VARCHAR(50), " +
114-
"DATE VARCHAR(20), " +
115-
"TIME VARCHAR(20))");
116-
} catch (SQLException e) {
117-
throw new RuntimeException(e);
118-
}
44+
public List<Reservation> findAll() {
45+
final var query = "SELECT * FROM reservation";
46+
return jdbcTemplate.query(query, reservationRowMapper);
11947
}
12048

49+
private final RowMapper<Reservation> reservationRowMapper = (resultSet, rowNum) -> new Reservation(
50+
resultSet.getInt("id"),
51+
resultSet.getString("name"),
52+
LocalDate.parse(resultSet.getString("date"), DateTimeFormatter.ISO_DATE),
53+
LocalTime.parse(resultSet.getString("time"), DateTimeFormatter.ISO_TIME)
54+
);
12155
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
spring.h2.console.enabled=true
2+
spring.h2.console.path=/h2-console
3+
4+
spring.datasource.url=jdbc:h2:mem:database
5+
spring.datasource.username=sa
6+
spring.datasource.password=
7+
8+
spring.sql.init.mode=embedded

src/main/resources/schema.sql

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

src/test/java/roomescape/DAOTest.java

Lines changed: 52 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,86 @@
11
package roomescape;
22

3-
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
3+
import static org.assertj.core.api.Assertions.assertThat;
44

5+
import io.restassured.RestAssured;
6+
import java.sql.Connection;
57
import java.sql.SQLException;
68
import java.time.LocalDate;
79
import java.time.LocalTime;
10+
import java.util.List;
11+
import java.util.Optional;
812
import org.junit.jupiter.api.BeforeEach;
913
import org.junit.jupiter.api.Test;
14+
import org.springframework.beans.factory.annotation.Autowired;
15+
import org.springframework.boot.test.context.SpringBootTest;
16+
import org.springframework.jdbc.core.JdbcTemplate;
1017
import roomescape.dao.ReservationDAO;
1118
import roomescape.domain.Reservation;
1219

20+
@SpringBootTest
1321
public class DAOTest {
1422

15-
private final ReservationDAO reservationDAO = new ReservationDAO();
23+
@Autowired
24+
private ReservationDAO reservationDAO;
25+
@Autowired
26+
private JdbcTemplate jdbcTemplate;
1627

1728
@BeforeEach
1829
void setUp() {
19-
reservationDAO.resetTable();
20-
}
21-
22-
@Test
23-
public void connection() {
24-
try (final var connection = reservationDAO.getConnection()) {
25-
assertThat(connection).isNotNull();
26-
} catch (SQLException e) {
27-
throw new RuntimeException(e);
28-
}
30+
reservationDAO.findAll().forEach(reservation ->
31+
reservationDAO.deleteReservation(reservation.getId()));
2932
}
3033

3134
@Test
3235
void addReservation() {
33-
final var reservation = new Reservation(1, "전서희", LocalDate.parse("2026-05-12"), LocalTime.parse("19:00"));
36+
Reservation reservation = new Reservation(1, "전서희", LocalDate.parse("2026-05-12"), LocalTime.parse("19:00"));
3437
reservationDAO.addReservation(reservation);
38+
assertThat(reservationDAO.findAll()).isNotEmpty();
3539
}
3640

3741
@Test
3842
void findReservation() {
39-
final var reservation = new Reservation(1, "전서희", LocalDate.parse("2026-05-12"), LocalTime.parse("19:00"));
43+
Reservation reservation = new Reservation(1, "전서희", LocalDate.parse("2026-05-12"), LocalTime.parse("19:00"));
4044
reservationDAO.addReservation(reservation);
41-
final var reservation2 = reservationDAO.findReservation(reservation.getId());
42-
assertThat(reservation2).isEqualTo(new Reservation(1, "전서희", LocalDate.parse("2026-05-12"), LocalTime.parse("19:00")));
45+
46+
Optional<Reservation> found = reservationDAO.findByID(1);
47+
assertThat(found).isPresent();
48+
assertThat(found.get()).isEqualTo(reservation);
4349
}
4450

4551
@Test
4652
void deleteReservation() {
47-
final var reservation = new Reservation(1, "전서희", LocalDate.parse("2026-05-12"), LocalTime.parse("19:00"));
53+
Reservation reservation = new Reservation(1, "전서희", LocalDate.parse("2026-05-12"), LocalTime.parse("19:00"));
4854
reservationDAO.addReservation(reservation);
49-
reservationDAO.deleteReservation(reservation.getId());
50-
final var result = reservationDAO.findReservation(reservation.getId());
51-
assertThat(result).isNull();
55+
reservationDAO.deleteReservation(1);
56+
57+
Optional<Reservation> result = reservationDAO.findByID(1);
58+
assertThat(result).isEmpty();
5259
}
5360

61+
@Test
62+
void 오단계() {
63+
try (Connection connection = jdbcTemplate.getDataSource().getConnection()) {
64+
assertThat(connection).isNotNull();
65+
assertThat(connection.getCatalog()).isEqualTo("DATABASE");
66+
assertThat(connection.getMetaData().getTables(null, null, "RESERVATION", null).next()).isTrue();
67+
} catch (SQLException e) {
68+
throw new RuntimeException(e);
69+
}
70+
}
71+
72+
@Test
73+
void 육단계() {
74+
jdbcTemplate.update("INSERT INTO reservation (name, date, time) VALUES (?, ?, ?)", "브라운", "2023-08-05", "15:40");
75+
76+
List<Reservation> reservations = RestAssured.given().log().all()
77+
.when().get("/reservations")
78+
.then().log().all()
79+
.statusCode(200).extract()
80+
.jsonPath().getList(".", Reservation.class);
81+
82+
Integer count = jdbcTemplate.queryForObject("SELECT count(1) from reservation", Integer.class);
83+
84+
assertThat(reservations.size()).isEqualTo(count);
85+
}
5486
}

0 commit comments

Comments
 (0)