Antop
Brain to Blog
Antop
전체 방문자
936,436
오늘
3
어제
27
  • 분류 전체보기 (167)
    • Ubuntu Developer (0)
    • Mini Project (12)
    • Request Sample (1)
    • Study (5)
      • Vue.js (2)
      • Hadoop (3)
    • Java+ (23)
      • Trouble Shooting (5)
      • Example (8)
    • Framework (22)
      • Struts (3)
      • Spring (3)
      • Spring OSGi (2)
      • Spring Security (3)
      • Hibernate (9)
      • Mybatis (1)
    • Android (1)
    • Oracle Solution (40)
      • Tutorial for Oracle Coheren.. (1)
      • PO Processing (17)
      • BPM 11g Foundation Training (11)
      • Oracle Service Bus 11g Hand.. (5)
      • BPEL (3)
      • Trouble Shooting (2)
    • JavaScript (5)
      • jQuery (2)
      • Ext JS (1)
    • Tools (12)
      • Eclipse (11)
      • Maven (1)
    • Database (6)
      • Oracle (3)
      • MySQL (2)
    • Server (30)
      • Ubuntu (16)
      • WebLogic (7)
      • VMware ESXi (6)
    • Etc (9)
      • Scrap (4)
      • Link (1)
      • Game (2)

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

  • Spring + @Lazy
    2019.08.05
    Spring + @Lazy
  • Mybatis Interceptor + RowBounds ⋯
    2017.12.12
  • org.springframework.dao.EmptyRes⋯
    2010.10.10
  • Spring Message Source from Datab⋯
    2013.03.03
    Spring Message Source from Datab⋯
  • Mockito.thenThrow() 주의사항!
    2021.09.25

태그

  • JDBC
  • JavaScript
  • BPEL
  • xml
  • ubuntu
  • mybatis
  • Java
  • SOA
  • API
  • jQuery
  • LAB
  • esxi
  • Struts
  • oracle
  • maven
  • Weblogic
  • BPM
  • Ajax
  • hibernate
  • ORM
  • JSP
  • Eclipse
  • Spring
  • MySQL
  • VMware
  • EJB
  • 하이버네이트
  • osb
  • JSON
  • extjs

최근 댓글

  • 소스를 오픈 해주셔서 감사합니다. 출처 남기고 긁어가겠습⋯
    헤르메스의날개
  • 드라이버에 의존하는것보다 확실하게 하는게 좋긴 하겠네요
    망고스틴
  • 비슷한걸 개발하면서 어떻게 해야되나 jsp단에서 jstl로⋯
    홍마초
  • 잘 보고 갑니다...
    딸랑딸랑
  • 잘 보고 갑니다...
    이웃사촌

