페이지

2022년 4월 17일 일요일

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.

댓글 없음:

댓글 쓰기

Llama 3.2로 문장 생성 및 챗팅 완성 실습

Llama 3.2로 문장 생성 및 챗팅 완성 실습 Running Meta Llama on Linux 문서의 내용을 참고하여 Llama 3.2 1B 모델로 다음 두 가지 기능을 실습합니다. 문장 완성 챗팅 ...