본문 바로가기

STUDY/Spring

Spring | MyBatis 연동 (1) ( + JDBC, Oracle, jUnit, Spring-test)

0. Spring Legacy Project 생성

 

SpringMyBatis라는 이름의 프로젝트를 생성함.

 

 

Spring Legacy Project (mvc) 구조 살짝 파악해보기

main/java폴더에 자바 개발코드 (DAO, DTO, Controller 등)을 작성하고,

스프링에 대한 설정(버전 및 필요한 프로퍼티 등)은 spring폴더 하위에 작성함.

 

servlet-context.xml에 등록되어있는 veiwResolver를 보면 경로가 views폴더임을 확인할 수 있다.

 

 

1. pom.xml에 필요한 의존성 주입

 

+) 자바 버전을 1.8로 변경, 스프링프레임워크 버전을 5.2.5릴리즈 버전으로 변경하였음.

 ++) 자바버전은 프로젝트 properties변경해주었음.

  +++) 버전 부분을 변경 후 저장하면 자동으로 다른 스프링 dependency들도 버전이 변경됨.

 

 

 

Spring JDBC

 

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

 

 

DBCP

 

<!-- Apache commons DBCP -->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-dbcp2</artifactId>
  <version>2.7.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
  <groupId>commons-dbcp</groupId>
  <artifactId>commons-dbcp</artifactId>
  <version>1.4</version>
</dependency>

 

 

MyBatis

 

<!-- MyBatis -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.3</version>
</dependency>

<!-- Spring과 연동 -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>2.0.3</version>
</dependency>

 

 

Ojdbc (repository필수!)

 

<!-- Oracle JDBC Driver -->
<dependency>
  <groupId>com.oracle</groupId>
  <artifactId>ojdbc6</artifactId>
  <version>11.2.0.3</version>
</dependency>   

 

 

ojdbc6가 참조하는 repository추가

 

<repository><!-- JDBC를 관리하는 repository -->
  <id>oracle</id>
  <name>ORACLE JDBC Repository</name>
  <url>https://repo.spring.io/plugins-release/</url>
</repository>

 

 

Maven Repository: Search/Browse/Explore

Adopt OpenJDK API (Vanilla client) Last Release on Jun 20, 2020

mvnrepository.com

 

pom.xml 전체 코드↓

더보기
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>spring.com</groupId>
	<artifactId>mybatis</artifactId>
	<name>SpringMyBatis</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.2.5.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>   
		
		<!-- Spring JDBC -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-jdbc</artifactId>
		    <version>${org.springframework-version}</version>
		</dependency>
		
		<!-- Apache commons DBCP -->
		<dependency>
		    <groupId>org.apache.commons</groupId>
		    <artifactId>commons-dbcp2</artifactId>
		    <version>2.7.0</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
		<dependency>
		    <groupId>commons-dbcp</groupId>
		    <artifactId>commons-dbcp</artifactId>
		    <version>1.4</version>
		</dependency>
		
		<!-- MyBatis -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.5.3</version>
		</dependency>
		
		<!-- Spring과 연동 -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>2.0.3</version>
		</dependency>
		
		<!-- Oracle JDBC Driver -->
		<dependency>
		    <groupId>com.oracle</groupId>
		    <artifactId>ojdbc6</artifactId>
		    <version>11.2.0.3</version>
		</dependency>     
	</dependencies>
	
	<repositories>	
		<repository><!-- JDBC를 관리하는 repository -->
			<id>oracle</id>
			<name>ORACLE JDBC Repository</name>
			<url>https://repo.spring.io/plugins-release/</url>
		</repository>
  	</repositories>
  	
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

2. root-context.xml 작성

 

namesapces탭 클릭 - 아래 체크된 항목 체크

(안 해도 되는지....는 모르겠네요....)

 

 

resources폴더 하위 mapper, properties 패키지 생성

mybatis-config.xml파일 생성

 

 

※ jdbc.properties 작성

(필수 아님 root-context.xml파일 안에 직접 입력하는 것도 가능)

properties패키지 우클릭 - New - Other - Wizard에 file검색 - 파일명 jdbc.properties로 생성(다른 파일명 가능)

 

 

파일내용

 

 

 

작성한 파일 경로 작성

<!-- jdbc properties -->
<context:property-placeholder location="classpath:properties/jdbc.properties"/>

 

classpath는 src/main/resources를 기본 경로로 갖음.

 

만약 경로를 제대로 인식하지 못한다면?
프로젝트 우클릭 - properties - Java Build Path - Source탭 - Default output folder확인
경로가 다를경우 Browse버튼 클릭하여 경로 설정하기

 

dataSource설정

${}를 통해 jdbc.properties파일의 값을 가져옴

<!-- DBMS -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  <property name="driverClassName" value="${jdbc.driverClassName}"/>
  <property name="url" value="${jdbc.url}"/>
  <property name="username" value="${jdbc.username}"/>
  <property name="password" value="${jdbc.password}"/>
</bean>	

 


jUnit을 통해 DataSource가 잘 설정되었는지(DB연동 확인) 테스트 해보기! (필수는 아님)

jUnit?
Java에서 독립된 단위 테스트를 지원해주는 프레임워크.

 

1. pom.xml 수정 및 추가

 

-  jUnit버전 변경 (4.7 → 4.12)

 

- build path jUnit추가

