[Mybatis] 커스텀 엔티티 타입 생성(Custom Entity Type) 예제

MyBatis에서 커스텀 엔티티 타입을 생성하려면 TypeHandler 인터페이스를 구현해야 합니다. 커스텀 엔티티 타입은 데이터베이스에서 가져온 데이터를 원하는 Java 객체로 변환하거나 그 반대로 Java 객체를 데이터베이스 컬럼 값으로 변환하는 데 사용됩니다. 아래는 커스텀 엔티티 타입을 생성하는 예제입니다.

예제: 커스텀 엔티티 타입 생성

  1. 커스텀 엔티티 클래스 작성:

    먼저 커스텀 엔티티 클래스를 작성합니다. 이 클래스는 데이터베이스 컬럼과 매핑됩니다.

public class CustomType {
    private String value;

    public CustomType(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    // 기타 메서드
}` 
  1. TypeHandler 구현:

    TypeHandler 인터페이스를 구현하여 데이터베이스에서 커스텀 엔티티로의 매핑 및 역매핑 로직을 정의합니다.

public class CustomTypeHandler implements TypeHandler<CustomType> {

    @Override
    public void setParameter(PreparedStatement ps, int i, CustomType parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.getValue());
    }

    @Override
    public CustomType getResult(ResultSet rs, String columnName) throws SQLException {
        return new CustomType(rs.getString(columnName));
    }

    @Override
    public CustomType getResult(ResultSet rs, int columnIndex) throws SQLException {
        return new CustomType(rs.getString(columnIndex));
    }

    @Override
    public CustomType getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return new CustomType(cs.getString(columnIndex));
    }
}` 
  1. MyBatis 설정 파일에 TypeHandler 등록:

    커스텀 TypeHandler를 MyBatis 설정 파일에 등록합니다.

<!-- mybatis-config.xml -->
<configuration>
    <!-- 기타 설정 -->
    <typeHandlers>
        <typeHandler handler="com.example.CustomTypeHandler" />
    </typeHandlers>
</configuration>` 
  1. 매퍼 XML 파일에서 커스텀 엔티티 타입 사용:

    매퍼 XML 파일에서 커스텀 엔티티 타입을 사용하고 매핑합니다.

<!-- OrderMapper.xml -->
<mapper namespace="com.example.OrderMapper">
    
    <resultMap id="orderResultMap" type="com.example.Order">
        <id property="orderId" column="order_id" />
        <result property="customType" column="custom_type_column" javaType="com.example.CustomType" />
    </resultMap>

    <select id="getOrders" resultMap="orderResultMap">
        SELECT order_id, custom_type_column FROM orders
    </select>
</mapper>` 
  1. Java 객체에서 사용:

    Java 코드에서 커스텀 엔티티 타입을 사용하여 데이터베이스와 상호 작용합니다.

public class Order {
    private int orderId;
    private CustomType customType;

    // Getter와 Setter 메서드
}` 

커스텀 엔티티 타입을 생성하고 MyBatis에 통합하는 것으로, 데이터베이스 컬럼과 커스텀 Java 객체 간의 매핑을 제어할 수 있습니다. TypeHandler를 사용하면 원하는 데이터 유형을 처리하고 변환할 수 있으므로 MyBatis를 더 유연하게 사용할 수 있습니다.