티스토리 뷰

 

 

Struts2, Spring, iBatis 사용

/**/

1. 다운로드

1-0. Mysql 다운로드

URL : http://dev.mysql.com/get/Downloads/MySQL-5.0/mysql-5.0.67-win32.zip/from/pick#mirrors

1-1. Spring 다운로드 : spring-framework-2.5.5.zip

URL : http://www.springframework.org/download
(2008년 9월 현재 최신버젼 2.5.5)

spring-framework-2.5.5-with-dependencies.zip (82M) 라이브러리 + 문서 + common-lib 포함
spring-framework-2.5.5-with-docs.zip (36M) 문서포함
spring-framework-2.5.5.zip (6M) 라이브러리

1-2. iBatis 다운로드 : ibatis-2.3.3.720.zip

URL : http://ibatis.apache.org/javadownloads.cgi
(2008년 9월 현재 최신버젼 2.3.3)

ibatis-2.3.3.720.zip (1.9M) 라이브러리

1-3. Struts 다운로드 : struts-2.0.11.2-lib.zip

URL : http://struts.apache.org/downloads.html
(2008년 9월 현재 최신버젼 2.0.11.2 )

struts-2.0.11.2-all.zip (91M) Full Distribution
struts-2.0.11.2-apps.zip (23M) Example Applications
struts-2.0.11.2-lib.zip (4M) Essential Dependencies Only

1-4. Mysql-Connector 다운로드 : mysql-connector-java-5.0.8.zip

URL : http://dev.mysql.com/downloads/connector/j/5.1.html

mysql-connector-java-5.0.8.tar.gz (8.4M) tar 압축(일반적으로 리눅스)
mysql-connector-java-5.0.8.zip (8.4M) zip 압축

2. 이클립스 프로젝트 생성

  • 환경
    이클립스 3.4 WTP
  • 새 프로젝트 작성
    File >> New >> Project >> Ohter >> Dyanmic Web Project
    Project Name : devTest 입력 >> Finish
  • Output폴더 변경
    Propterties >> Java Build Path >>Source탭 >> 제일 밑에 Default output folder 이 있다.
    Default output folder : devTest/WebContent/WEB-INF/classes

3. 설치

3-0. Mysql 설치

알아서 설치~^^; 윈도우용이라면 .exe 파일을 실행하셔서.
"다음", "다음".... 클릭신공 발휘!!

3-1. Spring 설치

  • (V) 표시가 되어있는 파일을 이클립스 프로젝트의 /devTest/WebContent/WEB-INF/lib 안에 넣는다.
    (파일을 복사하게 되면 자동으로 이클립스가 라이브러리를 Java Resources: src/Libraries/Web App Libraries 에 등록한다.신기 _!)
    spring-framework-2.5.5
        │  changelog.txt
        │  license.txt
        │  notice.txt
        │  readme.txt
        │  
        └─dist
            │  (V) spring.jar
            │  
            ├─modules
            │      (V) spring-aop.jar
            │      (V) spring-beans.jar
            │      (V) spring-context-support.jar
            │      (V) spring-context.jar
            │      (V) spring-core.jar
            │      (V) spring-jdbc.jar
            │      (V) spring-jms.jar
            │      (V) spring-orm.jar
            │      (V) spring-test.jar
            │      (V) spring-tx.jar
            │      (V) spring-web.jar
            │      (V) spring-webmvc-portlet.jar
            │      (V) spring-webmvc-struts.jar
            │      (V) spring-webmvc.jar
            │      
            ├─resources
            │      spring-aop-2.0.xsd
            │      spring-aop-2.5.xsd
            │      spring-beans-2.0.dtd
            │      spring-beans-2.0.xsd
            │      spring-beans-2.5.xsd
            │      spring-beans.dtd
            │      spring-context-2.5.xsd
            │      spring-form.tld
            │      spring-jee-2.0.xsd
            │      spring-jee-2.5.xsd
            │      spring-jms-2.5.xsd
            │      spring-lang-2.0.xsd
            │      spring-lang-2.5.xsd
            │      spring-tool-2.0.xsd
            │      spring-tool-2.5.xsd
            │      spring-tx-2.0.xsd
            │      spring-tx-2.5.xsd
            │      spring-util-2.0.xsd
            │      spring-util-2.5.xsd
            │      spring.ftl
            │      spring.tld
            │      spring.vm
            │      
            └─weaving
                    spring-agent.jar
                    spring-aspects.jar
                    spring-tomcat-weaver.jar

