Skip to the content.

MyBatis

MyBatis는 복잡한 SQL문을 따로 정의하여 유지보수하기 편리한 장점이 있다.

-spring-jdbc/spring-tx:스프링에서 데이터베이스 처리와 트랜잭션 처리

-mybatis/myBatis-spring:Mybatis와 스프링 연동용 라이브러리

pom.xml

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.7</version>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.6</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

SQLSessionFactory

이름 그대로 내부적으로 SQLSession이라는 것을 만들어 내는 곳인데

이것을 통해 Connection을 생성하거나 원하는 SQL을 전달하고 그 결과를 리턴 받는다.

쉽게 말하자면 DB서버와 MyBatis를 연결해주는 역할을 한다.그래서 이 객체가 DataSource를 참조하여

MyBatis와 DB(oracle,mysql)서버를 연동시켜준다.

*root-context.xml은 스프링 프레임워크에서 빈생성에 필요한 설정을 도와주는 설정파일이다.

스프링에 SqlSessionFactory를 등록하는 작업은 SqlSessionFactoryBean을 이용한다.

그 증거로는 패키지명을 보면 MyBatis의 패키지가 아니라

스프링과 연동 작업을 처리하는 mybatis-spring 라이브러리의 클래스임을 알 수 있다.

root-context.xml(xml의 경우)

	<!--HikcariCP configuration-->
	<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource"
		  destroy-method="close">
		<constructor-arg ref="hikariConfig"/>
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

RootConfig(java의 경우)

 @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource());
        return sqlSessionFactory.getObject();
    }

스프링과의 연동 처리

좀 더 편하게 작업하기 위해서는 SQL을 어떻게 처리할 것인지를 별도의 설정을 분리해 주고,

자동으로 처리되는 방식을 이용하는 것이 좋다.

이를 위해서 MyBatis의 Mapper 라는 존재를 이용한다.

Mapper는 쉽게 말해서 SQL과 그에 대한 처리를 지정하는 역할을 한다.

MyBatis-
Spring을 이용하는 경우에는 Mapper를 XML과 인터페이스+어노테이션의 형태로 작성할 수 있다.

Mapper를 작성 하였다면 인식하기 위해 태그 사용한다.

이 태그 안에 base-package속성에 지정된 패키지는 모든 MyBatis 관련 어노테이션을 찾아서 처리한다.

RootConfig.class에 경우

@MapperScan(basePackages = {“mapper파일 패키지경로”})

를 삽입하여 해당 mapper 파일을 불러올 수 있게 도와준다.