본문 바로가기

Spring

Spring 과 iBatis 연동


 Spring  iBatis 연동

http://www.mybatis.org/java.html

Past Release 2.3.4

ibatis-2.3.4.726.jar  webcontent lib 에 저장

 

 

      // Default 생성자가 반드시 있어야 .

      // 두번째 글자가 대문자인 경우 못찾는 경우 있음. ex. dName(x)

      // ibatis Mapper Class 만들어 줘야 .

 

** ibatis  sql Mapper framework

SQL 실행한 결과를 담을 있는

Parameter Class ResultSet 결과 값을 저장할 있는 Class 셋팅해 두어야 .

 

 

C:\springsource\ibaits download\ibatis-2.3.4.726\simple_example\com\mydomain\data\account.xml  book.xml (DTD 정의 필요해서 복사해옴)

 

C:\springsource\workspace\day5\src\ibatis\book.xml

<?xml version="1.0" encoding="UTF-8" ?>

 

<!DOCTYPE sqlMap     

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"     

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

 

<!-- namespace 용도는       Mapper 1. Member.xml      Mapper 2. Book.xml     

              각각의 Query 구분하기 위해 id="" 사용하며  id 중복을 피하기 위해 사용함.

 -->

<sqlMap namespace="Book">

 

 <insert id="add" parameterClass="ibatis.Book">

      insert into book(id, name, published, photo)

                values(#id#, #name#, #published#, #photo#)

                <!-- values(?, ?, ?, ?) -->

 </insert>

 

 

</sqlMap>

 

 

SqlMapConfig.xml

 

 

<?xml version="1.0" encoding="UTF-8" ?>

 

<!DOCTYPE sqlMapConfig     

    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"     

    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

 

<sqlMapConfig>

// Content Model : (properties?, settings?, resultObjectFactory?, typeAlias*, typeHandler*,

 transactionManager?, sqlMap*)+

 

  <!-- Configure a built-in transaction manager.  If you're using an

       app server, you probably want to use its transaction manager

       and a managed datasource -->

  <transactionManager type="JDBC" commitRequired="false">

    <dataSource type="SIMPLE">

      <property name="JDBC.Driver" value="org.hsqldb.jdbcDriver"/>

      <property name="JDBC.ConnectionURL" value="jdbc:hsqldb:."/>

      <property name="JDBC.Username" value="sa"/>

      <property name="JDBC.Password" value="sa"/>

    </dataSource>

  </transactionManager>

 

  <!-- List the SQL Map XML files. They can be loaded from the

       classpath, as they are here (com.domain.data...) -->

  <sqlMap resource="com/mydomain/data/Account.xml"/>

  <!-- List more here...

  <sqlMap resource="com/mydomain/data/Order.xml"/>

  <sqlMap resource="com/mydomain/data/Documents.xml"/>

  -->

 

</sqlMapConfig>

 

 

ibatis 는 이곳의 transactionManger 를 사용하지는 않음.

 

WAS 가 구성한 JNDI 에 등록한 걸 쓰겠다 하면 Type 을 변경하면 됨. JNDI

 

<transactionManager type="JDBC" commitRequired="false">

    <dataSource type="SIMPLE">

      <property name="JDBC.Driver" value="oracle.jdbc.OracleDriver"/>

      <property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@127.0.0.1:1521:XE"/>

      <property name="JDBC.Username" value="spring"/>

      <property name="JDBC.Password" value="ms*******"/>

    </dataSource>

  </transactionManager>

 

  <!-- List the SQL Map XML files. They can be loaded from the

       classpath, as they are here (com.domain.data...) -->

      

       <!-- Mapper 파일의 개수만큼 아래처럼 정의 하면 . -->

  <sqlMap resource="ibatis/book.xml/>

 

 

 

 

Mapper

 

SqlMapConfig.xml

 

<ß              SqlMapClientBuilder

 

SqlMapClient         ------------------------------->   Dao           

 

1.     insert (  id  )

2.     update

3.     delete

4.     queryForObject

5.     queryForList

6.      

 

 

 

