본문 바로가기

뇌/Mybatis

[Mybatis] 쿼리 예쁘게 출력, DB에 저장하기

1. maven dependency 추가

1
2
3
4
5
<dependency>
    <groupId>org.lazyluke</groupId>
    <artifactId>log4jdbc-remix</artifactId>
    <version>0.2.7</version>
</dependency>
cs


2. dataSource 설정

: dataSource를 net.sf.log4jdbc.Log4jdbcProxyDataSource클래스를 사용한 빈으로 교체

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    <bean id="dataSourceSpied" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE"/>
        <property name="username" value="아이디"/>
        <property name="password" value="비밀번호"/>
    </bean>
     
    <bean id="dataSource" class="net.sf.log4jdbc.Log4jdbcProxyDataSource">
        <constructor-arg ref="dataSourceSpied" />
        <property name="logFormatter">
            <bean class="net.sf.log4jdbc.tools.Log4JdbcCustomFormatter">
                <property name="loggingType" value="MULTI_LINE" />
                <property name="sqlPrefix" value="SQL         :  "/>
            </bean>
        </property>
    </bean>
cs


3. log4j 설정

: result는 ERROR 레벨에서만 확인하도록 수정

1
2
3
4
5
6
7
8
9
10
11
    <!-- Query Loggers -->
    <logger name="jdbc.sqlonly" additivity="false">  
        <level value="INFO"/>
        <appender-ref ref="console-infolog"/>  
    </logger>
     
    <logger name="jdbc.resultsettable" additivity="false">  
        <level value="ERROR"/>
        <appender-ref ref="console"/>  
    </logger>
 
cs


4. mybatis에서 쿼리 추출

mybatis로 쿼리 template 추출 후 ?를 parameter로 replace하여 사용한 쿼리 완성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public String getSql(String id, Map<String, Object> params){
        System.out.println("######## 쿼리시작");
        BoundSql bSql = sqlSession.getConfiguration().getMappedStatement(id).getBoundSql(params);
//        System.out.println("사용된 sql : "+sql.getSql());
        String sql = bSql.getSql();
        Object pObj = bSql.getParameterObject();
        if(pObj != null) {
            List<ParameterMapping> paramMapping = bSql.getParameterMappings();
            for (ParameterMapping mapping : paramMapping) {
                String propValue = mapping.getProperty();
                sql = sql.replaceFirst("\\?""'"+params.get(propValue).toString()+"'");
            }
        }
        System.out.println(sql);
        System.out.println("######## 쿼리끝");
        
        return sql;
    }
cs


' > Mybatis' 카테고리의 다른 글

[Mybatis] resultMap 예제, 사용 에러  (4) 2016.04.03