[Mybatis] 타임존 처리 개념과 예제

타임존 처리는 다양한 지역의 시간대를 관리하고 처리하는 과정을 의미합니다. 애플리케이션에서 시간 정보를 저장하거나 표시할 때 타임존을 고려하여 정확한 시간을 보여주는 것이 중요합니다. MyBatis는 타임존 처리를 위한 TypeHandlerResultSetHandler를 사용하여 데이터베이스의 시간 정보를 자바 객체로 변환하고 처리할 수 있습니다.

아래는 타임존 처리의 개념과 예제입니다.

예제: 타임존 처리를 위한 TypeHandler

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import java.sql.*;
import java.time.ZoneId;
import java.time.ZonedDateTime;

@MappedTypes(ZonedDateTime.class)
public class ZonedDateTimeTypeHandler extends BaseTypeHandler<ZonedDateTime> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, ZonedDateTime zonedDateTime, JdbcType jdbcType) throws SQLException {
        preparedStatement.setTimestamp(i, Timestamp.from(zonedDateTime.toInstant()));
    }

    @Override
    public ZonedDateTime getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        Timestamp timestamp = resultSet.getTimestamp(columnName);
        if (timestamp != null) {
            return ZonedDateTime.ofInstant(timestamp.toInstant(), ZoneId.systemDefault());
        }
        return null;
    }

    @Override
    public ZonedDateTime getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        Timestamp timestamp = resultSet.getTimestamp(columnIndex);
        if (timestamp != null) {
            return ZonedDateTime.ofInstant(timestamp.toInstant(), ZoneId.systemDefault());
        }
        return null;
    }

    @Override
    public ZonedDateTime getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        Timestamp timestamp = callableStatement.getTimestamp(columnIndex);
        if (timestamp != null) {
            return ZonedDateTime.ofInstant(timestamp.toInstant(), ZoneId.systemDefault());
        }
        return null;
    }
}` 

위의 예제에서는 ZonedDateTime을 처리하기 위한 TypeHandler를 구현하고 있습니다. setNonNullParameter 메서드에서는 ZonedDateTimeTimestamp로 변환하여 데이터베이스에 저장하고, getNullableResult 메서드에서는 TimestampZonedDateTime으로 변환하여 결과로 반환합니다.

매퍼 XML 파일:

BookMapper.xml:

<typeHandlers>
  <typeHandler handler="com.example.ZonedDateTimeTypeHandler"/>
</typeHandlers>

<select id="selectBook" resultType="Book">
  SELECT * FROM books WHERE id = #{id}
</select>` 

위의 예제에서는 ZonedDateTimeTypeHandler를 등록하고, 매퍼 XML 파일에서 해당 TypeHandler를 사용하여 타임존 처리를 적용하고 있습니다.

이렇게 하면 데이터베이스에서 시간 정보를 가져올 때 자동으로 타임존이 고려된 ZonedDateTime 객체로 변환하여 사용할 수 있습니다.