public class BookDao {

 

      SqlMapClient sqlMapClient;

     

      public BookDao(){

            try{

                  Reader reader = Resources.getResourceAsReader("src/ibatis/SqlMapConfig.xml");

                 

                  sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);

                 

            }catch(IOException e){

                  e.printStackTrace();

            }

      }

     

}

 

 

C:\springsource\ibaits download\ibatis-2.3.4.726\doc\dev-javadoc\index.html

 

Method Summary

 int

delete(java.lang.String id)
          Executes a mapped SQL DELETE statement.

 int

delete(java.lang.String id, java.lang.Object parameterObject)
          Executes a mapped SQL DELETE statement.

 int

executeBatch()
          Executes (flushes) all statements currently batched.

 java.util.List

executeBatchDetailed()
          Executes (flushes) all statements currently batched.

 java.lang.Object

insert(java.lang.String id)
          Executes a mapped SQL INSERT statement.

 java.lang.Object

insert(java.lang.String id, java.lang.Object parameterObject)
          Executes a mapped SQL INSERT statement.

 java.util.List

queryForList(java.lang.String id)
          Executes a mapped SQL SELECT statement that returns data to populate a number of result objects.

 java.util.List

queryForList(java.lang.String id, int skip, int max)
          Executes a mapped SQL SELECT statement that returns data to populate a number of result objects within a certain range.

 java.util.List

queryForList(java.lang.String id, java.lang.Object parameterObject)
          Executes a mapped SQL SELECT statement that returns data to populate a number of result objects.

 java.util.List

queryForList(java.lang.String id, java.lang.Object parameterObject, int skip, int max)
          Executes a mapped SQL SELECT statement that returns data to populate a number of result objects within a certain range.

 java.util.Map

queryForMap(java.lang.String id, java.lang.Object parameterObject, java.lang.String keyProp)
          Executes a mapped SQL SELECT statement that returns data to populate a number of result objects that will be keyed into a Map.

 java.util.Map

queryForMap(java.lang.String id, java.lang.Object parameterObject, java.lang.String keyProp, java.lang.String valueProp)
          Executes a mapped SQL SELECT statement that returns data to populate a number of result objects from which one property will be keyed into a Map.

 java.lang.Object

queryForObject(java.lang.String id)
          Executes a mapped SQL SELECT statement that returns data to populate a single object instance.

 java.lang.Object

queryForObject(java.lang.String id, java.lang.Object parameterObject)
          Executes a mapped SQL SELECT statement that returns data to populate a single object instance.

 java.lang.Object

queryForObject(java.lang.String id, java.lang.Object parameterObject, java.lang.Object resultObject)
          Executes a mapped SQL SELECT statement that returns data to populate the supplied result object.

 PaginatedList

queryForPaginatedList(java.lang.String id, int pageSize)
          Deprecated. All paginated list features have been deprecated

 PaginatedList

queryForPaginatedList(java.lang.String id, java.lang.Object parameterObject, int pageSize)
          Deprecated. All paginated list features have been deprecated

 void

queryWithRowHandler(java.lang.String id, java.lang.Object parameterObject, RowHandler rowHandler)
          Executes a mapped SQL SELECT statement that returns a number of result objects that will be handled one at a time by a RowHandler.

 void

queryWithRowHandler(java.lang.String id, RowHandler rowHandler)
          Executes a mapped SQL SELECT statement that returns a number of result objects that will be handled one at a time by a RowHandler.

 void

startBatch()
          Starts a batch in which update statements will be cached before being sent to the database all at once.

 int

update(java.lang.String id)
          Executes a mapped SQL UPDATE statement.

 int

update(java.lang.String id, java.lang.Object parameterObject)
          Executes a mapped SQL UPDATE statement.

 

 

 

 

    <dataSource type="SIMPLE">

      <property name="JDBC.Driver" value="oracle.jdbc.OracleDriver"/>

      <property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@127.0.0.1:1521:XE"/>

      <property name="JDBC.Username" value="spring"/>

      <property name="JDBC.Password" value="ms*******"/>

    </dataSource>

 