3-2. iBatis 설치

  • (V) 표시가 되어있는 파일을 이클립스 프로젝트의 /devTest/WebContent/WEB-INF/lib 안에 넣는다.
    ibatis-2.3.3.720
    │  jar-dependencies.txt
    │  license.txt
    │  notice.txt
    │  release.txt
    │  
    ├─doc
    │      dev-javadoc.zip
    │      user-javadoc.zip
    │      
    ├─lib
    │      (V) ibatis-2.3.3.720.jar
    │      
    ├─META-INF
    │      MANIFEST.MF
    │      
    ├─simple_example
    │  │  README.TXT
    │  │  
    │  └─com
    │      └─mydomain
    │          ├─data
    │          │      Account.xml
    │          │      SimpleExample.java
    │          │      SqlMapConfig.xml
    │          │      
    │          └─domain
    │                  Account.java
    │                  
    └─src
            ibatis-src.zip

3-3. Struts 설치

  • (V) 표시가 되어있는 파일을 이클립스 프로젝트의 /devTest/WebContent/WEB-INF/lib 안에 넣는다.
    struts-2.0.11.2
        │  LICENSE.txt
        │  NOTICE.txt
        │  
        └─lib
                antlr-2.7.2.jar
                commons-beanutils-1.6.jar
                commons-chain-1.1.jar
                (V) commons-logging-1.0.4.jar
                commons-logging-api-1.1.jar
                commons-validator-1.3.0.jar
                (V) freemarker-2.3.8.jar
                (V) ognl-2.6.11.jar
                oro-2.0.8.jar
                struts-core-1.3.5.jar
                struts2-codebehind-plugin-2.0.11.2.jar
                struts2-config-browser-plugin-2.0.11.2.jar
                (V) struts2-core-2.0.11.2.jar
                struts2-jasperreports-plugin-2.0.11.2.jar
                struts2-jfreechart-plugin-2.0.11.2.jar
                struts2-jsf-plugin-2.0.11.2.jar
                struts2-pell-multipart-plugin-2.0.11.2.jar
                struts2-plexus-plugin-2.0.11.2.jar
                struts2-sitegraph-plugin-2.0.11.2.jar
                struts2-sitemesh-plugin-2.0.11.2.jar
                struts2-spring-plugin-2.0.11.2.jar
                struts2-struts1-plugin-2.0.11.2.jar
                struts2-tiles-plugin-2.0.11.2.jar
                tiles-api-2.0.4.jar
                tiles-core-2.0.4.jar
                tiles-jsp-2.0.4.jar
                (V) xwork-2.0.5.jar

3-4. Mysql-Connector 다운로드 : mysql-connector-java-5.1.6.zip

  • 압축을 풀고 mysql-connector-java-5.1.6-bin.jar 파일을 JRE_HOME/lib 안에 복사한다.

4. HelloWorld!! HelloWorld!! HelloWorld!! HelloWorld!! HelloWorld!! HelloWorld!!

4-1. HelloWorld!! Spring!!

 

Spring을 사용하는 이유? 10가지!!

1. Spring Provides Better Leverage
적은 노력을 하고도 많은 결과를 줄 수 있다.
2. Spring Provides Better Leverage
적은 노력을 하고도 많은 결과를 줄 수 있다.
3. Spring Provides Better Leverage
적은 노력을 하고도 많은 결과를 줄 수 있다.
4. Spring Provides Better Leverage
적은 노력을 하고도 많은 결과를 줄 수 있다.
5. Spring Provides Better Leverage
적은 노력을 하고도 많은 결과를 줄 수 있다.
6. Spring Enables POJO Programming
Spring은 POJO프로그래밍을 가능하게 한다.
7. Spring Enables POJO Programming
Spring은 POJO프로그래밍을 가능하게 한다.
8. Dependency Injection Helps Testability
DI는 테스트를 용이하게 해준다.
9. Inversion of Control Simplifies JDBC
IoC는 JDBC를 단순화한다.
10. Spring's Community Thrives
Spring 커뮤니티의 번영

