ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [SPRING] SPRING게시판 (2) - DB 연동
    JAVA/SPRING 2020. 3. 10. 20:30
    728x90

    DB 생성

    pom.xml 수정

     

    <!-- pom.xml -->
    
    	<properties>
    		<java-version>1.8</java-version> <!-- 변경 -->
    		<org.springframework-version>5.1.4.RELEASE</org.springframework-version> <!-- 변경 -->
    		<org.aspectj-version>1.9.2</org.aspectj-version> <!-- 변경 -->
    		<org.slf4j-version>1.7.25</org.slf4j-version> <!-- 변경 -->
    	</properties>
        
        ...
        
    		<!-- Test -->
    		<dependency>
    			<groupId>junit</groupId>
    			<artifactId>junit</artifactId>
    			<version>4.12</version> <!-- 변경 -->
    			<scope>test</scope>
    		</dependency>
            
            <!-- 새로 추가 -->
            <!-- MySQL -->
    		<dependency>
    		    <groupId>mysql</groupId>
    		    <artifactId>mysql-connector-java</artifactId>
    		    <version>8.0.13</version>
    		</dependency>
    		
    		<!-- 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-jdbc -->
    		<dependency>
    		    <groupId>org.springframework</groupId>
    		    <artifactId>spring-jdbc</artifactId>
    		    <version>${org.springframework-version}</version>
    		</dependency>
    		
    		
    		<!-- spring-test -->
    		<dependency>
    		    <groupId>org.springframework</groupId>
    		    <artifactId>spring-test</artifactId>
    		    <version>${org.springframework-version}</version>
    		    <scope>test</scope>
    		</dependency>

    JDK버전을 변경했기 때문에 [Maven -> update project] 으로 maven 업데이트해서 적용

     

     

    DB 설정

     

    dataSource-context.xml 파일을 [src/main/resources/spring]에 생성

    <!-- resources/spring/dataSource-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:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
    	xsi:schemaLocation="
    http://mybatis.org/schema/mybatis-spring 
    http://mybatis.org/schema/mybatis-spring.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    	<!--dataSource Setting -->
    	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    		<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
    		<property name="url" value="jdbc:mysql://127.0.0.1:3306/board?useSSL=false&amp;serverTimezone=Asia/Seoul" />       
    		<property name="username" value="root"></property>
    		<property name="password" value="1111"></property>
    	</bean>  
    	
    	<!-- SqlSessionFactory Setting -->
    	<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    		<property name="dataSource" ref="dataSource" />       
    		<property name="mapperLocations" value="classpath:/mappers/**/*Mapper.xml" />
    	</bean>
    	
    	<!-- SqlSession Template Setting -->
    	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache">
    		<constructor-arg name="sqlSessionFactory" ref="SqlSessionFactory" />
    	</bean>
        
        <context:component-scan base-package="com.ms.*" />	
    </beans>
    
    • datasource : 데이터 베이스의 접속 정보를 설정
    • SqlSessionFactory : mapperLocation property는 SQL 쿼리문이 있는 위치임으로 [src/main/resources/mappers]폴더를 생성하고 boardMapper.xml을 작성
    <!-- resources/mappers/boardMapper.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.ms.board.boardMapper">
    
    </mapper>
    

     

    DB 연동 테스트

     

    // src/test/java/com/ms/board/MySqlConnectionTest.java
    
    package com.ms.board;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    
    import javax.inject.Inject;
    import javax.sql.DataSource;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.slf4j.LoggerFactory;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:spring/dataSource-context.xml"})
    public class MySqlConnectionTest {
    
    	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(MySqlConnectionTest.class);
    	
    	@Inject
    	private DataSource ds;
    	
    	@Test
    	public void testConnection() throws SQLException {
    		try(Connection con = ds.getConnection()){
    			logger.info("MySQL Connection Success : " + con);
    		}catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

     

    작성한 파일을 [우클릭 -> Run As -> Junit Test]로 실행

     

    동일한 방법으로 Mybatis도 테스트

    // src/test/java/com/ms/board/MybatisTest.java
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath:spring/dataSource-context.xml" })
    public class MybatisTest {
    	private static final Logger logger = LoggerFactory.getLogger(MybatisTest.class);
    
    	@Inject
    	private SqlSessionFactory sessionFactory;
    
    	@Test
    	public void testSessionFactory() {
    		logger.info("\n Session Factory : " + sessionFactory);
    	}
    
    	@Test
    	public void testSqlSession() {
    		try (SqlSession session = sessionFactory.openSession()){
    			logger.info("Sql Session : " + session);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    728x90
Designed by Tistory.