Bibi's DevLog ๐ค๐
[Java Spring] DB์ ๋ ์ง ์ ์ฅํ๊ธฐ, JSON์ผ๋ก ๋ ์ง ๋ฐ๊ธฐ ๋ณธ๋ฌธ
[Java Spring] DB์ ๋ ์ง ์ ์ฅํ๊ธฐ, JSON์ผ๋ก ๋ ์ง ๋ฐ๊ธฐ
๋น๋น bibi 2021. 5. 28. 22:17[Java] DB์ LocalDate์๋ฃํ ์ ์ฅํ๊ณ ๊บผ๋ด๊ธฐ
DB ํ ์ด๋ธ
๋ ์ง ์๋ฃํ์ธ Date๋ก ์ ์ฅํ๋ค
create table `booking`
(
`id` int not null auto_increment,
`room_id` int not null,
`user_id` int not null,
`check_in` date not null,
`check_out` date not null,
`number_of_people` int not null,
`total_price` int not null,
primary key (`id`),
foreign key (`room_id`) references `room` (`id`),
foreign key (`user_id`) references `user` (`id`)
);
Java ์ํฐํฐ
๋ ์ง ์๋ฃํ์ธ LocalDate๋ก ์ ์ฅํ๋ค
public class Booking {
@Id
private Long id;
private Long roomId;
private Long userId;
private LocalDate checkIn;
private LocalDate checkOut;
private int numberOfPeople;
private int totalPrice;
//...
}
๊บผ๋ด๊ธฐ
(JdbcTemplate ๊ธฐ์ค)
resultSet.getDate("์ด๋ฆ").toLocalDate()
resultSet.getDate()์ ๋ฆฌํด๊ฐ์ java.util.Date
๊ฐ ์๋ java.sql.Date
์ด๋ค. ๊ทธ๋์ toLocalDate()๋ฅผ ์ฌ์ฉํด LocalDate๋ก ๋ณํํ๋ ๊ณผ์ ์ด ํ ๋ฒ ๋ ํ์ํ ๊ฒ.
@Override
public List<Booking> findAll() {
String sql = "select `id`, `room_id`, `user_id`, `check_in`, `check_out`, `number_of_people`, `total_price` from booking";
return jdbcTemplate.query(sql, bookingRowMapper());
}
private RowMapper<Booking> bookingRowMapper() {
return (resultSet, rowNum) -> {
Booking booking = new Booking(resultSet.getLong("id"), resultSet.getLong("room_id"), resultSet.getLong("user_id"),
resultSet.getDate("check_in").toLocalDate(), resultSet.getDate("check_out").toLocalDate(), resultSet.getInt("number_of_people"),
resultSet.getInt("total_price"));
return booking;
};
}
์ ์ฅํ๊ธฐ
ํน๋ณํ ๋ณํ์ ํ์ ์์. JdbcTemplate.update()
๋ฅผ ์ฌ์ฉํ๋ค.
public void insert(Booking booking) {
String sql = "insert into `booking` (`room_id`, `user_id`, `check_in`, `check_out`, `number_of_people`, `total_price`) values (?, ?, ?, ?, ?, ?)";
jdbcTemplate.update(sql, booking.getRoomId(), booking.getUserId(), booking.getCheckIn(),
booking.getCheckOut(), booking.getNumberOfPeople(), booking.getTotalPrice());
}
[Spring] JSON Response๋ก ๋ ์ง ์๋ฃํ ๋ฐ๊ธฐ - @DateTimeFormat
์ถ์ฒ๐โโ๏ธ
https://perfectacle.github.io/2018/01/15/jackson-local-date-time-deserialize/
์๋ฐ์ LocalDate์ ๊ฐ์ ๋ ์ง ์๋ฃํ์ JSON์ผ๋ก ๋ฐ์ผ๋ ค ํ๋ฉด ์๋์ ๊ฐ์ TypeMisMatchException์ด ๋ฐ์ํ๋ค.
{
...
"exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
"message": Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate';
...
}
์ด๋ ํ๋ผ๋ฏธํฐ๋ก ๋๊ธด ๊ฐ์ String์ผ๋ก ์ธ์ํ๊ธฐ ๋๋ฌธ์ด๋ค.
ํด๊ฒฐ์ฑ
: @DateTimeFormat(pattern = "")
๋๋ @JsonFormat(pattern = "")
์ด๋
ธํ
์ด์
์ ๋ ์ง ์๋ฃํ ํ๋ผ๋ฏธํฐ ๋๋ ํ๋์ ๋ฌ์ ์ค๋ค.
@RestController
public class Controller {
@GetMapping("/")
public DateType get(@RequestParam
@DateTimeFormat(pattern = "yyyy-MM-dd")
LocalDate date,
@RequestParam
@DateTimeFormat(pattern = "kk:mm:ss")
LocalTime time,
@RequestParam
@DateTimeFormat(pattern = "yyyy-MM-dd kk:mm:ss")
LocalDateTime dateTime) {}
}