카테고리 보관물: Apache Project/Ibatis/Mybatis

mybatis의 SqlSession에서 commit();close(); vs close(); 어떤걸 해야 하나요?

코드를 보다보니, 아래와 같은 코드가 있어서 확인해 봤습니다.. ^^;;

try {

session = createSqlSession();
// db 처리.. .
} finally {
// db 세션 종료
if(session != null) {
session.commit();
session.close();
}

}

그래서, http://code.google.com/p/mybatis/source/browse/tags/mybatis-3.0.4/src/main/java/org/apache/ibatis/session/defaults/DefaultSqlSession.java 의 session코드에서 commit메쏘드와 close메쏘드를 살펴 봤습니다..

* commit() : 오버로딩하는 두개의 메쏘드가 있네요.. ^^

  public void commit() {
    commit(false);
  }

  public void commit(boolean force) {
    try {
      executor.commit(isCommitOrRollbackRequired(force));
      dirty = false;
    } catch (Exception e) {
      throw ExceptionFactory.wrapException(“Error committing transaction.  Cause: ” + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

* close()

  public void close() {
    try {
      executor.close(isCommitOrRollbackRequired(false));
      dirty = false;
    } catch (Exception e) {
      throw ExceptionFactory.wrapException(“Error closing transaction.  Cause: ” + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

위 코드를 보시면, commit();close(); 코드와 close();가 있습니다..
코드를 따라가다 보면, 결국, http://code.google.com/p/mybatis/source/browse/tags/mybatis-3.0.4/src/main/java/org/apache/ibatis/transaction/jdbc/JdbcTransaction.java 에서, 아래와 같은 코드를 볼 수 있습니다.


  public void commit() throws SQLException {
    if (!connection.getAutoCommit()) {
      connection.commit();
    }
  }


  public void close() throws SQLException {
    resetAutoCommit();
    connection.close();
  }


  protected void resetAutoCommit() {
    try {
      if (!connection.getAutoCommit()) {
        // for compatibility we always use true, as some drivers don’t like being left in “false” mode.
        connection.setAutoCommit(true);
      }
    } catch (SQLException e) {
      // Only a very poorly implemented driver would fail here,
      // and there’s not much we can do about that.
      throw new TransactionException(“Error configuring AutoCommit.  ” +
          “Your driver may not support getAutoCommit() or setAutoCommit(). Cause: ” + e, e);
    }
  }

흠, 따라서 commit();close();와 close();가 동일할 거라는 심증만 가지게 되네요..^^;;
commit();close();해야 하나요?? close();만 하면 되까요?? ㅋㅋ

ibatis/mybatis에서 oracle connection detect 하기..

오라클 db conn detect할 수 있는 옵션입니다.
<dataSource type=”POOLED”> 안에 아래의 property를 넣어주면 됩니다..

<property name=”poolPingEnabled” value=”true”/>
<property name=”poolPingQuery” value=”select 1 from dual”/>

아, 좋네요.. ^^

Mapped Statements collection does not contain value xxx.xxx.xxx.xxx 에러

ibatis나 mybatis에서 XML을 사용해서 쿼리문을 작성해서 쿼리를 실행한 경우, 아래와 같은 에러를 볼 수 있다.

java.lang.IllegalArgumentException: Mapped Statements collection does not contain value xxx.xxx.xxx.xxx

이 에러가 나는 겨우, 알면 쉽지만 모르는 경우 찾는게 쉽지 않았다.
이 에러는 매퍼(Mapper)에 선언한 메서드 이름과 매퍼 파일(XML)에 기술한 쿼리문(Select, Insert 등)의 이름이 같지 않아서 발생하게 된다.

위 에러가 발생시키는 예는 다음과 같다.

ex) 인터페이스 이름

public String print(String x) throws Exception;

ex) mapper.xml


<select id="prints" statementType="CALLABLE" parameterType="String" resultType="String">
        .........................
</select>

mssql 2008 jdbc 세팅하기..

ibatis를 사용해서 mssql 2008에 연결하는 설정이다. 예전의 mssql 서버의 default port는 1443 이었는데, 4147로 바뀌었나 보다. 이 내용은, Sql Server Configuration Manager –> SQL Server 네트워크 구성 –> TCP/IP 사용의 속성창을 보면 확인 할 수 있다. IPALL의 TCP 동적포트로 연결 포트를 설정하면 된다.

<sqlMapConfig>
<transactionManager type=”JDBC” commitRequired=”false”>
<dataSource type=”SIMPLE”>
<property name=”JDBC.Driver” value=”com.microsoft.sqlserver.jdbc.SQLServerDriver”/>
<property name=”JDBC.ConnectionURL” value=”jdbc:sqlserver://computer-name\SQLEXPRESS:4147;databaseName=testdb;integratedSecurity=true;”/>
<property name=”JDBC.Username” value=”id”/>
<property name=”JDBC.Password” value=”password”/>
<property name=”Pool.MaximumIdleConnections” value=”5″/>
<property name=”Pool.MaximumCheckoutTime” value=”120000″/>
<property name=”Pool.TimeToWait” value=”500″/>
</dataSource>
</transactionManager>
<sqlMap resource=”article.xml”/>
</sqlMapConfig>

그리고, 혹시 경고: Failed to load the sqljdbc_auth.dll 메세지를 보게되면,플랫폼에 맞는 sqljdbc_auth.dll를 windows\system32폴더에 복사하면 된다.

Apache iBatis에서 다중 데이터 베이스 사용 방법

Apache iBatis에서 다중 데이터 베이스에 접속하는 방법이다.

1. database.properties

driver=oracle.jdbc.driver.OracleDriver
jdbc.url1=jdbc:oracle:thin:@mimuluserdb:1521:mimuluser
username1=mimuluser
password1=mimuluser
jdbc.url2=jdbc:oracle:thin:@pepsiuserdb:1521:pepsiuser
username2=pepsiuser
password2=pepsiuser

2. sqlmap1.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<properties resource="com/mimul/dwr/app/
resource/database.properties"/>
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxRequests="40"
maxSessions="20"
maxTransactions="5"
useStatementNamespaces="false"
/>
<transactionManager type="JDBC">
<dataSource type="DBCP">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${jdbc.url1}"/>
<property name="username" value="${username1}"/>
<property name="password" value="${password1}"/>
<!-- OPTIONAL PROPERTIES BELOW -->
<property name="initialSize" value="5"/>
<property name="maxActive" value="30"/>
<property name="maxIdle" value="20"/>
<property name="maxWait" value="60000"/>
<property name="poolPreparedStatements" value="true"/>
<property name="validationQuery" value="select 0 from dual"/>
<property name="testOnBorrow" value="true"/>
<property name="maximumActiveConnections" value="10"/>
<property name="maximumIdleConnections" value="5"/>
<property name="maximumWait" value="60000"/>
<property name="logAbandoned" value="false"/>
<property name="removeAbandoned" value="false"/>
<property name="removeAbandonedTimeout" value="50000"/>
</dataSource>
</transactionManager>
<sqlMap resource="com/mimul/dwr/app/sql/Mimul.xml"/>
</sqlMapConfig>

3. sqlmap2.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<properties resource="com/mimul/dwr/app/resource/database.properties"/>
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxRequests="40"
maxSessions="20"
maxTransactions="5"
useStatementNamespaces="false"
/>
<transactionManager type="JDBC">
<dataSource type="DBCP">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${jdbc.url2}"/>
<property name="username" value="${username2}"/>
<property name="password" value="${password2}"/>
<!-- OPTIONAL PROPERTIES BELOW -->
<property name="initialSize" value="5"/>
<property name="maxActive" value="30"/>
<property name="maxIdle" value="20"/>
<property name="maxWait" value="60000"/>
<property name="poolPreparedStatements" value="true"/>
<property name="validationQuery" value="select 0 from dual"/>
<property name="testOnBorrow" value="true"/>
<property name="maximumActiveConnections" value="10"/>
<property name="maximumIdleConnections" value="5"/>
<property name="maximumWait" value="60000"/>
<property name="logAbandoned" value="false"/>
<property name="removeAbandoned" value="false"/>
<property name="removeAbandonedTimeout" value="50000"/>
</dataSource>
</transactionManager>
<sqlMap resource="com/mimul/dwr/app/sql/Pepsi.xml"/>
</sqlMapConfig>

4. SqlCondig.java

import java.io.File;
import java.io.Reader;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.jaeminara.common.log.LogPool;
public class SqlConfig {
  private static SqlMapClient sqlMap1 = null;
  private static SqlMapClient sqlMap2 = null;
  private static SqlConfig instance_ = null;

  private SqlConfig() throws Exception {
    Reader reader = null;
    String resource = null;
    try {
      if (sqlMap == null) {
        resource = "sqlmap1.xml";
        reader = Resources.getResourceAsReader(resource);
        sqlMap1 = SqlMapClientBuilder.buildSqlMapClient(reader);
        resource = "sqlmap2.xml";
        reader = Resources.getResourceAsReader(resource);
        sqlMap2 = SqlMapClientBuilder.buildSqlMapClient(reader);
        reader.close();
      }
    } catch (Exception e) {
      System.out.println(e);
      throw e;
    } finally {
      if (reader != null)
      reader.close();
      reader = null;
      rsc = null;
    }
  }

  public static SqlConfig instance() {
    try {
      if (instance_ == null) {
        synchronized (SqlConfig.class) {
          if (instance_ == null)
            instance_ = new SqlConfig();
        }
      }
    } catch (Exception e) {
      System.out.println(e);
    }
    return instance_;
  }

  /**
  * Return SqlMapClient for SDP schema
  *
  * @return
  */
  public static SqlMapClient getSqlMap1Instance() {
    return sqlMap1;
  }

  /**
  * Return SqlMapClient for SDP schema
  *
  * @return
  */
  public static SqlMapClient getSqlMap2Instance() {
    return sqlMap2;
  }
}

* Reference
http://mimul.com/pebble/default/2008/02/24/1203779580000.html