본문 바로가기
IT/Spring Project

[Spring Project] - 스프링 프로젝트 메이븐(Maven) 기반 Spring 프로젝트 생성(스프링 + 오라클(Oracle) + Mybatis) 연동 하는 방법

by 차이나는 개발자 2022. 3. 1.
728x90
반응형

#스프링 프로젝트 메이븐(Maven) 기반 Spring 프로젝트 생성(스프링 + 오라클(Oracle) + Mybatis) 연동 하는 방법

 

 

1.Mybatis 관련 라이브러리를 추가합니다.

 

1-1. pom.xml 설정

<!-- Mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>
<!-- Mybatis + Spring -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.2</version>
</dependency>
<!-- Spring 트랜잭션 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.0.7.RELEASE</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.0.7.RELEASE</version>
</dependency>

 

 

1-2. Mybatis 핵심 객체 SQLSession, SQLSessionFactory 추가합니다.

-DataSourceConfig.java

package com.spring.web.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

@Configuration
public class DataSourceConfig {

	@Bean
	public DataSource dataSource(){
		HikariConfig hikariConfig = new HikariConfig();
		hikariConfig.setDriverClassName("oracle.jdbc.driver.OracleDriver");
		hikariConfig.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:XE");
		hikariConfig.setUsername("book_ex");
		hikariConfig.setPassword("book_ex");
		
		HikariDataSource dataSource = new HikariDataSource(hikariConfig);
		
		return dataSource;
	}
	
	
	// Mybatis 객체
	@Bean
	public SqlSessionFactory sqlSessionFactory() throws Exception {
		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(dataSource());
		return (SqlSessionFactory) sqlSessionFactory.getObject();
	}
	
}

 

 

1-3. Mybatis 연결 테스트 코드를 작성합니다.

-MybatisTest.java

package com.spring.web.test;

import static org.junit.Assert.fail;

import java.sql.Connection;

import javax.sql.DataSource;

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

import com.spring.web.config.DataSourceConfig;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {DataSourceConfig.class})
@Slf4j
public class MybatisTest {

	@Setter(onMethod_ = { @Autowired })
	private DataSource dataSource;
	
	@Setter(onMethod_ = { @Autowired })
	private SqlSessionFactory sqlSessionFactory;
	
	@Test 
	public void testMybatisConnect(){
		try(SqlSession session = sqlSessionFactory.openSession();
				Connection con = session.getConnection()) {
			log.info("session= " + session);
			log.info("con= " + con);
		} catch (Exception e) {
			fail(e.getMessage());
		}
	}
}

 

 

1-4. 컨트롤키 + F11 JUnit Test 실행 후 결과를 확인합니다.

 

 

2. 스프링과 연동 처리(Mapper 인터페이스 사용)

 

2-1. 추가 되는 파일 구조

 

 

2-2. RootConfig.java

-MapperScan 어노테이션을 추가합니다.

package com.spring.web.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

// root-context.xml 대체 클래스
@Configuration // 설정 클래스임을 명시
@ComponentScan(basePackages = {"com.spring.web"} ) // 해당 패키지 스캔 의존성 주입
@MapperScan(basePackages = {"com.spring.web.mapper"} ) // Mybatis Mapper 스캔
public class RootConfig {

}

 

 

2-3. Mapper 인터페이스 생성 후 @Select 어노테이션을 사용해서 현재시간 조회 쿼리 생성입니다.

package com.spring.web.mapper;

import org.apache.ibatis.annotations.Select;

public interface MybatisMapper {

	@Select("SELECT sysdate FROM dual")
	public String getTime();
	
}

 

 

2-4. 테스트 코드를 작성합니다.

package com.spring.web.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.spring.web.config.RootConfig;
import com.spring.web.mapper.MybatisMapper;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {RootConfig.class})
@Slf4j
public class MybatisMapperTest {
	
	@Setter(onMethod_ = { @Autowired })
	private MybatisMapper mybatisMapper;
	
	@Test 
	public void testGetTime(){
		log.info(mybatisMapper.getClass().getName());
		log.info(mybatisMapper.getTime());
	}
}

 

 

2-5. 결과를 확인합니다.

 

 

3. Mybatis + XML 사용

 

3-1. MybatisMapper 인터페이스에 getTime2 메서드를 추가합니다.

package com.spring.web.mapper;

import org.apache.ibatis.annotations.Select;

public interface MybatisMapper {

	@Select("SELECT sysdate FROM dual")
	public String getTime();
	
	public String getTime2();
	
}

 

 

3-2. MybatisMapperTest.java

-testGetTime2() 메서드를 추가합니다.

package com.spring.web.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.spring.web.config.RootConfig;
import com.spring.web.mapper.MybatisMapper;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {RootConfig.class})
@Slf4j
public class MybatisMapperTest {
	
	@Setter(onMethod_ = { @Autowired })
	private MybatisMapper mybatisMapper;
	
	@Test 
	public void testGetTime(){
		log.info(mybatisMapper.getClass().getName());
		log.info(mybatisMapper.getTime());
	}
	
	@Test
	public void testGetTime2(){
		log.info("getTime2");
		log.info(mybatisMapper.getTime2());
	}
	
}

 

 

3-3. xml 파일 추가(Mapper 인터페이스명 = 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="com.spring.web.mapper.MybatisMapper">

	<select id="getTime2" resultType="string">
		SELECT sysdate FROM dual
	</select>

</mapper>

 

 

3-4. 결과를 확인합니다.

 

 

 

728x90
반응형

댓글