|
| 1 | +package roomescape.controller; |
| 2 | + |
| 3 | +import org.springframework.http.ResponseEntity; |
| 4 | +import org.springframework.jdbc.core.JdbcTemplate; |
| 5 | +import org.springframework.web.bind.annotation.GetMapping; |
| 6 | +import org.springframework.web.bind.annotation.PostMapping; |
| 7 | +import org.springframework.web.bind.annotation.RequestBody; |
| 8 | +import org.springframework.web.bind.annotation.RestController; |
| 9 | +import roomescape.hello.Customer; |
| 10 | + |
| 11 | +import java.util.List; |
| 12 | + |
| 13 | +@RestController |
| 14 | +public class CustomerController { |
| 15 | + private JdbcTemplate jdbcTemplate; |
| 16 | + |
| 17 | + public CustomerController(JdbcTemplate jdbcTemplate) { |
| 18 | + this.jdbcTemplate = jdbcTemplate; |
| 19 | + } |
| 20 | + |
| 21 | + @PostMapping("/customers") |
| 22 | + public ResponseEntity<Void> save(@RequestBody Customer customer) { |
| 23 | + String sql = "INSERT INTO customers(first_name, last_name) VALUES (?,?)"; |
| 24 | + jdbcTemplate.update(sql, customer.getFirstName(), customer.getLastName()); |
| 25 | + return ResponseEntity.ok().build(); |
| 26 | + } |
| 27 | + |
| 28 | + @GetMapping("/customers") // -> customers 라는 파일(경로)을 만든 적이 없는데 코드가 돌아가긴 함.. |
| 29 | + public ResponseEntity<List<Customer>> list() { |
| 30 | + String sql = "select id, first_name, last_name from customers"; |
| 31 | + List<Customer> customers = jdbcTemplate.query( |
| 32 | + sql, (resultSet, rowNum) -> { |
| 33 | + Customer customer = new Customer( |
| 34 | + resultSet.getLong("id"), |
| 35 | + resultSet.getString("first_name"), |
| 36 | + resultSet.getString("last_name") |
| 37 | + ); |
| 38 | + return customer; |
| 39 | + }); |
| 40 | + return ResponseEntity.ok().body(customers); |
| 41 | + } |
| 42 | +} |
0 commit comments