기본 콘텐츠로 건너뛰기

JDK 1.6 + Spring Framework 4 + MyBatis 3 사용 기초

JDK 1.6 + Spring Framework 4 + MyBatis 3 사용 기초

1. 개요

다음과 같은 환경에서 Spring Framework 4 기반의 MyBatis 3 사용 프로그램을 작성하고 빌드하여 실행할 수 있도록 안내합니다.

도구 버전 설명
Windows 10 운영체제
JDK 1.6 Java 컴파일러 및 실행 환경
IntelliJ IDEA 2021.2.2 (Community Edition) 통합 개발 환경
Maven 3.2.5 (JDK 1.6에서 동작하는 마지막 버전) 빌드 도구
Spring Framework 4.3.30.RELEASE 응용 프레임워크
MyBatis 3.4.6 DB 사용 프레임워크

2. 준비

아래 블로그 글을 참고하여 프로젝트를 생성하고 Spring Framework 4 기반 응용프로그램을 작성합니다.

3. JDBC 설정 파일 추가

3.1. jdbc.conf

#############################  
##         MySQL           ##  
#############################  
jdbc.type=1  
jdbc.driver=com.mysql.jdbc.Driver  
jdbc.url=jdbc:mysql://DB_IP:DB_PORT/DB_NAME?serverTimezone=UTC&useSSL=false  
jdbc.username=DB_USERNAME  
jdbc.password=DB_PASSWORD 
jdbc.validation.query=SELECT 1  
mybatis.mapper.location=../conf/mapper/app-mysql.xml  
  
#===========================================================  
# DATABASE SESSION CONFIG ( init; max; min )  
#===========================================================  
jdbc.init.pool.size=5  
jdbc.max.pool.size=20  
jdbc.min.pool.size=5

3.2. applicationContext.xml

<beans ...
       xmlns:context="http://www.springframework.org/schema/context"
       ...
       xsi:schemaLocation="
       ...
       http://www.springframework.org/schema/context  
       http://www.springframework.org/schema/context/spring-context.xsd
       ...>

    <context:property-placeholder properties-ref="properties" />  
  
    <bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
        <property name="locations">  
            <list>  
                <value>file:../conf/jdbc.conf</value>  
            </list>  
        </property>  
    </bean>
    ...

4. MyBatis 사용

4.1. pom.xml

<properties>  
    <spring.version>4.3.30.RELEASE</spring.version>  
    <mybatis.version>3.4.6</mybatis.version>  
    <mybatis.spring.version>1.3.3</mybatis.spring.version>  
    <hikaricp.version>2.3.13</hikaricp.version>  
    <mysql.connector.version>5.1.49</mysql.connector.version>
</properties>

