티스토리 뷰

 

결론부터 이야기 하자면 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()을 씁니다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
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
글 보관함