<transactionManager type="JDBC" commitRequired="false">

   <dataSource type="SIMPLE">

      <property name="JDBC.Driver" value="oracle.jdbc.OracleDriver"/>

      <property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@192.168.123.163:1521:XE"/>

      <property name="JDBC.Username" value="hr"/>

      <property name="JDBC.Password" value="1234"/>

    </dataSource>

  </transactionManager>

 

 

public class BookDao {

 

      SqlMapClient sqlMapClient;

     

      public BookDao(){

            try{

                  Reader reader = Resources.getResourceAsReader("ibatis/SqlMapConfig.xml");

                 

                  sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);

                 

            }catch(IOException e){

                  e.printStackTrace();

            }

      }

     

      public static void main(String[] args) throws SQLException{

            BookDao  dao = new BookDao();

            Book book1 = new Book(8, "Spring Book Edition 8", new Date(), "spring8.jpg");

            dao.addBook(book1);

      }

     

     

      public void addBook(Book book) throws SQLException {

           

            sqlMapClient.insert("add", book);

           

      }

     

}

 

http://mybatis.googlecode.com/svn/branches/mybatis-2-maintenance/mybatis-2-docs/ko/

 

 

1 건이 반환될 때  queryForObject

여러건이 반환될 때  queryForList

 

XML 안에서는 부동호를 적을 수 없음

 

Ø    >  부등호를  &gt;  로 변경해서 적어야 함.

Ø  특수문자의 경우

 

<![CDATA[

        select id, name, published, photo

        from Book

        where id = #id#

     ]]>

 

