3탄) 전자정부프레임워크 + spring legacy MVC + Oracle 프로젝트
3탄에서는 프로젝트와 Database를 연결하는 실습을 해보겠습니다.
이번 실습에서는
프로젝트는 2탄에서 완성한 프로젝트,
Database는 Oracle 11gR2 Express를 사용할 것입니다.
1. Database 설치
아래 페이지에서 설치파일을 다운 받아 설치를 진행해주시면 되겠습니다.
https://www.oracle.com/database/technologies/xe-prior-releases.html
2. Database 계정 생성 및 권한 부여
Oracle 이 설치되었다면 계정을 생성하고 접근 권한을 부여하자
SQL CLI를 실행하여, 다음과 같이 입력하면 test 계정이 생성됩니다
1
2
3
|
CONN /AS SYSDBA;
CREATE USER test IDENTIFIED BY test;
GRANT CONNECT, RESOURCE, DBS TO test;
|
3. 프로젝트와 Database 연동(connection)
프로젝트와 Database를 연동하기 위해서는 ojdbc 드라이버가 필요합니다.
아래 페이지에서 드라이버를 다운받아
https://www.oracle.com/database/technologies/jdbcdriver-ucp-downloads.html
lib 경로에 넣어두겠습니다.
그리고 pom.xml 에 oracle jdbc, test관련 의존성(라이브러리)을 추가합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<dependency>
<groupId>ojdbc</groupId>
<artifactId>ojdbc</artifactId>
<version>6</version>
<scope>system</scope>
</dependency>
<dependency>
<version>1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.2.RELEASE</version>
<scope>test</scope>
</dependency>
|
4. JUnit을 활용한 connection test
이런 과정이 잘 진행되었는지 JUnit을 활용하여 Test를 진행해보겠습니다.
Build Path에 JUnit4 라이브러리도 추가합니다.