4-1-1. Controller + Model 생성 및 테스트

  • hello1 패키지 생성
  • hello1.HelloWorld.java 인터페이스 생성
    HelloWorld.java
    package hello1;
    
    public interface HelloWorld {
    	public String sayHello(String message);
    }
  • hello1.HelloWorldImpl.java 클래스 생성
    hello1.xml에서 message를 설정
    HelloWorldImpl.java
    package hello1;
    
    public class HelloWorldImpl implements HelloWorld {
    
     
        private String message;
    
        public HelloWorldImpl() {
        }
    
        public HelloWorldImpl(String message) {
                this.message = "From Constructor" + message;
        }
    
        public String sayHello(String message) {
                return this.message + message;
        }
    
        public void setMessage(String a) {
                message = a;
        }
    }
  • /src/hello1.xml 생성
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
       <!--  bean 설정 -->
    	<bean id="hello" class="hello1.HelloWorldImpl">
    		<property name="message">
    			<value>HelloWorld!! Spring!!</value>
    		</property>
    	</bean>
    </beans>
    친절한 클립스씨

    이클립스에서 컴파일시 자동으로 /devTest/WebContent/WEB-INF/hello1.xml로 옴겨준다. '친절한것..^^'

  • 테스트를 위한 HelloClient.java 생성
    HelloClient 테스트 (hello1.xml과 HelloWorld연동 테스트)
    package hello1;
    
    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.xml.XmlBeanFactory;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;
    
    public class HelloClient {
            public static void main(String[] args) {              
                    Resource res = new ClassPathResource("hello1.xml"); // 리소스를 읽어온다.
                                
                    BeanFactory factory = new XmlBeanFactory(res); // 스프링 컨테이너.
                    
                    HelloWorld bean1 = (HelloWorld)factory.getBean("hello"); // hello1.xml에서 입력한 beanID
                    
                    String str = bean1.sayHello("I need you!");
                    
                    System.out.println(str);                
            }
    }
    <결과>
    
    HelloWorld!! Spring!!I need you!

4-1-2. WAS 연동 : 웹으로 사용해보자.

  • HelloWorldServlet.java 생성
    package hello1;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.xml.XmlBeanFactory;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;
    
    public class HelloWorldServlet extends HttpServlet {
            public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
                    res.setContentType("text/html; charset=euc-kr");
                    req.setCharacterEncoding("KSC5601");
                    PrintWriter out = res.getWriter();
                    String text = req.getParameter("message");
                    
                    try {                        
                            Resource resource = new ClassPathResource("hello1.xml");
                            BeanFactory factory = new XmlBeanFactory(resource);
                            HelloWorld bean1 = (HelloWorld)factory.getBean("hello");
                            String s = bean1.sayHello(text);
                            out.println(s);                        
                    }
                    catch(Exception e) {
                            
                    }
            }
            
            public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
             {
              doGet(req, resp);
             }
    
    }

    컴파일 오류시 tomcat5/common/lib/servlet-api.jar 를 lib 추가한다.

  • 필터를 위한 WebContent/WEB-INF/web.xml 생성
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
    	<!-- 설정 -->
    	<servlet>
    	<!-- hello1.HelloWorldServlet클래스의 서블릿이름은 HelloWorld 이다. -->
    		<servlet-name>HelloWorld</servlet-name>
    		<servlet-class>hello1.HelloWorldServlet</servlet-class>
    	</servlet>
    	
    	<!-- 맵핑 -->
    	<servlet-mapping>
    	<!-- url끝에     /servlet/HelloWorld.ok가 들어오면 서블릿이름이 HelloWorld인것을 연결시켜라 -->
    		<servlet-name>HelloWorld</servlet-name>
    		<url-pattern>/servlet/HelloWorld.ok</url-pattern> 
    	</servlet-mapping>
    </web-app>
  • 입력을 위한 index.html 생성
    <html>
    <body>
    	<form method=post
    		action="http://localhost:8080/devTest/servlet/HelloWorld.ok"><input
    		type=text name="message"> <input type=submit></form>
    </body>
    </html>

