티스토리 뷰

Study/Spring

[Spring] Mybatis 연동 (1)

그징그징 2018. 12. 24. 17:02

[Spring] Mybatis 연동 (1)


root-context.xml 파일에

SqlSessionFactory와 SqlSession 설정을 추가해야한다.


mybatis에서 SqlSession을 생성하기 위해 SqlSessionFactory를 사용한다.


(참고 - http://www.mybatis.org/spring/ko/getting-started.html)


mybatis와 spring 연동을 위해 pom.xml에

mybatis, mybatis-spring 2개의 라이브러리를 추가한다.


마이바티스는 개발자가 지정한 SQL, 저장프로시저 그리고 몇가지 고급 매핑을 지원하는 퍼시스턴스 프레임워크이다. 마이바티스는 JDBC로 처리하는 상당부분의 코드와 파라미터 설정및 결과 매핑을 대신해준다. 마이바티스는 데이터베이스 레코드에 원시타입과 Map 인터페이스 그리고 자바 POJO 를 설정해서 매핑하기 위해 XML과 애노테이션을 사용할 수 있다.


(참고 - http://www.mybatis.org/mybatis-3/ko/index.html)





(참고  - https://github.com/mybatis/spring/blob/master/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java)


에 들어가서 DataSource를 검색해서 찾아보면

setDataSource() 라는 함수가 존재한다.



root-context.xml 파일에 2가지의 설정을 추가한다.


1. SqlSessionFactoryBean


SqlSessionFactory  생성을 하려할때

Mybatis와 Spring 연동시 SqlSessionFactoryBean을 사용합니다.

(Mybatis만 사용시 SqlsessionFactoryBuilder)


        <bean id = "sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="dataSource"></property>

</bean>

 Sqlsession을 생성하기 위해 SqlSessionFactory를 먼저 설정해준다.(dataSource도 property(속성)로 지정해준다.)



Spring 문서에 있는 글이다.

SqlSessionFactoryBean은 FactoryBean 인터페이스를 상속받아진 상태로

.getObject() 를 이용하여 SqlSessionFactory 를 만들게 된다.

3.7.3. Customizing instantiation logic using FactoryBeans

The org.springframework.beans.factory.FactoryBean interface is to be implemented by objects that are themselves factories.

The FactoryBean interface is a point of pluggability into the Spring IoC containers instantiation logic. If you have some complex initialization code that is better expressed in Java as opposed to a (potentially) verbose amount of XML, you can create your own FactoryBean, write the complex initialization inside that class, and then plug your customFactoryBean into the container.

The FactoryBean interface provides three methods:

  • Object getObject(): has to return an instance of the object this factory creates. The instance can possibly be shared (depending on whether this factory returns singletons or prototypes).

  • boolean isSingleton(): has to return true if this FactoryBean returns singletons, false otherwise

  • Class getObjectType(): has to return either the object type returned by the getObject() method or nullif the type isn't known in advance

The FactoryBean concept and interface is used in a number of places within the Spring Framework; at the time of writing there are over 50 implementations of the FactoryBean interface that ship with Spring itself.

Finally, there is sometimes a need to ask a container for an actual FactoryBean instance itself, not the bean it produces. This may be achieved by prepending the bean id with '&' (sans quotes) when calling the getBean method of the BeanFactory (including ApplicationContext). So for a given FactoryBean with an id of myBean, invoking getBean("myBean") on the container will return the product of the FactoryBean, but invokinggetBean("&myBean") will return the FactoryBean instance itself. 


(main 이 있는 .java 파일 생성 후 테스트)




2. SqlSessionTemplate



Mybaits를 사용하기위한 기본적인 자바 인터페이스 : SqlSession

해당 인터페이스를 이용하여 명령어를 실행, 매퍼를 얻고 트랜잭션을 관리 할수있다.(열고 닫고를 내가 해줘야하는 상황..?으로 이해했다.)


SqlSessionTemplate 는 세션을 닫고, 커밋 또는 롤백하는 것을 포함한 세션의 생명주기를 관리하고

Mybatis 예외를 DataAccessException 으로 변환하는 작업 또한 처리한다.

(자동으로 열고 닫고 처리?!)


  <bean id = "sqlSession" class="org.mybatis.spring.SqlSessionTemplate">

<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>

</bean>

 sqlSessionFactory 객체를 SqlSessionTemplate의 생성자에 넘겨준다.(constructor-arg 생성자 관련 태그)


(자바 코드)

(확인)




1. SqlSessionFactory JUnit 확인

(src/test/java -> com.sora.shop.db -> SqlSessionFactoryTest.java 생성)



객체 생성됨.




2. Sqlsession JUnit 확인

(src/test/java -> com.sora.shop.db -> SqlSessionTest.java 생성)


객체 생성됨.





1. SqlSession을 만들기 위해서는 SqlSessionFactory가 필요하다. 


2. SqlSessionFactory는 SqlSessionFactoryBean 을 이용하여 생성 (JDBC dataSource를 넘겨줘야한다.)


3. 생성된 SqlSessionFactory를 SqlSessionTemplate 생성자 인자로 넘겨주면 SqlSession 생성


'Study > Spring' 카테고리의 다른 글

[Spring] web.xml (한글 설정)  (0) 2018.12.26
[Spring] Mybatis 연동 (2)  (0) 2018.12.26
[Spring] Mysql과 JUnit (2)  (0) 2018.12.24
[Spring] root-context.xml와 servlet-context.xml  (0) 2018.12.24
[Spring] Mysql과 JUnit (1)  (0) 2018.12.24
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   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
글 보관함