프로젝트 우클릭 - Build Path - configu.. - Libraries탭 - Add Libarary

 

 

- Spring-test 추가

*mvn repository에서 복.붙 할 경우 <scope>test></scope>부분 삭제!

 

 

2. 테스트를 위한 클래스 작성 

 

경로는 test/java

package spring.com.mybatis;

import java.sql.Connection;

import javax.inject.Inject;
import javax.sql.DataSource;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/**/root-context.xml" })
public class DBConnectionTest {
	
	@Inject
	private DataSource ds;
	
	// DataSource Connection 확인
	@Test
	public void testConnection() {	
		try(Connection conn = ds.getConnection()) {
			System.out.println("DB Connection Success" + conn);
		}catch (Exception e) {
			System.out.println("DB Connection fail");
			e.printStackTrace();
		}
	}
}

 

3. jUnit 테스트 실행

 

테스트 클래스 우클릭 - Run As - jUnit Test - jUnit콘솔에서 테스트 결과 확인!

 


 

 

mybatis 세팅

 

mybatis-config.xml파일 작성(resources폴더 바로 하위)

*DOCTYPE주의! configuration임

<!-- mybatis-config.xml -->
<?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>

 

경로 주의! 오타 주의!

<!-- mybatis setting -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <property name="configLocation" value="classpath:mybatis-config.xml"></property>
  <property name="mapperLocations" value="classpath:mapper/**/*.xml"/><!-- mapper의경로 -->
</bean>

<!-- sqlSession 취득 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-arg index="0" ref="sqlSessionFactory"/>
  <constructor-arg index="1" value="SIMPLE"/><!-- SIMPLE / BATCH 모드 있음 -->
</bean>

<!-- jdbc  -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="dataSource"/>
</bean>

 


MyBatis연결 확인을 위한 jUnit테스트 코드 작성!(역시 필수는 아님)

역시 경로 확인

 

테스트 클래스 우클릭 - Run As - jUnit Test - jUnit콘솔에서 테스트 결과 확인!

 

package spring.com.mybatis;

import javax.inject.Inject;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/**/root-context.xml"})
public class MyBatisTest {
	
	@Inject
    private SqlSessionFactory sqlFactory;
    
    @Test
    public void testFactory(){
        System.out.println("sqlFactory : "+sqlFactory);
    }
    
    @Test
    public void testSession() throws Exception{
        
        try(SqlSession session = sqlFactory.openSession()){           
            System.out.println("MyBatis Connection success! session  : "+session);           
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
}

 


 

root-context.xml 전체코드 ↓

더보기
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- jdbc properties -->
	<context:property-placeholder location="classpath:properties/jdbc.properties"/>
	
	<!-- DBMS -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>	
	
	<!-- mybatis setting -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="configLocation" value="classpath:mybatis-config.xml"></property>
		<property name="mapperLocations" value="classpath:mapper/**/*.xml"/><!-- mapper의경로 -->
	</bean>
	
	<!-- sqlSession 취득 -->
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory"/>
		<constructor-arg index="1" value="SIMPLE"/><!-- SIMPLE / BATCH 모드 있음 -->
	</bean>

</beans>

 

 

+) web.xml에 인코딩 필터 추가 (한글 설정)

<filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

  <init-param>
  	<param-name>encoding</param-name>
  	<param-value>UTF-8</param-value>
  </init-param>

  <init-param>
  	<param-name>forceEncoding</param-name>
  	<param-value>true</param-value>
  </init-param>
</filter>

<filter-mapping>
  <filter-name>encodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

 


스프링 시큐리티와의 연동을 하다가.. 에러가 굉 장 히 많이 발생해서... 다시 코드 추가해봅니다...

정답은.... 공식문서다....

 

root-context.xml 전체 코드

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- jdbc properties -->
	<context:property-placeholder location="classpath:properties/jdbc.properties"/>
	<!-- DBMS -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
		<property name="initialSize" value="${jdbc.initialSize}"/>
		<property name="maxActive" value="${jdbc.maxActive}"/>
		<property name="minIdle" value="${jdbc.initialSize}"/>
		<property name="maxWait" value="3000"/>
		<property name="poolPreparedStatements" value="true"/>
		<property name="maxOpenPreparedStatements" value="50"/>
	</bean>	
	
	<!-- mybatis setting -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	  <property name="dataSource" ref="dataSource"/>
	  <property name="transactionFactory">
    	<bean class="org.apache.ibatis.transaction.managed.ManagedTransactionFactory" />
  	  </property>  
	  <property name="configLocation" value="classpath:mybatis-config.xml"></property>
	  <property name="mapperLocations" value="classpath:mapper/**/*.xml"/><!-- mapper의경로 -->
	</bean>
	
	<!-- sqlSession 취득 -->
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
	  <constructor-arg index="0" ref="sqlSessionFactory"/>
	  <constructor-arg index="1" value="SIMPLE"/><!-- SIMPLE / BATCH 모드 있음 -->
	</bean>
	
	<!-- jdbc  -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	 	<constructor-arg ref="dataSource" />
	</bean>
</beans>

 

 

mybatis-spring – MyBatis-Spring | Getting Started

Getting Started This chapter will show you in a few steps how to install and setup MyBatis-Spring and how to build a simple transactional application. Installation To use the MyBatis-Spring module, you just need to include the mybatis-spring-2.0.5.jar file

mybatis.org