반응형

전자정부프레임워크에서 데이터베이스를 연동하는 방법을 학습합니다. 데이터베이스는 애플리케이션의 핵심 데이터를 저장하는 중요한 구성 요소입니다. MySQL 또는 Oracle과 같은 데이터베이스를 프로젝트와 연동하기 위한 설정 방법을 단계별로 설명하겠습니다.


1. 데이터베이스 준비

1-1. 데이터베이스 설치

  • MySQL, Oracle, 또는 다른 DBMS를 설치합니다.
  • MySQL 예제:

1-2. 샘플 데이터베이스 생성

  1. 데이터베이스 생성 SQL 실행
    • MySQL 기준:
      CREATE DATABASE egov_sample CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
      
  2. 테이블 생성
    • 전자정부프레임워크에서 제공하는 SQL 파일을 실행하여 샘플 테이블을 만듭니다.
    • 위치: src/main/resources/sql/
    CREATE TABLE SAMPLE (
        ID INT AUTO_INCREMENT PRIMARY KEY,
        NAME VARCHAR(100),
        DESCRIPTION TEXT
    );
    INSERT INTO SAMPLE (NAME, DESCRIPTION) VALUES ('Test', 'This is a test entry.');
    

2. 데이터베이스 드라이버 추가

전자정부프레임워크는 데이터베이스와 통신하기 위해 드라이버가 필요합니다.

2-1. Maven에 드라이버 의존성 추가

pom.xml 파일에서 사용하는 DBMS에 맞는 드라이버를 추가합니다.

MySQL 드라이버 예제:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.33</version>
</dependency>

Oracle 드라이버 예제:

<dependency>
    <groupId>com.oracle.database.jdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <version>21.9.0.0</version>
</dependency>

Maven 프로젝트를 업데이트하여 드라이버를 다운로드합니다.


3. 데이터 소스 설정

3-1. context-datasource.xml 수정

Spring에서 데이터베이스 연결 정보를 관리하기 위해 context-datasource.xml 파일을 설정합니다.

MySQL 설정 예시:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/egov_sample?useSSL=false&serverTimezone=UTC" />
    <property name="username" value="root" />
    <property name="password" value="your_password" />
</bean>

Oracle 설정 예시:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
    <property name="username" value="system" />
    <property name="password" value="oracle" />
</bean>

3-2. context-transaction.xml 수정

트랜잭션 관리를 위해 데이터 소스를 등록합니다.

<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

4. MyBatis 연동 설정

전자정부프레임워크는 MyBatis를 기본 ORM으로 사용합니다.

4-1. Mapper XML 파일 생성

src/main/resources/mappers/ 디렉토리에 MyBatis 매퍼 파일을 생성합니다.

SampleMapper.xml:

<mapper namespace="egovframework.example.sample.service.impl.SampleMapper">
    <select id="selectSampleList" resultType="egovframework.example.sample.service.SampleVO">
        SELECT ID, NAME, DESCRIPTION FROM SAMPLE
    </select>
</mapper>

4-2. context-mapper.xml 설정

MyBatis 매퍼 파일을 등록합니다.

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

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="egovframework.example.sample.service.impl" />
</bean>

5. DAO 및 Service 구현

5-1. DAO 생성

SampleDAO.java 파일 작성:

@Repository("sampleDAO")
public class SampleDAO {
    @Autowired
    private SqlSession sqlSession;

    public List<SampleVO> selectSampleList() throws Exception {
        return sqlSession.selectList("egovframework.example.sample.service.impl.SampleMapper.selectSampleList");
    }
}

5-2. Service 구현

SampleServiceImpl.java 파일 작성:

@Service("sampleService")
public class SampleServiceImpl implements SampleService {

    @Resource(name = "sampleDAO")
    private SampleDAO sampleDAO;

    @Override
    public List<SampleVO> selectSampleList() throws Exception {
        return sampleDAO.selectSampleList();
    }
}

6. 테스트 및 실행

6-1. Controller 작성

@Controller
public class SampleController {

    @Resource(name = "sampleService")
    private SampleService sampleService;

    @RequestMapping("/sample/list.do")
    public String selectSampleList(Model model) throws Exception {
        List<SampleVO> sampleList = sampleService.selectSampleList();
        model.addAttribute("sampleList", sampleList);
        return "sample/sampleList";
    }
}

6-2. JSP 작성

/webapp/WEB-INF/views/sample/sampleList.jsp:

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>NAME</th>
            <th>DESCRIPTION</th>
        </tr>
    </thead>
    <tbody>
        <c:forEach var="sample" items="${sampleList}">
            <tr>
                <td>${sample.id}</td>
                <td>${sample.name}</td>
                <td>${sample.description}</td>
            </tr>
        </c:forEach>
    </tbody>
</table>

6-3. 실행 확인

  • URL: http://localhost:8080/sample/list.do
  • 브라우저에서 샘플 데이터가 출력되면 데이터베이스 연동이 성공적으로 설정된 것입니다.

마무리

전자정부프레임워크 프로젝트와 데이터베이스를 연동하는 방법을 배웠습니다. 이 설정은 데이터 기반 애플리케이션 개발의 필수적인 과정입니다.

다음 글에서는 전자정부프레임워크의 공통 컴포넌트 활용에 대해 다룰 예정입니다.

반응형

+ Recent posts