준비가 되었다면 JUnit 소스로 db와 연결이 잘되는지 테스트를 해봅시다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package example;
import java.sql.Connection;
import java.sql.DriverManager;
import org.junit.Test;
public class ConnTester {
private static final String URL ="jdbc:oracle:thin:@127.0.0.1:1521:xe";
private static final String USER ="test";
private static final String PW ="test";
@Test
public void testConnect() throws Exception{
Class.forName(DRIVER);
try(Connection con = DriverManager.getConnection(URL, USER, PW)){
System.out.println(con);
}catch(Exception e) {
e.printStackTrace();
}
}
}
|
성공했다면 다음과 같은 결과를 얻을 것입니다.
만약 커넥션 예외가 발생한다면, Build path에서 ojdbc lib가 잘 추가되었는지 확인해봅시다.
5. MyBatis 연결하기
MyBatis 실습을 위한 프로젝트 구성은 다음과 같습니다.
하이라이트된 부분이 해당 실습의 주요 구성 요소입니다.
우선 xml Config 부터 먼저 살펴보겠습니다.
context-datasource.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:xe"></property>
<property name="username" value="test"></property>
<property name="password" value="test"></property>
</bean>
</beans>
|
context-sqlMap.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?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-3.2.xsd">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:/egovframework/sqlmap/example/sql-mapper-config.xml" />
<property name="mapperLocations">
<list>
</list>
</property>
</bean>
</beans>
|
context-mapper.xml
1
2
3
4
5
6
7
8
9
10
11
|
<?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">
<property name="basePackage" value="egovframework.example"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
|
sample-mapper-config.xml
1
2
3
4
5
6
7
8
9
10
11
|
<?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>
<typeAliases>
</typeAliases>
</configuration>
|
SampleMapper.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<?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">
<select id="selectSampleList" parameterType="searchVO" resultType="egovMap">
SELECT
ID, NAME, DESCRIPTION, USE_YN, REG_USER
FROM SAMPLE
<if test="searchKeyword != null and searchKeyword != ''">
WHERE 1=1
<choose>
<when test="searchCondition == 0">
AND ID LIKE '%' || #{searchKeyword} || '%'
</when>
<when test="searchCondition == 1">
AND NAME LIKE '%' || #{searchKeyword} || '%'
</when>
</choose>
</if>
ORDER BY ID ASC
<!-- LIMIT #{recordCountPerPage} OFFSET #{firstIndex} -->
</select>
</mapper>
|
DTO는 전자정부 sample 프로젝트 기존의 SampleDefaultVO, SampleVO 소스를 사용하면 되며,
다음은 MVC 서비스 소스를 확인해보겠습니다.
EgovSampleService.java, 서비스 인터페이스
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
import java.util.List;
public interface EgovSampleService {
/**
* 글을 등록한다.
* @param vo - 등록할 정보가 담긴 SampleVO
* @return 등록 결과
* @exception Exception
*/
String insertSample(SampleVO vo) throws Exception;
/**
* 글을 수정한다.
* @param vo - 수정할 정보가 담긴 SampleVO
* @return void형
* @exception Exception
*/
void updateSample(SampleVO vo) throws Exception;
/**
* 글을 삭제한다.
* @param vo - 삭제할 정보가 담긴 SampleVO
* @return void형
* @exception Exception
*/
void deleteSample(SampleVO vo) throws Exception;
/**
* 글을 조회한다.
* @param vo - 조회할 정보가 담긴 SampleVO
* @return 조회한 글
* @exception Exception
*/
SampleVO selectSample(SampleVO vo) throws Exception;
/**
* 글 목록을 조회한다.
* @param searchVO - 조회할 정보가 담긴 VO
* @return 글 목록
* @exception Exception
*/
List<?> selectSampleList(SampleDefaultVO searchVO) throws Exception;
/**
* 글 총 갯수를 조회한다.
* @param searchVO - 조회할 정보가 담긴 VO
* @return 글 총 갯수
* @exception
*/
int selectSampleListTotCnt(SampleDefaultVO searchVO);
}
|
EgovSampleServiceImpl.java, 서비스 구현부
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service("sampleService")
public class EgovSampleServiceImpl extends EgovAbstractServiceImpl implements EgovSampleService {
private static final Logger LOGGER = LoggerFactory.getLogger(EgovSampleServiceImpl.class);
@Resource(name="sampleMapper")
private SampleMapper sampleMapper;
/** ID Generation */
@Resource(name = "egovIdGnrService")
private EgovIdGnrService egovIdGnrService;
@Override
public String insertSample(SampleVO vo) throws Exception {
LOGGER.debug(vo.toString());
/** ID Generation Service */
String id = egovIdGnrService.getNextStringId();
LOGGER.debug(vo.toString());
sampleMapper.insertSample(vo);
return id;
}
@Override
public void updateSample(SampleVO vo) throws Exception {
sampleMapper.updateSample(vo);
}
@Override
public void deleteSample(SampleVO vo) throws Exception {
sampleMapper.deleteSample(vo);
}
@Override
public SampleVO selectSample(SampleVO vo) throws Exception {
SampleVO resultVO = sampleMapper.selectSample(vo);
if (resultVO == null)
throw processException("info.nodata.msg");
return resultVO;
}
@Override
public List<?> selectSampleList(SampleDefaultVO searchVO) throws Exception {
List<?> result=sampleMapper.selectSampleList(searchVO);
LOGGER.debug(result.toString());
return result;
}
@Override
public int selectSampleListTotCnt(SampleDefaultVO searchVO) {
return sampleMapper.selectSampleListTotCnt(searchVO);
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
SampleMapper.java, myBatis 매퍼인터페이스
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import java.util.List;
@Mapper("sampleMapper")
public interface SampleMapper {
void insertSample(SampleVO vo) throws Exception;
void updateSample(SampleVO vo) throws Exception;
void deleteSample(SampleVO vo) throws Exception;
SampleVO selectSample(SampleVO vo) throws Exception;
List<?> selectSampleList(SampleDefaultVO searchVO) throws Exception;
int selectSampleListTotCnt(SampleDefaultVO searchVO);
}
|
이하 소스가 준비되었다면, JUnit으로 잘 동작하는지 Test를 진행해보겠습니다.
BatisTester.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
package example;
import java.sql.Connection;
import java.util.List;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ={
"classpath:/egovframework/spring/context-*.xml",
"classpath:/egovframework/sqlmap/example/sql-mapper-config.xml",
"classpath:/egovframework/sqlmap/example/mappers/*Mapper.xml",
})
public class BatisTester {
private static final Logger LOGGER = LoggerFactory.getLogger(BatisTester.class);
@Inject
private DataSource ds;
@Test
public void dsTest()throws Exception {
Connection con = ds.getConnection();
System.out.println("JUnit-dsConnection: " + con);
}
SampleDefaultVO searchVO;
@Resource(name="sampleMapper")
private SampleMapper sampleMapper;
@Before
public void init() throws Exception {}
@Test
@Transactional
@Rollback(true)
public void dbTest() throws Exception {
List<?> result=sampleMapper.selectSampleList(searchVO);
System.out.println("JUnit-dbQuery: " + result);
}
}
|
성공했다면 다음과 같은 결과를 얻을 것입니다.
그러면 실제 서버에 적용해보기 위해 Controller와 view를 추가해보겠습니다.
EgovSampleController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
@Controller
public class EgovSampleController {
@Resource(name = "sampleService")
EgovSampleService egovSampleService;
@RequestMapping(value = "/egovSampleList.do")
public String selectSampleList(SampleDefaultVO sampleDefaultVO,
ModelMap modelMap) throws Exception {
sampleDefaultVO = new SampleDefaultVO();
List<?> dbData = egovSampleService.selectSampleList(sampleDefaultVO);
modelMap.addAttribute("dbData", dbData);
return "sample/egovSampleList";
}
}
|
webapp/WEB-INF/jsp/egovframework/example/sample/
egovSampleList.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javaScript" language="javascript" defer="defer">
</script>
</head>
<body style="text-align:center; margin:0 auto; display:inline; padding-top:100px;">
리스트
${dbData}
</body>
</html>
|
cs |
여기까지 하셨다면 Ctrl + F11 하여 출력 결과를 알아보겠습니다.
아래와 같이 출력되었다면 오늘 실습은 성공적으로 마치셨습니다. 수고하셨습니다~
다음 4탄에서는 end point에서 CURD 가 가능하도록 프로젝트를 완성해보겠습니다.