1. STS(Spring tool suite)에서 프로젝트를 새로 만든다.


2. pom.xml 파일에 다음 디펜던시를 추가한다.

하나라도 빠지면 안됨.

3. Spring의 다른 버전을 쓸 경우 Junit의 버전도 바꾼다.

필자는 스프링의 새 버전인 4.1.5를 써 보고자 스프링 버전을 높였다. 이럴 경우, Junit 버전도 높여야 한다.

다음의 글을 참고한다.

http://tadakichi.tistory.com/97


4. root-context.xml 파일로 가서 namespace를 체크한다.



이를 체크해줘야 mybatis 전용 태그를 쓸 수 있다.

만일 mybatis-spring이 보이지 않는다면 탭을 닫았다가 다시 열면 보일 것이다.


5. root-context.xml에 다음 세 가지 빈을 추가한다.


<bean id="dataSource"

class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver" />

<property name="url" value="jdbc:mysql://111.111.111.111:1111/스키마이름" />

<property name="username" value="유저네임" />

<property name="password" value="비밀번호" />

</bean>


<mybatis-spring:scan base-package="org.peno.mapper" />

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

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

</bean>


dataSource 빈은 DB와의 커넥션을 가져온다. 주의해야 할 점은 DriverManagerDataSource는 커넥션 풀을 만들지 않으므로 실전에서 쓰면 안된다는 거다. 실전에서는 아파치에서 제공하는 DBCP 등을 사용해야 할 것이다.


<mybatis-spring:scan base-package="org.peno.mapper" />은 Mybatis 전용 태그로 해당 패키지의 인터페이스를 자동 등록해준다. 여기서는 org.peno.mapper의 인터페이스들이 빈으로 등록된다. 인터페이스가 빈으로 등록되야 스프링에서 @autowired 같은 어노테이션을 이용해 쓸 수 있을 것이다.


6. 패키지를 만들어 간단한 인터페이스를 넣어둔다.


예를 들어 DB에서 시간을 불러오기 위한 인터페이스를 만든다면,


package org.peno.mapper;


import org.apache.ibatis.annotations.Select;


public interface TimeMapper {


@Select("select now()")

public String getTime();

}


7. 간단히 테스트하기

DB에서 시간을 불러오는 것을 간단히 테스트 한다면,

package org.peno.mapper;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/**/*-context.xml" })
public class Time {

@Autowired
ExcelMapper mapper;
@Before
public void setUp() throws Exception {
}

@Test
public void test() {

System.out.println(mapper.getTime());
}

}

이 정도면 충분할 것이다. 앞에서 mybatis 전용태그로 빈을 등록한 덕분에 테스트 클래스에서 @autowired로 빈을 불러다 쓸 수 있다. 




Posted by 타다키치
,