Background Image
Java
2009.04.01 08:32

Spring framework 사용 예제

조회 수 53291 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

 

Spring에서 CUBRID 사용하기

소개: Spring DAO package을 통해 CUBRID를 사용하는 방법을 간단한 샘플을 통해 설명하고자 한다.

이 문서에서 Spring Spring DAO의 상세내역은 별도로 설명하지 않고 Spring DAO를 통해 CUBRID Connection을 맺고 이를 통해 데이터를 추가, 조회하는 방법을 설명한다.

예제 수행을 위한 Java설치 및 JDBC 환경설정은 CUBRID 매뉴얼의 큐브리드 시작 > JDBC를 이용한 프로그램 작성 > JDBC 환경 설정을 참조하기 바란다.

 

적용 대상: CUBRID2008, JDK1.6.0_04, Spring Framework 2.5.6

Spring에서 CUBRID 사용하기

환경 설정

http://www.springsource.org/download 에서 Spring framework을 다운로드 하여 압축을 푼 후 dist 디렉토리의 spring.jar의 위치를 classpath에 설정한다.

Spring을 사용하기 위해서는

connon-loggin-1.1.1.jar http://commons.apache.org/downloads/download_logging.cgi

commons-dbcp-1.2.2.jar  http://commons.apache.org/downloads/download_dbcp.cgi

commons-pool-1.3.jar http://commons.apache.org/downloads/download_pool.cgi

commons-collections-3.2.1.jar http://commons.apache.org/downloads/download_collections.cgi

에서 각각의 최신 릴리스 바이너리 파일을 다운 받아 압축을 풀면 위 파일들을 얻을 수 있다. 이 파일들도 classpath에 설정한다.

샘플 소스 저장 및 컴파일 할 위치를 classpath에 설정한다.

간단 예제

다음은 Spring을 통해 CUBRID Connection을 맺고 데이터를 추가, 조회하는 것을 간단하게 구성한 예제이다.

테스트를 위해 아래 테이블 생성 스크립트를 DB에서 실행한다.

create table emp(

name varchar(20), //이름

title varchar(10),//직위

email varchar(100),//이메일

phone varchar(20)//전화번호

)

예제 소스는 firstSpringApp 패키지로 이루어져 있으므로 특정 폴더에 firstSpringApp 폴더를 생성하여 아래 스크립트들을 작성하여 저장한다.

applicationContext.xml

데이터베이스 접속 정보 및 사용될 객체가 정의된 configuration metadata이다.

<?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-2.0.xsd">

<!-- jdbc datasource 설정 -->

                           <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >

                           <property name="driverClassName">

<!-- jdbc 드라이버 클래스 이름 -->

                                                <value>cubrid.jdbc.driver.CUBRIDDriver</value>

                           </property>

                           <property name="url">

<!-- 접속 할 데이터베이스 url jdbc:cubrid:IP:PORT:DB이름::: 형식으로 입력 -->

                                                <value>jdbc:cubrid:localhost:33000:demodb:::</value>

                           </property>

<!-- 데이터베이스에 접속할 아이디, 패스워드 설정. -->

                           <property name="username">

                                                <value>public</value>

                           </property>

                           <property name="password">

                                                <value></value>

                           </property>                    

                           </bean>

                           <!-- 질의 수행 객체 -->  

                           <bean id="EmpDao" class="firstSpringApp.EmpDao">

                           <property name="dataSource"><ref local="dataSource"/></property>

                           </bean>

</beans>

Emp.java

package firstSpringApp;

public class Emp {

                                               String name = "";

                                               String title = "";

                                               String email = "";

                                               String phone = "";        

                                               public String getName(){

                                                                    return name;

                                               }

                                               public void setName(String name){

                                                                    this.name = name;

                                               }

                                               public String getTitle(){

                                                                    return title;

                                               }

                                               public void setTitle(String title){

                                                                    this.title = title;

                                               }

                                               public String getEmail(){

                                                                    return email;

                                               }

                                               public void setEmail(String email){

                                                                    this.email = email;

                                               }

                                               public String getPhone(){

                                                                    return phone;

                                               }

                                               public void setPhone(String phone){

                                                                    this.phone = phone;

                                                }

}

EmpDao.java

package firstSpringApp;

 

