본문 바로가기

Spring/참고사항

Mybatis Plugins

Mybatis3에선 Spring AOP기능과 비슷한 동작을 제공하는 Plugins를 제공한다.

Mybatis에서 제공하는 메서드를 호출을 하면 요청을 가로채어 특정 작업을 수행할 수 있다.

AOP란?
관점 지향 프로그래밍의 약자로 주로 공통적인 부가기능을 비즈니스 로직과 분리하는 프로그래밍 기법

Mybatis에서 제공해주는 Plugins 클래스는 아래와 같다.

  • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler (getParameterObject, setParameters)
  • ResultSetHandler (handleResultSets, handleOutputParameters)
  • StatementHandler (prepare, parameterize, batch, update, query)

플러그인을 사용할 땐 mybatis config 설정이 된 xml에 다음과 같이 추가해준다.

<plugins>
  <plugin interceptor="org.mybatis.example.ExamplePlugin">
    <property name="someProperty" value="100"/>
  </plugin>
</plugins>

 

실제 Java에서 구현할 땐 ibatis에서 제공하는 @Intercepts라는 어노테이션을 지정하고, Interceptor 인터페이스의 intercept(Invocation invocation) 메서드를 구현해야한다.

@Intercepts({@Signature(
  type= Executor.class,
  method = "update",
  args = {MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
  private Properties properties = new Properties();
  public Object intercept(Invocation invocation) throws Throwable {
    // implement pre processing if need
    Object returnObject = invocation.proceed();
    // implement post processing if need
    return returnObject;
  }
  public void setProperties(Properties properties) {
    this.properties = properties;
  }
}

 

우선 상단에 있는 @Intercepts 어노테이션을 살펴보자.

Property 설명
type Plugin 클래스가 들어가는 자리.
Executor, ParameterHandler, ResultSetHandler, StatementHandler 요놈들이들어간다.
method 각각의 type에서 제공하는 인터셉터 구간을 지정한다.
StatementHandler 의 경우 (prepare, parameterize, batch, update, query) 요놈들이 들어갈 수 있다.
args 각각의 type들은 인터페이스 형태로 되어있는데 method들에 대한 추상메서드들이 있다. 추상메서드의 파라매터값을 넣는다.

그리고 인터셉터는 여러 개 지정할 수 있다. 예를 들어 StatementHandler 타입으로 prepare, parameterize 작업 중에 가로채고 싶다면 아래와 같이 설정한다.

@Intercepts({
@Signature(type= StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}),
@Signature(type= StatementHandler.class, method = "parameterize", args = {Statemennt.class})
})

 

이번엔 구현부인 intercept 메서드를 살펴보자. 코드를 보면 어디서 많이 봤을 것이다.

Spring AOP와 비슷할 것이다. Invocation은 Mybatis가 가로챈 요청의 대상정보가 들어가 있다.

 public Object intercept(Invocation invocation) throws Throwable {
   // implement pre processing if need
   Object returnObject = invocation.proceed();
   // implement post processing if need
   return returnObject;
 }

 

Mybatis의 Invocation이 제공하는 메서드는 아래와 같다.

Type Method
Object[] getArgs()
Method getMethod()
Object getTarget()
Object proceed()

따라서 Mybatis 작업을 가로챈 후 invocation.proceed() 메서드가 호출하기 전에 처리하고 싶은 작업들을 해주면 된다. 주로 사용하는 케이스는 로그 작업을 하거나, 파라매터 설정을 커스터마이즈 하고 싶을 때 사용한다.

 

다음장에선 Mybatis Intercept의 StatementHandler를 이용하면서 확인한 이슈와 이를 이용하는 방법에 대해서 알아보자.

'Spring > 참고사항' 카테고리의 다른 글

Mybatis StatementHandler와 Batch타입 처리 관련 이슈  (0) 2021.02.17