|
| 1 | +package roomescape.controller; |
| 2 | + |
| 3 | +import org.springframework.http.HttpStatus; |
| 4 | +import org.springframework.http.ResponseEntity; |
| 5 | +import org.springframework.jdbc.core.JdbcTemplate; |
| 6 | +import org.springframework.jdbc.support.GeneratedKeyHolder; |
| 7 | +import org.springframework.jdbc.support.KeyHolder; |
| 8 | +import org.springframework.stereotype.Controller; |
| 9 | +import org.springframework.web.bind.annotation.PostMapping; |
| 10 | +import org.springframework.web.bind.annotation.RequestBody; |
| 11 | +import roomescape.model.time.Time; |
| 12 | +import roomescape.model.time.TimeRequest; |
| 13 | + |
| 14 | +import java.sql.PreparedStatement; |
| 15 | + |
| 16 | +@Controller |
| 17 | +public class TimeController { |
| 18 | + private final JdbcTemplate jdbcTemplate; |
| 19 | + |
| 20 | + public TimeController(JdbcTemplate jdbcTemplate) { |
| 21 | + this.jdbcTemplate = jdbcTemplate; |
| 22 | + } |
| 23 | + |
| 24 | + @PostMapping("/times") |
| 25 | + public ResponseEntity<Time> createTimes(@RequestBody TimeRequest timeRequest) { |
| 26 | + Time time = new Time(timeRequest.getTime()); |
| 27 | + |
| 28 | + String sql = "INSERT INTO time (time) VALUES (?)"; |
| 29 | + KeyHolder keyHolder = new GeneratedKeyHolder(); |
| 30 | + |
| 31 | + jdbcTemplate.update(connection -> { |
| 32 | + PreparedStatement ps = connection.prepareStatement(sql, new String[]{"id"}); |
| 33 | + ps.setString(1, time.getTime()); |
| 34 | + return ps; |
| 35 | + }, keyHolder); |
| 36 | + |
| 37 | + Number generatedId = keyHolder.getKey(); |
| 38 | + if (generatedId != null) { |
| 39 | + time.setId(generatedId.longValue()); |
| 40 | + } |
| 41 | + return ResponseEntity.status(HttpStatus.CREATED) |
| 42 | + .header("Location", "/times/" + time.getId()) |
| 43 | + .body(time); |
| 44 | + } |
| 45 | +} |
0 commit comments