import java.util.List;

import java.sql.*;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.RowMapper;

import firstSpringApp.Emp;

 

public class EmpDao {

                           private DataSource dataSource;

                           private JdbcTemplate jdbcTemplate;

                          

                           public DataSource getDataSource(){

                                                return dataSource;

                           }                  

                           public void setDataSource(DataSource dataSource) {

                                                this.dataSource = dataSource;

                                                // datasource를 가지고 JdbcTemplate를 생성한다.

                                                this.jdbcTemplate = new JdbcTemplate(dataSource);

                           }

                           // insert 수행

                           public int add(Emp emp){

                                                String sql = "insert into emp(name,title,email,phone) values(?, ?, ?, ?)";

                                                // 입력 받은 emp객체를 update 실행 인자로 사용하기 위해 Object[]로 변경.

                                                Object[] args = {emp.getName(),emp.getTitle(),emp.getEmail(),emp.getPhone()};

                                                return jdbcTemplate.update(sql,args);

                           }

                           // name에 해당하는 데이터 조회

                           public Emp getEmp(String name){

                                                String sql = "select * from emp where name = ?";

                                                // RowMapper ResultSet의 레코드와 객체를 매핑시키는 역할을 한다.

                                                RowMapper mapper = new RowMapper(){

                                                                    public Object mapRow(ResultSet rs, int rowNum) throws SQLException{

                                                                                        Emp emp = new Emp();

                                                                                        emp.setName(rs.getString("name"));

                                                                                        emp.setTitle(rs.getString("title"));

                                                                                        emp.setEmail(rs.getString("email"));

                                                                                        emp.setPhone(rs.getString("phone"));

                                                                                        return emp;

                                                                    }

                                                };

                                                // 입력 받은 name queryForObject 실행 인자로 사용하기 위해 Object[]로 변경.

                                                Object[] args = {name};

                                                return (Emp)jdbcTemplate.queryForObject(sql, args, mapper);

                           }

                           // 전체 데이터 조회

                           public List<Emp> searchAll(){

                                                String sql = "select * from emp";

                                                // RowMapper ResultSet의 레코드와 객체를 매핑시키는 역할을 한다.

                                                RowMapper mapper = new RowMapper(){

                                                                    public Object mapRow(ResultSet rs, int rowNum) throws SQLException{

                                                                                        Emp emp = new Emp();

                                                                                        emp.setName(rs.getString("name"));

                                                                                        emp.setTitle(rs.getString("title"));

                                                                                        emp.setEmail(rs.getString("email"));

                                                                                        emp.setPhone(rs.getString("phone"));

                                                                                        return emp;

                                                                    }

                                                };

                                                return jdbcTemplate.query(sql, mapper);

                           }

}

JdbcTestClient.java

package firstSpringApp;

 

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.*;

import firstSpringApp.Emp;

 

public class JdbcTestClient {

                           public static void main(String[] args) {

                                                // configuration metadata를 읽는다.

                                                ApplicationContext ac = new ClassPathXmlApplicationContext(

                                                                                        new String[] { "firstSpringApp/applicationContext.xml" });

                                                // EmpDao 객체를 생성.

                                                EmpDao empdao = (EmpDao) ac.getBean("EmpDao");

                                                // 실행인자 in 인 경우 insert 수행                         

                                                if (args.length !=0 && "in".equals(args[0])) {

                                                                    Emp emp = new Emp();

                                                                    emp.setName("홍길동");

                                                                    emp.setTitle("사원");

                                                                    emp.setEmail("hong@korea.com");

                                                                    emp.setPhone("010-123-4567");

                                                                    empdao.add(emp);

                                                }else if (args.length !=0 && "view".equals(args[0])) {

                                                                    // 실행인자 view 인 경우 한 건 조회수행

                                                                    Emp emp = empdao.getEmp("홍길동");

                                                                    System.out.println("====== view =========");

                                                                    System.out.println("name:"+emp.getName());

                                                                    System.out.println("title:"+emp.getTitle());

                                                                    System.out.println("email:"+emp.getEmail());

                                                                    System.out.println("phone:"+emp.getPhone());

                                                                    System.out.println("=====================");

                                                }else if (args.length !=0 && "all".equals(args[0])) {

                                                                    // 실행인자 all 인 경우 전체 조회수행

                                                                    List lemp = (List)empdao.searchAll();

                                                                    Iterator empIter= lemp.iterator();

                                                                    System.out.println("======= all list ======");

                                                                    while(empIter.hasNext()){

                                                                                        Emp emplist = (Emp)empIter.next();

                                                                                        System.out.println("name:"+emplist.getName());

                                                                                        System.out.println("title:"+emplist.getTitle());

                                                                                        System.out.println("email:"+emplist.getEmail());

                                                                                        System.out.println("phone:"+emplist.getPhone());

                                                                                        System.out.println("=====================");

                                                                    }                  

                                                }

                           }

}

