spring로 검색한 결과 :: 시소커뮤니티[SSISO Community]
 
SSISO 카페 SSISO Source SSISO 구직 SSISO 쇼핑몰 SSISO 맛집
추천검색어 : JUnit   Log4j   ajax   spring   struts   struts-config.xml   Synchronized   책정보   Ajax 마스터하기   우측부분

회원가입 I 비밀번호 찾기


SSISO Community검색
SSISO Community메뉴
[카페목록보기]
[블로그등록하기]  
[블로그리스트]  
SSISO Community카페
블로그 카테고리
정치 경제
문화 칼럼
비디오게임 스포츠
핫이슈 TV
포토 온라인게임
PC게임 에뮬게임
라이프 사람들
유머 만화애니
방송 1
1 1
1 1
1 1
1 1
1

spring로 검색한 결과
등록일:2015-05-21 13:37:30
작성자:
제목:Spring - Mybatis 에서 Mapper interface 를 주입받는 방법과 SqlSession 을 주입받는 방법


spring - Mybatis 에서 SQL을 실행 하려면 크게 다음 2가지 방법을 사용 가능하다.

1) Mapper interface 를 주입받는 방법

2) SqlSession 을 주입받는 방법

 

1) Mapper interface 를 주입 받는 방법은 앞에서 설명 했듯이 MapperFactoryBean을 이용하는 것이다.

MapperFactoryBean 을 이용해서 Mapper interface bean 을 선언하는 방법은 다음과 같다.

  1 <bean id="mapper1" class="org.mybatis.spring.mapper.MapperFactoryBean">
  2     <property name="mapperInterface" value="tkstone.test.mapping.Mapper1" />
  3     <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  4 </bean>

 

SQL을 실행 하려는 Bean 에서는 "mapper1" 을 주입 (Dependency injection) 받아서 실행하면 된다.

 

2) SqlSession 을 주입 받는 방법은 SqlSessionTemplate 을 이용하는 것이다.

다음은 SqlSession 을 Bean 으로 선언하는 부분이다. 

  1 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
  2     <constructor-arg index="0" ref="sqlSessionFactory" />
  3 </bean> 

 

이렇게 선언된 SqlSession 을 사용하는 Bean (주로 DAO 클래스) 에서는 다음과 같이 구현한다.

  1 import org.apache.ibatis.session.SqlSession;
  2 
  3 public class MyDao {
  4  private SqlSession sqlSession;
  5  
  6     @Resource(name="sqlSession")
  7  public void setSqlSession(SqlSession sqlSession){
  8   this.sqlSession = sqlSession;
  9  }
 10  
 11  public void insertA1() throws Exception{
 12   sqlSession.insert("tkstone.test.mapping.Mapper1.insertA1", SomeParam);
 13  }
 14 }

위의 예제의 11라인에서는 Mybatis SqlSession.insert() 메소드를 바로 호출하고 있다.  

 

결과적으로 실행되는 SQL은 동일하다. 개인적으로 생각하는 장단점은 다음과 같다.

 

 Mapper interface bean 선언 

 SqlSession bean 선언 

 장점

  • Java 소스 내에 Mybatis 에 종속적인 API 를 사용하지 않음
  •  DAO 클래스가 늘어날수록 Bean 선언이 용이함 (DAO를 @Component 로 선언하는 경우)

 단점

  •  Mapper interface 개수가 늘어날수록 선언해야 하는 Bean 도 늘어남
  • Sql 종류, Parameter type에 따라 SqlSession API 를 구분해서 사용해야 함