ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [전자정부 프레임워크] eGovframework 웹 어플리케이션 개발_04 전자정부 프레임워크 MariaDB 연동 하기!!
    Java/전자정부 프레임워크 2019. 7. 8. 22:19
    반응형

    저번 시간에는 Sample project를 생성하여 /test/hello.do라는 요청이 들어오면

    화면에 Hello World라는 String을 출력해보았다

     

    이번 시간에는 저번 시간에 생성한 프로젝트에 무료 DataBase인 MariaDB를 연동하여

    본격적으로 Web Project를 시작해 보려고 한다.

     

     

    기본적으로 MariaDB는 설치되어있다는 가정하에 진행하도록 하겠다.

     

     

     

    먼저 pom.xml 파일을 수정한다.

    Sample project를 생성하면 기본적으로 메모리 DB와 연동되어있으며

    pom.xml에 아래와같이 다른 DB 연동 관련 dependency가 주석 처리되어 생성되어있을 것이다.

     

     

     

     

     

     

    이제 여기서 우리는 기존에 추가되어있는 메모리 DB dependency를 제거하고 기존에 주석 처리되어있던 4개 dependency 중 log4jdbc와 mysql-connector-java는 살려주시고 나머지 2개 dependency는 삭제해준 뒤

    마지막으로 MariaDB 연동을 위한 dependency를 추가해 준다.

     

     

     

     

    <!-- 아래의 메모리DB dependency는 삭제 -->
    <dependency>
    	<groupId>org.hsqldb</groupId>
    	<artifactId>hsqldb</artifactId>
    	<version>2.3.2</version>
    </dependency>
    
    <!-- 사진에서 주석으로 막혀있던 dependency중 아래 2개는 삭제 -->
    <dependency>
    	<groupId>ojdbc</groupId>
    	<artifactId>ojdbc</artifactId>
    	<version>14</version>
    	<scope>system</scope>
    	<systemPath>${basedir}/src/main/webapp/WEB-INF/lib/ojdbc-14.jar</systemPath>
    </dependency>
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>
    
    
    
    
    <!-- 주석으로 막혀있던 dependency중 아래 2개는 유지 -->
    <dependency>
        <groupId>com.googlecode.log4jdbc</groupId>
        <artifactId>log4jdbc</artifactId>
        <version>1.2</version>
        <exclusions>
            <exclusion>
                <artifactId>slf4j-api</artifactId>
                <groupId>org.slf4j</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
    	<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<version>5.1.31</version>
    </dependency>
    
    
    
    <!-- MariaDB 연동을 위해 아래 dependency 추가 -->
    <dependency>
    	<groupId>org.mariadb.jdbc</groupId>
        	<artifactId>mariadb-java-client</artifactId>
        	<version>2.4.1</version>
    </dependency>

     

     

     

    context-datasource의 설정도 수정해야한다.

    datasource에도 마찬가지로 메모리DB와 연동이 되어있다.

    이것을 MariaDB로 바꿔주어야 한다.

    기존 설정을 날려주고 아래의 bean을 등록한다.

     

      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="org.mariadb.jdbc.Driver"/>
            <property name="url" value="jdbc:mariadb://127.0.0.1:3306/maria_test" />
            <property name="username" value="root"/>
            <property name="password" value="password"/>
        </bean>
    
    

    여기서 url username password를 각자 DB의 설정을 넣어준다.

     

     

     

     

    context-datasource의 최종 모습

     

     

     

     

    또한 우리는 Sample Project를 생성하여 basePackage를 변경하였으니

    context-aspect.xml와 context-mapper.xml 파일도 수정해줘야 한다.

     

     

     

     

    먼저 context-aspect의 aop:config에서 기본 egovframework로 잡혀있던 것을

    아래와 같이 변경해준다. 

    물론 현재 진행하고 계신 프로젝트에 맞도록 변경해주시면 된다.

    	<aop:config>
    		<aop:pointcut id="serviceMethod" expression="execution(* JayPrj.*.service.impl.*Impl.*(..))" />
    		<aop:aspect ref="exceptionTransfer">
    			<aop:after-throwing throwing="exception" pointcut-ref="serviceMethod" method="transfer" />
    		</aop:aspect>
    	</aop:config

     

     

     

     

    여기서 잠깐 저의 프로젝트 package구조를 보면

    아래와 같다.

     

     

     

     

     

     

     

     

     

    다음은 context-mapper.xml도 마찬가지로 basePackage를 아래와 같이 변경한다.

    이것 또한 진행하고 계신 프로젝트에 맞게 변경하면 된다.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    
    	<!-- SqlSession setup for MyBatis Database Layer -->
    	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
    		<property name="dataSource" ref="dataSource" />
    		<property name="configLocation" value="classpath:/egovframework/sqlmap/example/sql-mapper-config.xml" />
    		<property name="mapperLocations" value="classpath:/egovframework/sqlmap/example/mappers/*.xml" />
    	</bean>
    
    	<!-- MapperConfigurer setup for MyBatis Database Layer with @Mapper("deptMapper") in DeptMapper Interface -->
     	<bean class="egovframework.rte.psl.dataaccess.mapper.MapperConfigurer">
    		<property name="basePackage" value="JayPrj.*.mapper" />
    	</bean>
        
    </beans>
    

     

     

    이제 MariaDB와의 연동 세팅은 끝났다.

    자 이제 본격적으로 DB에서 데이터를 읽어와 보자!!!

    간단히 User에게 요청을 받아 단순히 DB table에서 Select만 해오도록 하겠다.

     

     

     

     

     

     

    먼저 VO를 생성한다.

    모두 String type으로 간단하게 test, ID, name 3개만 넣어주겠다.

    DB에도 마찬가지로 위의 3개의 column test, ID, name을 생성하여 적당히 값을 넣어준다.

     

     

     

     

     

     

     

     

     

     

    Controller

    @RestController
    @RequestMapping("/test")
    public class testHelloWorld {
    
    
    	@Resource(name = "testHelloWorldService")
    	private testHelloWorldService testService;
    
    	
    	@RequestMapping("/hello.do")
    	public @ResponseBody String HelloWorldTest() {
    		
    		return "Hello World!!";
    	}
    	
    	@RequestMapping("/testDB.do")
    	public @ResponseBody String testDB() throws Exception{
    	
    		return testService.testDB();
    	}
    	
    
    }
    
    

    (사용자에게 /test/testDB.do라는 요청을 받아 testHelloWorldService에 선언되어있는 testDB()메서드를 실행한다.)

     

     

     

     

    service

    public interface testHelloWorldService {
    
    	String testDB() throws Exception;
    
    }

     

     

     

     

     

    serviceImpl

    @Service("testHelloWorldService")
    public class testHelloWorldServicImpl extends EgovAbstractServiceImpl implements testHelloWorldService{
    
    	@Resource(name="testHelloWorldMapper")
    	private testHelloWorldMapper testMapper;
    
    	@Override
    	public String testDB() throws Exception{
    
    		List<testHelloWorldVo> data =  testMapper.testDB();
    		return data.get(0).getTest();
    	}
    }
    

    testHelloWorldMapper에 선언되어있는 testDB()라는 메소드를 실행시켜 return 되는 값을

    위에서 생성한 vo class의 List로 받아 그중에 첫 번째 test의 값을 return 한다. 

     

     

     

     

     

     

    mapper

    @Mapper("testHelloWorldMapper")
    public interface testHelloWorldMapper {
    	
    	List<testHelloWorldVo> testDB() throws Exception;
    }
    <?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="JayPrj.testPkg.mapper.testHelloWorldMapper">
    
    	<select id="testDB" resultType="JayPrj.testPkg.vo.testHelloWorldVo">
    		SELECT *
    		FROM sample         
    	</select>	
    </mapper>
    

     

     

     

     

    모든 코딩이 끝났다.

    이제 테스트해보자.

     

     

     

     

     

     

     

     

     

    첫 번째 Row의 test값 t1이 정상적으로 출력된다.

     

    오늘은 여기까지 MariaDB의 연동과 간단히 DB에서 데이터를 Select 해오는 것을 해보았습니다.

     

    다음에는 file 등의 upload download delete 처리를 해보도록 하겠습니다.

    읽어주셔서 감사합니다.

    반응형
Designed by Tistory.