본문 바로가기

Spring/Spring JDBC

[Spring] [SpringJDBC] insert시, key값 알아오기

keyholder를 사용하면, auto-generated된 key값을 가져올 수 있다.

    private NamedParameterJdbcTemplate jdbcTemplate;

    // 1. reservation_info 만들어서 insert
    // 이때, pk값 알아와야한다
    public int insertReservationInfo(ReservationInfo reservationInfo){
        Map<String, Object> params = new HashMap<>();
        params.put("product_id", reservationInfo.getProductId());
        params.put("display_info_id", reservationInfo.getDisplayInfoId());
        params.put("user_id", reservationInfo.getUserId());
        params.put("reservation_date", reservationInfo.getReservationDate());
        params.put("cancel_flag", reservationInfo.getCancelFlag());
        params.put("create_date",new Date());
        params.put("modify_date",new Date());

        KeyHolder reservationInfoKeyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(INSERT_RESERVATION_INFO, new MapSqlParameterSource(params), reservationInfoKeyHolder, new String[]{"id"});
        return reservationInfoKeyHolder.getKey().intValue();
    }