Spring/Toby의 스프링3 따라하기
Spring Jdbc로 mysql datetime 타입의 데이터 넣기
KyeongRok Kim
2021. 11. 14. 17:12
결론부터 이야기 하자면 Jdbc로 MySql의 Datetime타입에 값을 넣을 때 LocalDateTime을 이용하고 db에 insert할 때는 Timestamp로 바꿔서 합니다.
위 table의 created_at이 MySql datetime 타입 입니다.
public class CarModel {
private int id;
private String name;
private int level;
private LocalDateTime createdAt;
}
Model은 LocalDateTime으로 했습니다.
public void add(CarModel carModel) throws SQLException {
this.jdbcContext.workWithStatementStrategy(new StatementStrategy() {
@Override
public PreparedStatement makePreparedStatement(Connection c) throws SQLException {
PreparedStatement ps = c.prepareStatement("insert into car_model(id, name, level, created_at, updated_at) values(?, ?, ?, ?, ?)");
ps.setInt(1, carModel.getId());
ps.setString(2, carModel.getName());
ps.setInt(3, carModel.getLevel());
ps.setTimestamp(4, Timestamp.valueOf(carModel.getCreatedAt()));
ps.setTimestamp(5, Timestamp.valueOf(carModel.getCreatedAt())); // created at과 같음
return ps;
}
});
}
그리고 PreparedStatement 만들때는 .setTimestamp()를 이용해 timestamp로 변경 해서 넣습니다.
데이터 매핑
MySql은 아니고 Postgres지만 Postgres의 timestamp를 Java의 LocalDateTime으로 매핑하는 방법 입니다.
private RowMapper<CustomerServiceRecord> rowMapper = new RowMapper<CustomerServiceRecord>() {
@Override
public CustomerServiceRecord mapRow(ResultSet rs, int rowNum) throws SQLException {
CustomerServiceRecord customerServiceRecord = new CustomerServiceRecord();
customerServiceRecord.setId(rs.getLong("id"));
customerServiceRecord.setCarModelId(rs.getInt("car_model_id"));
customerServiceRecord.setCsStartDate(rs.getTimestamp("cs_start_date").toLocalDateTime());
customerServiceRecord.setContents(rs.getString("contents"));
return customerServiceRecord;
}
};
.toLocalDateTime()을 씁니다.
728x90