4-1-3. 실행

4-2. HelloWorld!! iBatis!!

 

iBatis의 장점 5가지..

적은 노력으로 SQL문을 변경할수 있다.
적은 노력으로 SQL문을 변경할수 있다.
기존 데이터베이스 프로그램 코드의 20%정도만 사용해도 80%이상의 같은 기능을 수행할 수가 있게 된다
코드를 간단(simple)하게 해준다.
코드를 간단(simple)하게 해준다.

4-2-1. SqlMap

  • src/SqlMapConfig.xml 생성
    SqlMapConfig.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" 
    "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
    <sqlMapConfig>
    	<properties resource="SqlMapConfig.properties" />
    	<settings cacheModelsEnabled="true" enhancementEnabled="true"
    		lazyLoadingEnabled="true" maxRequests="32" maxSessions="10"
    		maxTransactions="5" useStatementNamespaces="false" />
    	<typeAlias alias="Hello" type="hello2.Hello" />
    	<transactionManager type="JDBC">
    		<dataSource type="DBCP">
    			<property name="JDBC.Driver" value="${driver}" />
    			<property name="JDBC.ConnectionURL" value="${url}" />
    			<property name="JDBC.Username" value="${username}" />
    			<property name="JDBC.Password" value="${password}" />
    			<property name="JDBC.DefaultAutoCommit" value="false" />			 
    			
    		</dataSource>
    	</transactionManager>
    	
    	<sqlMap resource="HelloMessage" />
    	<!-- 요런식으로 추가할 수 있다. -->
    	<!-- <sqlMap resource="Comment.xml" />  -->
    	<!-- <sqlMap resource="Message.xml" />  -->
    </sqlMapConfig>
  • settings 엘리먼트의 속성들
    acheModelsEnabled SqlMapClient 를 위한 모든 캐시모델을 가능 유무. Default: true (enabled)
    enhancementEnabled 런타임시 바이트코드 향상을 가능유무. Default: false (disabled)
    lazyLoadingEnabled 모든 늦은(lazy)로딩을 가능유무. Default: true (enabled)
    maxRequests 동시에 SQL문을 수행할 수 있는 쓰레드의 수. 셋팅값보다 많은 쓰레드는 다른 쓰레드가 수행을 완료할 때까지 블록 된다. Default: 512
    maxSessions 주어진 시간동안 활성화될 수 있는 세션의 수. Default: 128
    maxTransactions 한꺼번에 SqlMapClient.startTransaction()에 들어갈 수 있는 쓰레드의 최대갯수. 셋팅값보다 많은 쓰레드는 다른 쓰레드가 나올 때까지 블록 된다. Default: 32
    useStatementNamespaces 이 셋팅을 가능하게 하면 당신은 sqlmap이름과 statement이름으로 구성된 전체적인 이름(fully qualified name)으로 맵핑된 statement를 참조해야 한다. 예를 들면: queryForObject("sqlMapName.statementName"); Default: false (disabled)
  • transactionManager 엘리먼트의 별칭
    JDBC com.ibatis.sqlmap.engine.transaction.jdbc.JdbcTransactionConfig
    JTA com.ibatis.sqlmap.engine.transaction.jta.JtaTransactionConfig
    EXTERNAL com.ibatis.sqlmap.engine.transaction.external.ExternalTransactionConfig
  • dataSource 엘리먼트의 별칭
    SIMPLE com.ibatis.sqlmap.engine.datasource.SimpleDataSourceFactory
    DBCP com.ibatis.sqlmap.engine.datasource.DbcpDataSourceFactory
    JNDI com.ibatis.sqlmap.engine.datasource.JndiDataSourceFactory

