티스토리 뷰

2016/09/19 - [개발/JAVA] - 스프링 부트(Spring boot)에서 logback 적용하기


이어서.. 스프링 부트에서 마이바티스를 연동해 보도록 하겠습니다.

실무에서 주로 사용되는 mapper xml을 이용한 방법을 살펴보겠습니다.

DB는 오라클을 사용하지만 드라이버만 바꾸면 다른 종류의 DB도 사용이 가능합니다.


pom.xml

오라클 드라이버는 메이븐 중앙 저장소에 없기 때문에 오라클 저장소를 추가해 줍니다.

parent와 동일 레벨로 저장소를 추가합니다.


<repositories>

        <repository>

            <id>oracle</id>

            <name>ORACLE JDBC Repository</name>

            <url>http://maven.jahia.org/maven2</url>

        </repository>

    </repositories>

그리고 오라클 드라이버와 mybatis spring goot starter 종속성을 추가해줍니다.

마이바티스에서 스프링 대응하여 나온 것으로 기존 마이바티스는 필요없습니다.

(http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure)

<dependency>

        <groupId>org.mybatis.spring.boot</groupId>

        <artifactId>mybatis-spring-boot-starter</artifactId>

        <version>1.1.1</version>

    </dependency>

         

    <dependency>

        <groupId>com.oracle</groupId>

        <artifactId>ojdbc6</artifactId>

        <version>11.1.0.7.0</version>

    </dependency>


application.yml

spring.datasource 설정 부분이 추가되었으며, mybatis 설정 부분이 추가되었습니다.

mybatis-config.xml형식으로 설정을 하고 싶으면 mybatis.config-location설정을 쓰시면 됩니다.

다양한 설정 항목들이 있으니 스프링, 마이바티스 문서를 참고해 주세요.

datasource항목은 대부분 개발과 상용이 다를테니 샘플보다는 프로파일별로 옮겨서 관리를 하시는게 좋습니다.

spring:
  profiles: 
    active: dev
  timerName: exampleTimer
  datasource:
    driver-class-name: oracle.jdbc.driver.OracleDriver
    url: jdbc:oracle:thin:@111.222.111.222:1521:SIDHERE
    username: donnert
    password: password
---
mybatis:
  mapper-locations: classpath:mapper/**/*.xml
  configuration:
    lazyLoadingEnabled=true
    aggressiveLazyLoading=false
    mapUnderscoreToCamelCase=true
---
spring:
  profiles: local
  task:
    fixedDelay: 1000
    name: localTask
---
spring:
  profiles: dev
  task:
    fixedDelay: 5000
    name: devTask

Application.java

기존에 사용하시던대로 MapperScan어노케이션으로 매퍼 패키지 위치를 정의해 줍니다.

package net.donnert.spring.boot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@MapperScan("net.donnert.spring.boot")
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

TestMapper.java

쿼리 xml과의 인터페이스를 제공해줍니다.

package net.donnert.spring.boot;

public interface TestMapper {
	public String getValueFromDatabase();
}


testMapper.xml

src/main/resources하위에 mapper폴더 생성 후 testMapper.xml을 생성해 줍니다.

내용은 위에서 정의한 인터페이스 쿼리를 작성해줍니다.




    

Timer.java

매퍼 빈을 주입 받아서 그냥 호출하면 됩니다.

package net.donnert.spring.boot;

import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Component
public class Timer {
	Logger logger = LoggerFactory.getLogger(this.getClass());
	private AtomicInteger loopCounter = new AtomicInteger();
	
	@Autowired
	private StopWatch watch;
	
	@Autowired
	private TestMapper testMapper;
	
	@Value("${spring.task.name}")
	private String taskNamePrefix;
	
	@Value("${spring.timerName}")
	private String timerName;
	
	@PostConstruct
	public void init() {
		logger.info("{} init", timerName);
		watch.start();
	}

	@Scheduled(fixedDelayString = "${spring.task.fixedDelay}")
	public void tick() throws InterruptedException{
		watch.stop();
		logger.info(testMapper.getValueFromDatabase());
		String taskName = taskNamePrefix + "-" + String.valueOf(loopCounter.getAndIncrement());
		watch.start(taskName);
	}

	@Bean
	public StopWatch watch() {
		return new StopWatch();
	}
}

테스트

실행해 보면 아래처럼 쿼리 로그와 결과가 정상적으로 찍히는 모습을 볼 수 있습니다.

2016-09-20 13:56:08.904  INFO(12012)[main] [net.donnert.spring.boot.Timer:33] exampleTimer init
2016-09-20 13:56:09.286  INFO(12012)[main] [o.s.j.e.a.AnnotationMBeanExporter:431] Registering beans for JMX exposure on startup
2016-09-20 13:56:09.349  INFO(12012)[main] [o.s.s.a.ScheduledAnnotationBeanPostProcessor:244] No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
2016-09-20 13:56:09.372  INFO(12012)[main] [n.d.spring.boot.Application:57] Started Application in 3.229 seconds (JVM running for 3.793)
2016-09-20 13:56:10.812 DEBUG(12012)[pool-2-thread-1] [n.d.s.b.T.getValueFromDatabase:145] ==>  Preparing:  SELECT NAME FROM TEST WHERE ROWNUM=1
2016-09-20 13:56:10.902 DEBUG(12012)[pool-2-thread-1] [n.d.s.b.T.getValueFromDatabase:145] ==> Parameters: 
2016-09-20 13:56:10.930 DEBUG(12012)[pool-2-thread-1] [n.d.s.b.T.getValueFromDatabase:145] <==      Total: 1
2016-09-20 13:56:10.932  INFO(12012)[pool-2-thread-1] [net.donnert.spring.boot.Timer:40] 테스트이름

간단한 예제같지만 프로파일, 로깅, DB연결 등 필요한 부분들은 모두 들어가 있기 떄문에 실무에서도 

배치나 데몬 프로세스로 충분히 사용하실 수 있습니다.

스프링 부트를 이용하면 복잡한 설정도 필요없고

이미 구현된 것들을 설정만 해서 쓰는 방식이기 때문에 개발 시간이 많이 단축됩니다.


완성소스

https://github.com/donnert/spring-boot/tree/master/spring-boot-batch


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
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
글 보관함