<dependencies>
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-tx</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-jdbc</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.mybatis</groupId>  
        <artifactId>mybatis</artifactId>  
        <version>${mybatis.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.mybatis</groupId>  
        <artifactId>mybatis-spring</artifactId>  
        <version>${mybatis.spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>com.zaxxer</groupId>  
        <artifactId>HikariCP-java6</artifactId>  
        <version>${hikaricp.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>mysql</groupId>  
        <artifactId>mysql-connector-java</artifactId>  
        <version>${mysql.connector.version}</version> 
    </dependency>
</dependencies>

4.2. applicationContext-dataSource.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:tx="http://www.springframework.org/schema/tx"  
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans  
       http://www.springframework.org/schema/beans/spring-beans.xsd 
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">  
  
    <bean id="dataSource" class="com.example.helper.CryptoHikariDataSource" >  
        <constructor-arg index="0" ref="properties"/>  
        <property name="driverClassName" value="${jdbc.driver}"/>  
        <property name="jdbcUrl" value="${jdbc.url}"/>  
        <property name="username" value="${jdbc.username}"/>  
        <property name="password" value="${jdbc.password}"/>  
        <property name="minimumIdle" value="${jdbc.min.pool.size}"/>  
        <property name="maximumPoolSize" value="${jdbc.max.pool.size}"/>  
        <property name="connectionTestQuery" value="${jdbc.validation.query}"/>  
        <property name="leakDetectionThreshold" value="3000"/>  
    </bean>  
  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource"/>  
        <property name="configurationProperties" ref="properties"/>  
        <property name="mapperLocations">  
            <array>  
                <value>file:${mybatis.mapper.location}</value>  
            </array>  
        </property>  
        <property name="typeAliasesPackage" value="com.example.beans"/>  
    </bean>  
  
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
        <constructor-arg index="0" ref="sqlSessionFactory"/>  
    </bean>  
  
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
  
    <tx:annotation-driven transaction-manager="transactionManager" />  
  
</beans>

4.3. app-mysql.xml

<?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="app">  
  
    <select id="checkTable" parameterType="String" resultType="String">  
        SHOW TABLES LIKE #{tableName}  
    </select>  
  
</mapper>

4.4. ConsoleExecutor.java

protected void initBeanFactory() {  
    beanFactory = new ClassPathXmlApplicationContext(  
            "classpath:applicationContext.xml",  
            "classpath:applicationContext-dataSource.xml"  
    );  
}

5. App DAO 추가

5.1. applicationContext.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:task="http://www.springframework.org/schema/task"  
       xsi:schemaLocation="  
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd 
       http://www.springframework.org/schema/task 
       http://www.springframework.org/schema/task/spring-task.xsd">  
  
    <context:property-placeholder properties-ref="properties" />  
  
    <bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
        <property name="locations">  
            <list>  
                <value>file:../conf/jdbc.conf</value>  
            </list>  
        </property>  
    </bean>  
  
    <bean id="appDao" class="com.example.dao.AppDao">  
        <property name="sqlSession" ref="sqlSession"/>  
    </bean>  
  
    <bean id="messageHandler" class="com.example.handler.DefaultMessageHandler">  
        <property name="appDao" ref="appDao"/>  
    </bean>  
  
    <bean id="serviceExecutor" class="com.example.executor.ServiceExecutor">  
        <property name="messageHandler" ref="messageHandler"></property>  
    </bean>  
  
    <bean id="appScheduler" class="com.example.scheduler.AppScheduler">  
    </bean>  
  
    <task:scheduler id="scheduler" pool-size="10"/>  
    <task:scheduled-tasks scheduler="scheduler">  
        <task:scheduled ref="appScheduler" method="sayHello" fixed-delay="10000"/>  
    </task:scheduled-tasks>  
  
</beans>

5.2. AppDao.java

package com.example.dao;  
  
import org.apache.commons.lang3.StringUtils;  
import org.mybatis.spring.SqlSessionTemplate;  
  
public class AppDao {  
  
    private SqlSessionTemplate sqlSession;  
  
    public void setSqlSession(SqlSessionTemplate sqlSession) {  
        this.sqlSession = sqlSession;  
    }  
  
    public boolean checkTable(String tableName) {  
        String table = sqlSession.selectOne("app.checkTable", tableName);  
  
        return !StringUtils.isEmpty(table);  
    }  
  
}

6. App DAO 사용

6.1. DefaultMessageHandler.java

package com.example.handler;  
  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
import com.example.dao.AppDao;  
  
public class DefaultMessageHandler implements MessageHandler {  
  
    private static Logger LOGGER = LoggerFactory.getLogger(DefaultMessageHandler.class);  
  
    private AppDao appDao;  
  
    public void setAppDao(AppDao appDao) {  
        this.appDao = appDao;  
    }  
  
    @Override  
  public void handle(String message) {  
        LOGGER.info("handle: " + message);  
        boolean result = appDao.checkTable("SERVER_INFO");  
        LOGGER.info("checkTable: " + result);  
    }  
  
}

6.2. applicationContext.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:task="http://www.springframework.org/schema/task"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/task 
    http://www.springframework.org/schema/task/spring-task.xsd">  
  
    <bean id="messageHandler" class="com.example.handler.DefaultMessageHandler">  
    </bean>  
  
    <bean id="serviceExecutor" class="com.example.executor.ServiceExecutor">  
        <property name="messageHandler" ref="messageHandler"></property>  
    </bean>  
  
    <bean id="appScheduler" class="com.example.scheduler.AppScheduler">  
    </bean>  
  
    <task:scheduler id="scheduler" pool-size="10"/>  
    <task:scheduled-tasks scheduler="scheduler">  
        <task:scheduled ref="appScheduler" method="sayHello" fixed-delay="10000"/>  
    </task:scheduled-tasks>  
  
</beans>

Written with StackEdit.

댓글

이 블로그의 인기 게시물

Windows에 AMP와 MediaWiki 설치하기

1. 들어가기     AMP는 Apache + MySQL +  Perl/PHP/Python에 대한 줄임말이다. LAMP (Linux + AMP)라고 하여 Linux에 설치하는 것으로 많이 소개하고 있지만 Windows에서도 간편하게 설치하여 사용할 수 있다.       이 글은 Windows 7에 Apache + MySQL + PHP를 설치하고 그 기반에서 MediaWiki를 설치하여 실행하는 과정을 간략히 정리한 것이다. 2. MySQL     * 버전 5.6.12     1) 다운로드         http://dev.mysql.com/downloads/installer/         MySQL Installer 5.6.12         Windows (x86, 32-bit), MSI Installer         (mysql-installer-web-community-5.6.12.0.msi)     2) 다운로드한 MSI 파일을 더블클릭하여 설치를 진행한다.           설치 위치:                   C:\Program Files\MySQL               선택 사항:                       Install MySQL Products             Choosing a Se...

MATLAB Rutime 설치하기

MATLAB Rutime 설치하기 미설치시 에러 MATLAB Runtime 을 설치하지 않은 환경에서 MATLAB 응용프로그램이나 공유 라이브러리를 사용하려고 하면 아래와 같은 에러 메시지가 표시될 것입니다. 처리되지 않은 예외: System.TypeInitializationException: 'MathWorks.MATLAB.NET.Utility.MWMCR'의 형식 이니셜라이저에서 예 외를 Throw했습니다. ---> System.TypeInitializationException: 'MathWorks.MATLAB.NET.Arrays.MWArray'의 형식 이니셜라이저에서 예외를 Throw했습니다. ---> System.DllNotFoundException: DLL 'mclmcrrt9_3.dll'을(를) 로드할 수 없습니다. 지정된 모듈을 찾을 수 없습니다. (예외가 발생한 HRESULT: 0x8007007E) 위치: MathWorks.MATLAB.NET.Arrays.MWArray.mclmcrInitialize2(Int32 primaryMode) 위치: MathWorks.MATLAB.NET.Arrays.MWArray..cctor() --- 내부 예외 스택 추적의 끝 --- 위치: MathWorks.MATLAB.NET.Utility.MWMCR..cctor() --- 내부 예외 스택 추적의 끝 --- 위치: MathWorks.MATLAB.NET.Utility.MWMCR.processExiting(Exception exception) 해결 방법 이 문제를 해결하기 위해서는 MATLAB Runtime 을 설치해야 합니다. 여러 가지 방법으로 MATLAB Runtime 을 설치할 수 있습니다. MATLAB 이 설치되어 있는 경우에는 MATLAB 설치 폴더 아래에 있는 MATLAB Runtime 설치 프로그램을 실행하여 설치합니다. ...

Wi-Fi 카드 2.4GHz로만 동작시키기

Wi-Fi 카드 2.4GHz로만 동작시키기 별도의 Wi-Fi AP 장치를 두지 않고 아래와 같은 기기들로만 Wi-Fi 네트워크를 구성하고자 할 때 주변 기기들이 2.4GHz만 지원하기 때문에 PC에서 실행하는 AP가 항상 2.4GHz를 사용하도록 Wi-Fi 카드를 설정해 주어야 합니다. 기기 Wi-Fi 카드 주파수 대역 Wi-Fi Direct 지원 PC (Windows 10) 2.4GHz, 5GHz O 주변 기기들 2.4GHz X Wi-Fi 카드별 주파수 대역 선택 방법 Windows 시작 메뉴에서 설정 을 클릭합니다. Windows 설정 화면에서 네트워크 및 인터넷 을 클릭합니다. 설정 화면의 왼쪽 메뉴바에서 Wi-Fi 를 클릭합니다. 화면 오른쪽 관련 설정 구역에 있는 어댑터 옵션 변경 을 클릭합니다. 설정을 바꾸고자 하는 Wi-Fi 카드 항목을 선택하고 마우스 오른쪽을 누른 다음 속성 메뉴를 클릭합니다. 대화상자의 네트워킹 탭 화면에 있는 구성 버튼을 클릭합니다. 장치 속성 대화상자의 고급 탭 화면으로 이동합니다. 제시되는 속성 항목들은 제품별로 다르며 자세한 사항은 아래의 제품별 설명을 참고하여 값을 설정하시기 바랍니다. Intel Dual Band Wireless-AC 7265 기술 사양 주파수 대역: 2.4GHz, 5GHz 무선 표준: 802.11ac 주파수 대역 선택 장치 속성 대화상자에서 아래와 같이 선택합니다. Wireless Mode 1. 802.11a => 5GHz 4. 802.11b/g => 2.4GHz (이 항목 선택) 6. 802.11a/b/g => 2.4GHz, 5GHz Intel Dual Band Wireless-AC 8265 기술 사양 주파수 대역: 2.4GHz, 5GHz 무선 표준: 802.11ac 주파수 대역 선택 장치 속성 대화상자에서 아래와 같이 ...