티스토리 뷰

지난 글인 File to File 예제를 통해 어떤것이 Chunk 지향적인것인지 간단히 알수 있었다. 

 

Spring Batch Chunk Example (1) - File to File (with FlatFileItemReader, FlatFileItemWriter)

현재까지 진행한 대부분의 프로젝트는 복잡하기도 하고 상황에 맞지 않아(WebService, EAI 연동 등) Spring Batch에서 일반적으로 사용하고 있는 chunk 방식 대신에 tasklet을 이용하여 사용하였다. tasklet을

oingdaddy.tistory.com

DB to DB는 File to File에서 기본적인것은 충분히 언급을 했으므로 바로 예제로 들어가겠다. 

 


context-batch-job-db2db.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:batch="http://www.springframework.org/schema/batch"
	xsi:schemaLocation="
	http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	
  <batch:job id="db2dbJob">
    <batch:step id="db2dbStep">			
      <batch:tasklet transaction-manager="transactionManager">
        <batch:chunk reader="db2dbReader" writer="db2dbWriter" commit-interval="100" />
      </batch:tasklet>
    </batch:step>
  </batch:job>
    ... 생략 ...
</beans>

file2file 과 마찬가지 Batch Job의 구조를 가지고 있다. 차이가 있게 설정을 한 부분이라면 중간의 processor를 없앤 것이다. processor는 데이터 가공을 위한 역할을 하지만 Step의 필수 구성요소는 아니다. 이 Job의 역할은 A (SAMPLE_STUDENT_IN)라는 테이블에서 값을 읽어서 그대로 B (SAMPLE_STUDENT_OUT) 테이블에 넣어주는 것이다.


db2dbReader

<bean id="db2dbReader" class="org.mybatis.spring.batch.MyBatisPagingItemReader">
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  <property name="queryId" value="student.retrieveStudent"/>
  <property name="pageSize" value="100"/>
</bean>

Reader는 어디로부터 값을 읽어오는 역할을 하는 것이다. 이번에는 file이 아닌 db에서 값을 읽어와야 하므로 위와 같은 세팅이 필요하다. 이 property 값은 MyBatis를 사용해봤다면 익숙하게 금방 사용할 수 있을것이다. Mybatis에서 제공을 해주는 MyBatisPagingItemReader라는 Reader를 사용해서 값을 불러오는것이다. pageSize는 일반적으로 chunk 사이즈와 일치시켜주면 된다. 

 

<mapper namespace="student">

  <select id="retrieveStudent" resultType="sample.template.model.Student">
    <![CDATA[
      SELECT * FROM ( SELECT ROWNUM AS RNUM, A.* FROM (
        SELECT user_id, 
               user_name
        FROM    SAMPLE_STUDENT_IN
      ) A WHERE ROWNUM <= #{_skiprows} + #{_pagesize} ) WHERE RNUM > #{_skiprows}
    ]]>
  </select>

</mapper>

student.retrieveStudent 쿼리는 위와 같고 SAMPLE_STUDENT_IN 이라는 테이블에서 100개 만큼의 데이터를 읽어오도록 한다. 말 그대로 paging 처리하여 그만큼의 데이터만큼씩 읽어서 처리하겠다는 것이다. 

MyBatisPagingItemReader 말고도 db에서 값을 읽어오는 reader는 MyBatisCursorItemReader 도 있다. 


db2dbWriter

<bean id="db2dbWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
  <property name="dataSource" ref="dataSource" />
  <property name="sql">
    <value>
      <![CDATA[    
        INSERT INTO SAMPLE_STUDENT_OUT (user_id, user_name) VALUES (:userId, :userName)
      ]]>
    </value>
  </property>
  <property name="itemSqlParameterSourceProvider">
    <bean class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider" />
  </property>
</bean>

읽어온 값을 DB에 다시 넣기 위해서는 JdbcBatchItemWriter를 사용하였다. property는 설명을 안해도 이해가 될정도로 직관적이다. 주의할점은 값을 바인딩 해주는 부분만 ':변수명' 으로 처리를 해주면 된다. itemSqlParameterSourceProvider에 해당하는 부분은 sql에 파라미터 설정으로 PreparedStatement의 데이터 설정을 하는 것이라고 보면 된다. 아주 간결하게 writer를 구현해 볼수 있었다. 

JdbcBatchItemWriter 말고도 db에 값을 쓰는 writer는 MyBatisBatchItemWriter 도 있다. 사용방식은 위에 기술한 MyBatisPagingItemReader와 거의 흡사하다. 

 

MyBatis 에서 제공하는 자세한 기능은 다음을 참고하자. 

 

mybatis-spring – 마이바티스 스프링 연동모듈 | 스프링 배치

Spring Batch 마이바티스 스프링 연동모듈의 1.1.0버전에서는 스프링 배치 애플리케이션을 만들기 위해 두개의 빈을 제공한다. 두개의 빈은 MyBatisPagingItemReader 와 MyBatisCursorItemReader 와 MyBatisBatchItemWrit

mybatis.org

위와 같이 수행을 했을때 SAMPLE_STUDENT_IN의 데이터가 SAMPLE_STUDENT_OUT로 넘어간 것을 확인할 수 있다. 

 

지금까지 설명한 file2file 과 db2db 예제를 적절하게 활용하여 file2db, db2file 에 대한 구현도 시도해볼수 있다.  file reader, file writer, db reader, db writer가 모두 존재하기에 이를 조합하여 사용한다면 어렵지 않게 구현할 수 있다. 

 

끝!

댓글
최근에 올라온 글
최근에 달린 댓글
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31