4-2-2. ibatis

  • 환경
    mysql
    SQL 쿼리
    create table hello(name varchar(10), text varchar(10)); 
    
    insert into hello values("spring", "helloworld 1");
    insert into hello values("ibatis", "helloworld 2");
    insert into hello values("struts", "helloworld 3");
    
    commit;
  • hello2 패키지 생성
  • hello2.Hello.java 생성 (VO)
    Hello.java
    package hello2;
    
    public class Hello {
    	private String name;
    	private String text;
    	
    	public Hello(String name, String text) {	
    		this.name = name;
    		this.text = text;
    	}
    	
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getText() {
    		return text;
    	}
    	public void setText(String text) {
    		this.text = text;
    	}
    	
    	
    }
  • src/SqlMapConfig.properties 생성
    SqlMapConfig.xml의 $Driver같은 참조를 사용할 속성 정의
    SqlMapConfig.properties
    driver=org.gjt.mm.mysql.Driver
    url=jdbc:mysql://192.168.10.200:3306/swjang
    username=swjang
    password=xxxxxxxx
  • src/HelloMessage.xml 생성
    HelloMessage.xml
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">
    <sqlMap>
    	<select id="getHelloMessage" parameterClass="string" resultMap="Hello">
      <![CDATA[
        select 
          name,
          text
        from userinfo
        where name=#name#
      ]]>
    	</select>
    </sqlMap>
  • hello2.HelloWorld.java 생성
    HelloWorld.java
    package hello2;
    
    import java.io.IOException;
    import java.io.Reader;
    import java.sql.SQLException;
    
    import com.ibatis.common.resources.Resources;
    import com.ibatis.common.util.PaginatedList;
    import com.ibatis.sqlmap.client.SqlMapClient;
    import com.ibatis.sqlmap.client.SqlMapClientBuilder;
    
    public class HelloWorld {
    
    	 
    	@SuppressWarnings("deprecation")
    	public static void main(String[] args) throws SQLException {		
    		Reader reader = null;
    		try {
    			reader = Resources.getResourceAsReader("SqlMapConfig.xml");
    			
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		
    		SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
    		
    		
    		PaginatedList list = (PaginatedList) sqlMap.queryForPaginatedList("getHelloMessage", "struts", 0);
    		
    		for (int i = 0; i < list.size(); i++) {
    			
    			System.out.println(list.getPageIndex());
    			list.nextPage();			  
    		}		
    		
    	}
    	
    }
    org.apache.commons.dbcp.BasicDataSource 클래스가 없다고 징징거릴때는?

    tomcat5/common/lib/nameing-factory-dbcp.jar 추가

그런데... 해도 에러난다?; =ㅅ=;

4-3. HelloWorld!! Spring + iBatis!!

4-3-1. SqlMapConfig.xml(ibatis용) => applicationContext.xml(spring용) 로 변경

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<!--
		iBATIS SQLMaps의 설정파일 위치를 지정한다. class값은 SQLMaps 1.x버전을 사용할때는
		org.springframework.orm.ibatis.SqlMapFactoryBean SQLMaps 2.x버전을 사용할때는
		org.springframework.orm.ibatis.SqlMapClientFactoryBean 를 사용한다.
	-->
	<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="configLocation">
			<value>WEB-INF/SqlMapConfig.xml</value>
		</property>
	</bean>
	<!--
		dataSource를 사용하는것에 대한 정보를 나타낸다. 여기서 사용될수 있는 dataSource타입은 다른 문서를 참조하길
		바란다. 여기선 apache의 DBCP Connection pooling을 사용하는 것이다.
	-->
		
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName">
			<value>org.gjt.mm.mysql.Driver</value>
		</property>
		<property name="url">
			<value>jdbc:mysql://192.168.10.200:3306/swjang</value>
		</property>
		<property name="username">
			<value>swjang</value>
		</property>
		<property name="password">
			<value>xxxxxxx</value>
		</property>
		<property name="defaultAutoCommit">
			<value>false</value>
		</property>
	</bean>
	<!--
		DB연결에 관련된 설정을 DataSource형태로 지정을 했기 때문에 트랜잭션 관리를
		org.springframework.jdbc.datasource.DataSourceTransactionManager 가
		담당하도록 지정한다.
	-->
	<bean id="myTransactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource">
			<ref local="dataSource" />
		</property>
	</bean>  
  
 <!--?? -->
  <!-- 각각의 메소드 별로 트랜잭션관리 속성을 지정한다. -->
	<bean id="guestService"
		class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
		<property name="transactionManager">
			<ref local="myTransactionManager" />
		</property>
		<property name="target">
			<ref local="guestTarget" />
		</property>
		<property name="transactionAttributes">
			<props>
				<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
				<prop key="save*">PROPAGATION_REQUIRED</prop>
				<prop key="update*">PROPAGATION_REQUIRED</prop>
				<prop key="delete*">PROPAGATION_REQUIRED</prop>
			</props>
		</property>
	</bean>
	<!--
		소위 Spring을 사용하게 되는 비지니스 객체의 클래스를 지정하는 부분이다. 즉 여기선
		gikim.dongguk.guestboard.spring.GuestSpringImpl 클래스가 Spring의 여러가지 기능을
		담당하게 되는것이다. 그리고 관리하게 되는 DAO는 guestDAO로 지정한다.
	-->
	<bean id="guestTarget" class="gikim.dongguk.guestboard.spring.GuestSpringImpl">
		<property name="guestDAO">
			<ref local="guestDAO" />
		</property>
	</bean>
	<!--
		DAO에 관련된 셋팅이다. 실제로 iBATIS SQLMaps를 사용하게 되는 클래스를 지정하게 된다. DB정보인
		dataSource값과. iBATIS SQLMaps설정파일의 위치에 해당하는 sqlMapClient를 지정한다.
	-->
	<bean id="guestDAO" class="gikim.dongguk.guestboard.dao.IbatisGuestDAOImpl">
		<property name="dataSource">
			<ref local="dataSource" />
		</property>
		<property name="sqlMapClient">
			<ref local="sqlMapClient" />
		</property>
	</bean>
</beans>

4-3-2. code

spring은 SqlMapClient객체를 대체하는 SqlMapClientTemplate를 제공하는데 이를 생성하는 메소드는 getSqlMapClientTemplate()이다.

Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
user = (User) sqlMap.queryForObject("getUser", id);

사용자 정보를 가져오는 소스가 위와 같다고 할 때 spring의 SqlMapClientTemplate를 사용하면 아래와 같이 될 것이다..

User user = getSqlMapClientTemplate().queryForObject("getUser", id);

눈에 띄게 소스가 간편해진다. 이것밖에 장점이 없을까.? 아니다. 다음의 소스를 보자. spring이 자동적으로 트랜잭션을 처리해 주기 때문에 조금 전 입력예제로 사용되었던 소스가 아래처럼 다시 변경될 수 있다.

getSqlMapClientTemplate().insert("insertMessage", message);
return true;

spring의 트랜잭션 관리를 사용하면 위와 같이 소스가 간단해진다.

이것은 transactionAttributes 속성 하위의 설정값들에 의해 spring의 DI(dependency injection)을 사용하여 가능한 것이지만, 일단 개발자들에게는 SQLMaps로 인해 간단해진 소스가 더욱 심플해졌다는 사실 자체로 행복한 일일 것이다. 이건 개발 프레임워크를 제대로 사용할 때 개발 프레임워크가 개발자에게 주는 혜택이다

4-4. HelloWorld!! Struts + Spring + iBatis!!

5. 결론

이런 프레임워크를 사용하는 이유는...

보다 적은 노력 큰 효과
1) 유연성
2) 간결함
3) 재사용성

6. 참고자료

spring : http://cafe.naver.com/hdjv.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=299
spring의 장점 : http://epro.tistory.com/tag/spring의 장점

ibatis : http://openframework.or.kr/Wiki.jsp?page=SqlmapsOfMaso
ibatis 장점 : http://okjsp.pe.kr/seq/104465

spring + ibatis + struts로 게시판 만들기 : http://blog.naver.com/phcs1219?Redirect=Log&logNo=140044056674

문서에 대하여

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함