<![CDATA[ 사용할 경우 구문을 Parsing 하지 않음.  Text 로만 인식함.  특수문자의 경우  <   >   "    '  &

해석하지 않고 그대로 구문이 날아가기 때문에 문제가 발생하지 않음.

 

 

title like '%우리%'

title like '%#value#%'  (X)  아래와 같이 처리해 주어야 함. 치환값이 포함된 경우

ibatis 에서는    title like '%' | #value# | '%'

 

<settings useStatementNamespaces="true"/>

하는 경우

Exception in thread "main" com.ibatis.sqlmap.client.SqlMapException: There is no statement named detail in this SqlMap.

      at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.getMappedStatement(SqlMapExecutorDelegate.java:231)

      at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.queryForObject(SqlMapExecutorDelegate.java:509)

      at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.queryForObject(SqlMapExecutorDelegate.java:493)

      at com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl.queryForObject(SqlMapSessionImpl.java:106)

      at com.ibatis.sqlmap.engine.impl.SqlMapClientImpl.queryForObject(SqlMapClientImpl.java:82)

      at ibatis.BookDao.getBookDetail(BookDao.java:43)

      at ibatis.BookDao.main(BookDao.java:34)

 

 

자주 사용하는 경우

<typeAlias alias="book" type="ibatis.Book"/>

 

 

 

      public int getAllCount() throws SQLException{

            return (Integer)sqlMapClient.queryForObject("Book.count");

      }    

 

 

 

 

jdbc  << --  jdbcTemplate  << -- DataSource

 

ibatis << -- sqlMapClientTemplate

 

 

Spring 과 연계 하려면   sqlMapClientFactoryBean 에 의해서 만들어진 것을 얻어 사용하는 방식임.

                          slqMapClientBuilder 와 동일한 역할을 함. ( sqlMapClient 객체를 생성해 줌 )

 

1.     sqlMapConfig.xml 이 어디 있는지 알려줘야 함.

2.     DataSource  ibatis 각 연결할 DB 를 알려줘야 함.

Spring 이 제공하는 TransactionManager 기능을 사용하기위해서는 ConnectionPool  Spring 에서 만들어서 소유해야 함.

Spring 내에 Datasource 와 관련된 생성이 있어야 함.

 

 

SqlMapClient SQLException 를 던지기 때문에 try~ catch 를 해줘야 하나

 

Spring SqlMapClientTemplate (위의 SqlMapClient 과 동일한 기능을 제공) --- Wrapper 의 역할을 하게 됨.  를 제공해 준다. 

DataAccessException 을 발생함 // 이는 try~catch 가 불필요하게 됨.

 

 

 

D:\springsource-tool-suite-2.3.2\spring-framework-2.5.6.SEC01-with-dependencies\spring-framework-2.5.6.SEC01\dist\modules

spring-test.jar

D:\springsource-tool-suite-2.3.2\spring-framework-2.5.6.SEC01-with-dependencies\spring-framework-2.5.6.SEC01\lib\junit

junit-4.4.jar

 

 

 

transactionManager 사용하니

 

2010. 8. 14 오후 9:48:19 org.springframework.test.context.TestContextManager retrieveTestExecutionListeners

정보: @TestExecutionListeners is not present for class [class orm.IbatisBookDaoTest]: using defaults.

2010. 8. 14 오후 9:48:19 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

정보: Loading XML bean definitions from class path resource [orm/orm.xml]

2010. 8. 14 오후 9:48:19 org.springframework.context.support.AbstractApplicationContext prepareRefresh

정보: Refreshing org.springframework.context.support.GenericApplicationContext@1888759: display name [org.springframework.context.support.GenericApplicationContext@1888759]; startup date [Sat Aug 14 21:48:19 KST 2010]; root of context hierarchy

2010. 8. 14 오후 9:48:19 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory

정보: Bean factory for application context [org.springframework.context.support.GenericApplicationContext@1888759]: org.springframework.beans.factory.support.DefaultListableBeanFactory@10f6d3

2010. 8. 14 오후 9:48:19 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons

정보: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@10f6d3: defining beans [dataSource,sqlMapClient,sqlMapClientTemplate,bookDao,transactionManager,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor]; root of factory hierarchy

2010. 8. 14 오후 9:48:19 org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName

정보: Loaded JDBC driver: oracle.jdbc.OracleDriver

2010. 8. 14 오후 9:48:20 org.springframework.test.context.transaction.TransactionalTestExecutionListener startNewTransaction

정보: Began transaction (1): transaction manager [org.springframework.jdbc.datasource.DataSourceTransactionManager@491c4c]; rollback [true]

2010. 8. 14 오후 9:48:20 org.springframework.test.context.transaction.TransactionalTestExecutionListener endTransaction

정보: Rolled back transaction after test execution for test context [[TestContext@137d090 testClass = IbatisBookDaoTest, locations = array<String>['classpath:/orm/orm.xml'], testInstance = orm.IbatisBookDaoTest@15db314, testMethod = configBookDao@IbatisBookDaoTest, testException = [null]]]

2010. 8. 14 오후 9:48:20 org.springframework.test.context.transaction.TransactionalTestExecutionListener startNewTransaction

정보: Began transaction (2): transaction manager [org.springframework.jdbc.datasource.DataSourceTransactionManager@491c4c]; rollback [true]

2010. 8. 14 오후 9:48:20 org.springframework.test.context.transaction.TransactionalTestExecutionListener endTransaction

정보: Rolled back transaction after test execution for test context [[TestContext@137d090 testClass = IbatisBookDaoTest, locations = array<String>['classpath:/orm/orm.xml'], testInstance = orm.IbatisBookDaoTest@aeea66, testMethod = testAddBook@IbatisBookDaoTest, testException = [null]]]

 

4.4 부터 annotation 지원함.

 

 

hamcrest

http://code.google.com/p/hamcrest/downloads/list

 

hamcrest

Hamcrest - library of matchers for building test expressions

 

import static org.hamcrest.CoreMatchers.*;

 

 

 

'Spring' 카테고리의 다른 글

Spring cglib  (0) 2011.09.12
Spring fw AOP and Paypal soap  (0) 2011.09.04
자바 - Log4j 사용법 ( 설명 자세히 잘 되어 있음 )  (0) 2011.08.26
Java 연습 2008-1 Banking  (0) 2011.08.24
스프링 First class 2010 .07 .03 (토)  (0) 2011.08.23