티스토리 뷰

Spring

[Spring] MySQL MyBatis 연동 방법

꼴레뇨 2018. 7. 6. 17:07
반응형

테스트 환경

- Spring 4.3.18

- STS 플러그인 3.9.5

- JDK 1.8

- Tomcat 8.0

- MySQL 8.0




Step 0. 준비사항


아래 링크를 참조하여 Spring과 MySQL의 연동 작업을 완료한다.

http://its-easy.tistory.com/15




Step 1. pom.xml 파일에 관련 라이브러리 추가


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
 
        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>        
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
cs

* 테스트 환경과 버전이 다르다면 아래 링크를 참조하여 시스템 최소 요구사항 확인 필요

http://www.mybatis.org/spring/


* spring-jdbc 라이브러리를 추가하지 않으면 select 등의 db작업 시에 아래와 같은 에러 발생

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

java.lang.NoClassDefFoundError: org/springframework/dao/support/DaoSupport

...


org.springframework.web.context.ContextLoader - Context initialization failed

java.lang.NoClassDefFoundError: org/springframework/dao/support/DaoSupport

...




Step 2. root-context.xml 파일에 sqlSessionFactory 추가


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
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!-- Root Context: defines shared resources visible to all other web components -->
    
    <!-- MySQL dataSource -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/
        <property name="username" value="user"/
        <property name="password" value="user123"/>
    </bean>        
    
    <!-- MyBatis -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="dataSource" ref="dataSource"></property>
        <property name="mapperLocations" value="classpath:mappers/**/*.xml"></property>
    </bean>    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.my.test" />
    </bean>
            
</beans>
 
cs

* 20라인은 쿼리가 직접적으로 작성될 mapper파일들이 있는 위치를 지정해주는 것이다. 여기에서는 mappers 폴더 하위의 모든 xml파일이라고 지정해놓았다.

* 22~24라인은 mapper에 대한 bean을 지정된 패키지에서 scan해서 등록해주는 것이다. 이 설정이 없으면 mapper 파일 하나당 하나의 bean을 직접 등록해줘야한다.




Step 3. mybatis-config.xml 파일 생성


1
2
3
4
5
6
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0/EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
 
<configuration>
    
</configuration>     
cs

Step 2의 18라인에서 지정해 준 경로에 파일을 생성해야 한다.

일반적으로 src/main/resources 폴더는 classpath로 잡혀있기 때문에 잘 모르겠으면 이 경로에 생성하면 된다.

classpath는 이클립스에서 프로젝트 우클릭 후 Deployment Assembly를 클릭해서 확인 할 수 있다.




Step 4. mapper xml 파일 생성


1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
<mapper namespace="com.my.test.service.test.TestMapper">
 
    <select id="selectNow" resultType="String">
        SELECT NOW()
    </select>
    
</mapper>
cs

Step 2의 20라인에서 지정해 준 경로에 파일을 생성해야 한다.

4라인의 namespace는 Step 5에서 생성할 mapper 인터페이스의 패키지 + 파일명을 의미한다.




Step 5. mapper 인터페이스 파일 생성


1
2
3
4
5
package com.my.test.service.test;
 
public interface TestMapper {
    String selectNow();
}
cs

Step 4의 4라인의 namespace에 지정된 경로와 파일명과 동일하게 파일을 생성해야 한다.




Step 6. 서비스 파일 생성


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.my.test.service.test;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
@Service
public class TestService {
 
    @Autowired
    private TestMapper mapper;
    
    public String selectNow() {
        return mapper.selectNow();
    }
}
cs




Step 7. 컨트롤러에서 호출


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.my.test.web;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
import com.my.test.service.test.TestService;
 
@Controller
public class TestController {
 
    @Autowired
    private TestService service;
    
    @RequestMapping("/selectNow.do")
    public void selectNow() {
        String result = service.selectNow();
        System.out.println(result);
    }    
    
}
cs




Step 8. 테스트


콘솔창을 확인해보면 쿼리의 결과값이 정상적으로 출력되는 것을 확인 할 수 있다.

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함