최근 글

  • Mockito.thenThrow() 주의사항!
    2021.09.25
  • Spring + @Lazy
    2019.08.05
    Spring + @Lazy
  • [Kotlin + Spring] Maven configur⋯
    2019.05.26
  • Installation Vue.js (Eclipse)
    2018.05.24
    Installation Vue.js (Eclipse)
  • Installation Vue.js (WebStorm + ⋯
    2018.05.21
    Installation Vue.js (WebStorm + ⋯

티스토리

hELLO · Designed By 정상우.
Antop

Brain to Blog

Mybatis Type Handler
Java+/Example

Mybatis Type Handler

2012. 9. 30. 12:49
반응형

마이바티스를 이용하여 자바 객체와 데이터베이스 테이블을 매핑할 때 서로 완전히 다른 타입의 것들을 사용할 때가 있습니다.

 

그 예로 대표적인 예가 자바의 Boolean 과 데이터베이스의 플래그 문자입니다.

 

 

오라클 같은경우 boolean 타입이 없기 때문에 보통 CHAR(1) 잡고 Y/N 값을 많이 사용합니다.

 

다른 경우는 1 or 0 을 사용하여 참/거짓, 사용/미사용, 차단/허용 같은 on/off 플래그 값을 사용합니다.

 

값

자바 

데이터베이스 

boolean

CHAR(1)

INTEGER  

참 / 사용

true

Y

 1 

거짓 / 미사용

false

N

 0 

 

org.apache.ibatis.type.TypeHandler 인터페이스를 이용해서 서로 다른 타입을 연결할 수 있습니다.

 

package com.tistory.antop.mybatis.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.log4j.Logger;

public class StringYnTypeHandler implements TypeHandler<Boolean> {

    private Logger logger = Logger.getLogger(getClass());

    public Boolean getResult(ResultSet rs, String columnName) throws SQLException {
        String s = rs.getString(columnName);

        return parseBoolean(s);
    }

    public Boolean getResult(ResultSet rs, int columnIndex) throws SQLException {
        String s = rs.getString(columnIndex);

        return parseBoolean(s);
    }

    public Boolean getResult(CallableStatement cs, int columnIndex)
        throws SQLException {
        String s = cs.getString(columnIndex);

        return parseBoolean(s);
    }

    public void setParameter(PreparedStatement ps, int i, Boolean bool,
        JdbcType jdbcType) throws SQLException {

        ps.setString(i, parseString(bool));
    }

    // "Y" or "N" -> true or false
    private boolean parseBoolean(String s) {
        boolean bool = false;

        if (s == null) {
            return false;
        }

        s = s.trim().toUpperCase();

        if (s.length() == 0) {
            return false;
        }

        // allow "Y" or "N"
        if ("Y".equals(s) == false && "N".equals(s) == false) {
            throw new PersistenceException("value must be \"Y\" or \"N\".");
        }

        bool = "Y".equals(s);

        if (logger.isDebugEnabled()) {
            logger.debug("\"" + s + "\" -> " + bool);
        }

        return bool;
    }

    // true or false -> "Y" or "N"
    private String parseString(Boolean bool) {
        String s = (bool != null && bool == true) ? "Y" : "N";

        if (logger.isDebugEnabled()) {
            logger.debug(bool + " -> " + "\"" + s + "\"");
        }

        return s;
    }
}

 

이 클래스를 이용하면 자바에서는 boolean 타입을 사용하면 데이터베이스에서는 Y or N 값이 들어가게 됩니다.

 

mybatis.typehandler.zip

 

위 샘플은 메이븐 프로젝트 구조입니다.

 

샘플을 만드는 도중에 sqlite3 는 이상한게 TIMESTAMP 타입을 java.util.Date 클래스와 매핑 하면 들어갈 때는 그대로 들어가는데 조회할 때는 java.util.String 이 나오는군요....

 

그래서 TIMESTAMP 에 대한 핸들러 하나 더 만들었습니다.

 

테스트는 com.tistory.antop.mybatis.TypeHandlerTest 클래스 입니다. JUnit 입니다.

 

실행시 Run Configurations 중 VM 옵션에 이래와 같이 "-Dlog4j.configuration=config/properties/log4j.properties" 를 추가해 줘야 로그를 볼 수 있습니다.

 

 

 

반응형
저작자표시
  • 카카오스토리
  • 트위터
  • 페이스북

'Java+ > Example' 카테고리의 다른 글

LOGBack Configurator with JMX  (0) 2014.07.20
현지어로 언어명 보여주기  (0) 2014.02.09
2014년 도로명 주소 사용에 따른 우편번호 준비  (2) 2013.12.22
JSTL Custom Tag using Spring Beans  (0) 2013.12.01
Spring Message Source from Database  (1) 2013.03.03
Infinite Routing DataSource  (1) 2013.01.13
Using AUTO_INCREMENT keys  (0) 2011.03.01
    'Java+/Example' 카테고리의 다른 글
    • JSTL Custom Tag using Spring Beans
    • Spring Message Source from Database
    • Infinite Routing DataSource
    • Using AUTO_INCREMENT keys
    mybatis, ORM, Spring, type handler
    Antop
    Antop
    뇌에서 블로그로... antop@naver.com
    댓글쓰기
    Infinite Routing DataSource
    다음 글
    Infinite Routing DataSource
    Using AUTO_INCREMENT keys
    이전 글
    Using AUTO_INCREMENT keys

    티스토리툴바