8. Spring-myBatis-oracle 연동 및 연결 확인 테스트

1. MyBatis 라이브러리 추가

   - 아래 링크 참조

   - https://github.com/mybatis/mybatis-3/releases

   - https://mybatis.org/mybatis-3/ko/getting-started.html

 

MyBatis – 마이바티스 3 | 시작하기

Copyright © 2009–2021MyBatis.org. .

mybatis.org

 

Releases · mybatis/mybatis-3

MyBatis SQL mapper framework for Java. Contribute to mybatis/mybatis-3 development by creating an account on GitHub.

github.com

 

   - maven 사용 시 pom.xml에 추가

<!-- ************************************************************ -->
<!-- myBatis 관련 -->
<!-- ************************************************************ -->

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.9</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.7</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-dbcp2</artifactId>
    <version>2.9.0</version>
</dependency>

<!-- ************************************************************ -->

<!-- ************************************************************ -->
<!-- annotation -->
<!-- ************************************************************ -->

<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>

<!-- ************************************************************ -->

 

2. root-context.xml 파일 설정

   - Namespace에서 아래 항목 체크 확인

   - root-context.xml : 모든 서블릿이 공유할 수 있는 bean들의 설정 집합

   - AOP(Aspect Oriented Programming) : 관점 지향 프로그래밍. 핵심적인, 부가적인 관점을 기준으로 모듈화.

   - beans : Spring에 의해 생성되고 관리되는 자바 객체들의 집합

   - context : 웹 상에서의 환경설정

   - myBatis : JDBC를 통해 DB에 엑세스하는 작업을 캡슐화, mapping 지원 및 매개 변수의 중복작업 제거

   - Source에서 아래 코드 입력

<context:property-placeholder location="classpath:config/db.properties"/>

<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="${db.driver}"/>
    <property name="url" value="${db.host}"/>
    <property name="username" value="${db.username}"/>
    <property name="password" value="${db.password}"/>
</bean>

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

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

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.study.testapp" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache">
    <constructor-arg index="0" ref="sqlSessionFactory" />
</bean>

 

3. 폴더 및 파일 생성

   - Folder 생성 : src/main/resources > config

   - Folder 생성 : src/main/resources > mappers

   - 파일 생성 : src/main/resources > config > db.propertes

   - xml 생성 : src/main/resources > config > mybatis-config.xml

   - db.properties

db.driver=oracle.jdbc.driver.OracleDriver
db.host=jdbc:oracle:thin:@255.255.255.255:1521:orcl
db.username=id입력
db.password=password입력

 

   - 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>

 

4. mybatis를 이용한 세션 연결 확인 테스트

   - 세션 연결 확인 테스트 junit으로 테스트 시 Session null 오류 발생

   - 컨트롤러에서 작성, 톰캣 서버 가동 후 테스트

package com.hhkim.homepage;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.inject.Inject;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@Inject
	private SqlSessionFactory sqlFactory;
		
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
				
		try(SqlSession session = sqlFactory.openSession()){
			System.out.println("세션 확인 : " + session);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		return "home";
	}
	
	
}

 

5. 결과 확인

   - 주소창 : http://localhost:8080/homepage/ 입력 시 아래와 같은 로그 확인

'Server > Spring(구버전)' 카테고리의 다른 글

10. logback 설정  (0) 2022.03.31
9. Controller - Service - Query 연동 및 테스트  (0) 2022.03.31
7. Oracle DB (JDBC) Web Server 연동 (JUnit Test)  (0) 2022.03.29
6. 자바 버전 변경  (0) 2022.03.29
5. UTF-8 설정  (0) 2022.03.28