-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathTimeDAO.java
More file actions
68 lines (58 loc) · 1.75 KB
/
TimeDAO.java
File metadata and controls
68 lines (58 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package roomescape.DAO;
import java.sql.PreparedStatement;
import java.util.List;
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.Domain.Time;
@Repository
public class TimeDAO {
private final JdbcTemplate jdbcTemplate;
public TimeDAO(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<Time> findAllTimes() {
String sql = "SELECT * FROM time";
return jdbcTemplate.query(
sql,
timeRowMapper
);
}
public Time findTimeByID(Long id) {
String sql = "SELECT * FROM time WHERE id = ?";
return jdbcTemplate.queryForObject(
sql,
timeRowMapper,
id
);
}
public List<Time> findTimesByID(Long id) {
String sql = "SELECT * FROM time WHERE id = ?";
return jdbcTemplate.query(
sql,
timeRowMapper,
id);
}
public Long insertWithKeyHolder(Time time) {
KeyHolder keyHolder = new GeneratedKeyHolder();
String sql = "INSERT INTO time (time) VALUES (?)";
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, new String[] {"id"});
ps.setString(1, time.getTime());
return ps;
}, keyHolder);
return keyHolder.getKey().longValue();
}
public int delete(Long id) {
String sql = "delete from time where id = ?";
return jdbcTemplate.update(sql, Long.valueOf(id));
}
private final RowMapper<Time> timeRowMapper = (resultSet, rowNum) -> {
return new Time(
resultSet.getLong("id"),
resultSet.getString("time")
);
};
}