위의 소스 코드를 컴파일 한 후 실행하면 아래와 같은 결과가 나타난다.

// insert 수행

c:testspring>java firstSpringApp.JdbcTestClient in

2009. 1. 8 오후 5:43:29 org.springframework.context.support.AbstractApplicationC

ontext prepareRefresh

…(생략)

정보: Pre-instantiating singletons in org.springframework.beans.factory.support.

DefaultListableBeanFactory@1b1aa65: defining beans [hello,dataSource,EmpDao]; ro

ot of factory hierarchy

c:testspring>

// 한 건 조회 수행

c:testspring>java firstSpringApp.JdbcTestClient view

2009. 1. 8 오후 5:46:04 org.springframework.context.support.AbstractApplicationC

ontext prepareRefresh

… (생략)

====== view =========

name:홍길동

title:사원

email:hong@korea.com

phone:010-123-4567

=====================

c:testspring>

// 전체 조회 수행

c:testspring>java firstSpringApp.JdbcTestClient all

2009. 1. 8 오후 5:48:04 org.springframework.context.support.AbstractApplicationC

ontext prepareRefresh

…(생략)

======= all list ======

name:홍길동

title:사원

email:hong@korea.com

phone:010-123-4567

=====================

 


List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
21 Java JDBC를 사용한 다중화 구성 SELECT Query 부하 분산 가이드 file 윤준수 2017.03.30 4160
20 Java tomcat8.0(DBCP2)과 CUBRID 연동하기 손승일 2016.07.01 15838
19 Java CUBRID에서 Java AddBatch 사용 엄기호 2016.06.28 8564
18 Java CUBRID와 MyBATIS 빠르게 연동하기 file 김승훈 2015.05.07 19298
17 Java CUBRID와 Oracle의 Clob 타입 사용 방법 비교. seongjoon 2012.06.30 54697
16 Java SELECT ~ FOR UPDATE 대체 방법 손승일 2009.12.30 32530
15 Java CUBRID Java Stored Procedure와 DB Server Memory 관계 file 손승일 2009.10.31 40288
14 Java QuantumDB Eclipse Plugin을 사용하여 CUBRID연동하기 2 cubebridge 2009.10.06 29069
13 Java CUBRID JDBC에서 유니코드 사용하기 1 손승일 2009.08.15 27536
12 Java CUBRID Collection Data Type 사용하기 - JDBC 손승일 2009.08.15 25019
11 Java CUBRID GLO 사용하기 - JDBC 손승일 2009.08.15 23588
10 Java JavaSP SampleCode(Pivot기능) cubebridge 2009.07.28 27655
9 Java log4jdbc를 사용한 JDBC 로그 분석 시난 2009.07.02 36501
8 Java CUBRID에서 log4sql을 사용하자 정병주 2009.06.12 44441
7 Java jsp용 jdbc 샘플입니다. file 시난 2009.05.25 47727
6 Java iBATIS framework with CUBRID file 웁쓰 2009.05.19 54662
5 Java SQuirreL SQL Client에서 CUBRID 사용하기 3 Prototype 2009.04.18 34636
4 Java Power*Architect 에서 CUBRID 사용하기 Prototype 2009.04.18 23999
3 Java AquaDataStudio 에서 CUBRID 사용하기 Prototype 2009.04.18 23786
» Java Spring framework 사용 예제 admin 2009.04.01 53291
Board Pagination Prev 1 2 Next
/ 2

Contact Cubrid

대표전화 070-4077-2110 / 기술문의 070-4077-2113 / 영업문의 070-4077-2112 / Email. contact_at_cubrid.com
Contact Sales