관리 메뉴

나만의공간

Spring Batch 강의 #4(DB연결편) 본문

IT/Spring Batch

Spring Batch 강의 #4(DB연결편)

밥알이 2023. 9. 20. 14:01

대부분에 어플리케이션은 DB를 접속하여 동작을 합니다.
Batch는 더욱 DB연결을 많이 하게 되어 있고, Spring Batch에서도 DB연결은 필요하게 됩니다.
이번 강의 에서는 Spring Batch에 DB를 연결하고 3편에서 강의한 Log를 이용해 DB관련 로그도 같이 출력 되도록 진행 하겠습니다.

SpringBatch 5.X가 나온상태이지만 DB연결시 어려움이 있어 SpringBatch 4.X기반으로 작성 되었습니다.

build.gradle DB 로그관련 설정 추가

start.spring.io 사이트에서 Spring Batch에 기본설정으로 생성하게 되면 아래와 비슷한 dependencies가 생성됩니다.
여기서 추가로 필요한 DB로그 정보등을 볼수 있는것들을 추가 합니다.

implementation group: 'org.bgee.log4jdbc-log4j2', name: 'log4jdbc-log4j2-jdbc4.1', version: '1.16'
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-batch'
	implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.0.1'
	compileOnly 'org.projectlombok:lombok'
	runtimeOnly 'com.mysql:mysql-connector-j'
	annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor:2.7.6'
	annotationProcessor 'org.projectlombok:lombok'
	implementation group: 'org.bgee.log4jdbc-log4j2', name: 'log4jdbc-log4j2-jdbc4.1', version: '1.16'
	implementation group: 'io.springfox', name: 'springfox-swagger2', version: '3.0.0'
	implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '3.0.0'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:3.0.1'
	testImplementation 'org.springframework.batch:spring-batch-test'
}

application.yml DB 정보 추가

application.yml 설정 파일에 DB연결 정보 등을 추가 합니다.

DB로그를 좀더 정확히 보기 위해 Local환경은 log4jdbc를 이용하여 연결하도록 합니다.
아래 driver를 사용하게 되면 DB관련 로그를 좀더 상세히 볼수 있게 됩니다.

driver-class-name: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
---
#local 환경 설정
spring:
  config:
    activate:
      on-profile: local
#MySql 데이터베이스 연결
  datasource:
    primary:
      driver-class-name: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
      jdbc-url: jdbc:log4jdbc:mysql://127.0.0.1:3306/test
      username: root
      password: test
      pool-name: hikari-cp-primary
    secondary:
      driver-class-name: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
      jdbc-url: jdbc:log4jdbc:mysql://127.0.0.1:3306/test
      username: root
      password: test
      pool-name: hikari-cp-primary

  #Spring batch가 사용하는 Schema생성 방식 설정
  #never:미생성, always:매번생성, embedded:테스트용 메모리 DB용
  batch:
    jdbc:
      initialize-schema: never

 

Transaction 어노테이션 생성

MySql 연결시 사용할 어노테이션을 만들고, DB정보 설정시 어노테이션 설정을해준다.
아래 어노테이션으로 Mapper Class에 명시하여 해당 DB와 연결 되도록 한다.

@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface PrimaryConnection {
}

 

DB 연결설정

application.yml에 설정된 DB정보를 이용하여 DB관련 세팅을 F/W에 진행
Mapper Class에서 사용할 어노테이션을 해당 클래스에서 정의

/**
 * Primary DataBase 연결 클래스
 * Mapper 클래스에서 AnotationClass명으로 지정: PrimaryConnection
 */
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = MyBatisConfig.BASE_PACKAGE, annotationClass = PrimaryConnection.class, sqlSessionFactoryRef = "primarySqlSessionFactory")
class PrimaryMyBatisConfig {
    @Primary
    @Bean(name = "primarySqlSessionFactory")
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource) throws Exception {
        return SqlSessionFactoryBuilder.build(primaryDataSource);
    }

    /**
     * DataSource 연결정보를 Application.yml에 정의한 값을 사용해서 연결
     * @return
     */
    @Primary
    @Bean(name = "primaryDataSource", destroyMethod = "")
    @ConfigurationProperties("spring.datasource.primary")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean
    public PlatformTransactionManager transactionManager(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(primaryDataSource);
        transactionManager.setGlobalRollbackOnParticipationFailure(false);
        return transactionManager;
    }
}

Mybatis 설정

Mybatis 파일위치를 지정한다.
Mapper Class와 Mybatis xml 파일이 연결이 안될경우에는 아래 패키지 위치 혹은 classpath위치등이 틀린경우 많이 발생한다.

아래와 같은 오류를 만나게 되면 xml 파일에 위치 mapper Class위치, classpath위치 등이 맞게 설정 되어 있는지 확인이 필요하다.
Invalid bound statement (not found)

/**
 * mybatis xml 파일 위치 정의
 */
public class SqlSessionFactoryBuilder {
    private static final String CONFIG_LOCATION_PATH = "classpath:/mybatis-config.xml";
    private static final String MAPPER_LOCATIONS_PATH = "classpath*:com/study/**/*.xml";
    private static final String TYPE_ALIASES_PACKAGE = "com.study";
    private static final String TYPE_HANDLERS_PACKAGE = "com.study";

    /**
     * SqlSessionFactory 설정
     * @param dataSource DataSource 정보
     * @return SqlSessionFactory
     * @throws Exception 예외가 발생할 경우 던짐
     */
    public static SqlSessionFactory build(DataSource dataSource) throws Exception {
        PathMatchingResourcePatternResolver pathResolver = new PathMatchingResourcePatternResolver();

        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setTypeAliasesPackage(TYPE_ALIASES_PACKAGE);
        sessionFactoryBean.setTypeHandlersPackage(TYPE_HANDLERS_PACKAGE);
        sessionFactoryBean.setConfigLocation(pathResolver.getResource(CONFIG_LOCATION_PATH));
        sessionFactoryBean.setMapperLocations(pathResolver.getResources(MAPPER_LOCATIONS_PATH));

        return sessionFactoryBean.getObject();
    }
}

 

위와 같이 기본적인 설정을 완료하고 나면 SpringBatch에서 DB를 연결하여 Batch를 만들수 있게 된다.
Log파일생성 / DB연결 두가지 기능이 완료된 Git정보는 아래에서 받으면 됩니다.

https://github.com/abilitybobr/springbatch.git

 

GitHub - abilitybobr/springbatch: springbatch 학습용 코드

springbatch 학습용 코드. Contribute to abilitybobr/springbatch development by creating an account on GitHub.

github.com

이제 SpringBatch를 실행할 기본 구성이 끝났으면 SpringBatch에 있는 기능들을 하나씩 예제로 만들어 가보겠습니다.

'IT > Spring Batch' 카테고리의 다른 글

Spring Batch 강의 #6(배치란?)  (0) 2023.09.25
Spring Batch 강의 #5(Spring Batch 메타 테이블 구조)  (0) 2023.09.22
Spring Batch 강의 #3 (Logging편)  (0) 2023.08.09
Spring Batch 강의 #2  (0) 2023.08.01
SpringBatch 강의 #1  (0) 2023.07.21
Comments