2014년 6월 26일 목요일

[오라클자바커뮤니티,Spring Framework강의교육추천,spring교육잘하는학원,스프링교육추천]스프링,아이바티스트랜잭션예제[Spring Framework3.X,Transaction,iBATIS, @Transactional], spring mybatis, ibatis 교육학원추천!!

[오라클자바커뮤니티,Spring Framework강의교육추천,spring교육잘하는학원,스프링교육추천]스프링,아이바티스트랜잭션예제[Spring Framework3.X,Transaction,iBATIS, @Transactional], spring mybatis, ibatis 교육학원추천!!
 
스프링의 트랜잭션 관리 방법중 @Transactional 애노테이션을 이용하여 iBATIS와 연동하는 간단 예제이다.(오라클 emp 테이블에 Data 1건 insert..)

먼저 Spring MVC 프로젝트 하나 생성하자.
 
1. pom.xml
 
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>onj</groupId>
 <artifactId>trsample</artifactId>
 <name>springtr</name>
 <packaging>war</packaging>
 <version>1.0.0-BUILD-SNAPSHOT</version>
 <properties>
  <java-version>1.6</java-version>
  <org.springframework-version>3.0.6.RELEASE</org.springframework-version>
  <org.aspectj-version>1.6.9</org.aspectj-version>
  <org.slf4j-version>1.5.10</org.slf4j-version>
 </properties>
 <dependencies>
 
  <!-- Spring -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${org.springframework-version}</version>
   <exclusions>
    <!-- Exclude Commons Logging in favor of SLF4j -->
    <exclusion>
     <groupId>commons-logging</groupId>
     <artifactId>commons-logging</artifactId>
    </exclusion>
   </exclusions>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-tx</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>
  <dependency>
   <groupId>org.apache.ibatis</groupId>
   <artifactId>ibatis-sqlmap</artifactId>
   <version>2.3.4.726</version>
  </dependency>
  <dependency>
   <groupId>commons-dbcp</groupId>
   <artifactId>commons-dbcp</artifactId>
   <version>1.2.2</version>
  </dependency>
  <dependency>
   <groupId>xerces</groupId>
   <artifactId>xercesImpl</artifactId>
   <version>2.9.1</version>
  </dependency>
  <dependency>
   <groupId>cglib</groupId>
   <artifactId>cglib</artifactId>
   <version>2.2</version>
   <type>jar</type>
   <scope>compile</scope>
  </dependency>
  <!-- AspectJ -->
  <dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjrt</artifactId>
   <version>${org.aspectj-version}</version>
  </dependency>
  <!-- Logging -->
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
   <version>${org.slf4j-version}</version>
  </dependency>
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>jcl-over-slf4j</artifactId>
   <version>${org.slf4j-version}</version>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-log4j12</artifactId>
   <version>${org.slf4j-version}</version>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>1.2.16</version>
   <exclusions>
    <exclusion>
     <groupId>javax.mail</groupId>
     <artifactId>mail</artifactId>
    </exclusion>
    <exclusion>
     <groupId>javax.jms</groupId>
     <artifactId>jms</artifactId>
    </exclusion>
    <exclusion>
     <groupId>com.sun.jdmk</groupId>
     <artifactId>jmxtools</artifactId>
    </exclusion>
    <exclusion>
     <groupId>com.sun.jmx</groupId>
     <artifactId>jmxri</artifactId>
    </exclusion>
   </exclusions>
   <scope>runtime</scope>
  </dependency>
  <!-- @Inject -->
  <dependency>
   <groupId>javax.inject</groupId>
   <artifactId>javax.inject</artifactId>
   <version>1</version>
  </dependency>
  <!-- Servlet -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>2.5</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet.jsp</groupId>
   <artifactId>jsp-api</artifactId>
   <version>2.1</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>
  <!-- Test -->
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.7</version>
   <scope>test</scope>
  </dependency>
 </dependencies>
 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>${java-version}</source>
     <target>${java-version}</target>
    </configuration>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
     <warName>abc</warName>
    </configuration>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
     <execution>
      <id>install</id>
      <phase>install</phase>
      <goals>
       <goal>sources</goal>
      </goals>
     </execution>
    </executions>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.5</version>
    <configuration>
     <encoding>UTF-8</encoding>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>
 

2. 컨트롤러
 
package onj.edu.transaction;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HomeController {
 @Autowired
 private TransactionMain transactionMain;

 @RequestMapping(value = "/hello", method = RequestMethod.GET)
 public String home(Locale locale, Model model) {
  String msg = "";
  try {
   msg = transactionMain.insert();
  } catch (Throwable e) {
   msg = "Transaction 오류";
   e.printStackTrace();
  }
  model.addAttribute("msg", msg );
  return "onj";
 }
}
 
3. 트랜잭션 메인 클래스
 
package onj.edu.transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
public class TransactionMain {
 @Autowired
 private Tran1 tr1;

 @Transactional(propagation = Propagation.REQUIRED)
 public String insert() throws Throwable {
  tr1.insertTest();
 
  return "Transaction Success!!";
 }
}

4. 트랜잭션 처리 클래스(간단히 EMP 테이블에 한건 인서트)

package onj.edu.transaction;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
public class Tran1 {
 @Autowired
 private SqlMapClientTemplate sqlMapClientTemplate;

 @Transactional(propagation = Propagation.REQUIRED)
 public void insertTest() {
  HashMap<String, String> hashMap = new HashMap<String, String>();
  hashMap.put("empno", "101");
  hashMap.put("ename", "오라클자바커뮤니티");
  sqlMapClientTemplate.insert("sql.empinsert1", hashMap);
 }
}
 
5. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/spring/root-context.xml</param-value>
 </context-param>


 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <servlet>
  <servlet-name>onjServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/spring/onjServlet-context.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>onjServlet</servlet-name>
  <url-pattern>*.html</url-pattern>
 </servlet-mapping>
</web-app>
 
6. /spring/root-context.xml

연 결하려는 PlatformTransactionManager의 빈 이름이 transactionManager인 경우에는 <tx:annotation-driven/> 태그에서 transaction-manager 속성을 생략할 수 있다. 의존성 주입하려는 PlatformTransactionManager 빈이 다른 이름을 가지고 있다면 명시적으로 사용해야 한다.

<!-- 어노테이션에 기반한 트랜잭션 동작의 설정을 활성화 -->
<!-- 트랜잭션매니저이름이 transactionManager인 경우  transaction-manager 속성생략가능 -->
 <tx:annotation-driven proxy-target-class="true"/>

 <context:component-scan base-package="onj.edu.transaction">
  <context:exclude-filter type="annotation" __EXPRESSION__="org.springframework.stereotype.Controller" />
 </context:component-scan>
 
<!--PlatformTransactionManager중 BasicDataSourceTransactionManager 사용 -->
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName">
   <value>oracle.jdbc.driver.OracleDriver</value>
  </property>
  <property name="url">
   <value>jdbc:oracle:thin:@192.168.0.7:1521:onj</value>
  </property>
  <property name="username">
   <value>scott</value>
  </property>
  <property name="password">
   <value>tiger</value>
  </property>
 </bean>
   
    <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
        <property name="configLocation" value="classpath:/sql-map-config.xml"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>
   
    <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">
        <property name="sqlMapClient" ref="sqlMapClient"/>
    </bean>
 <bean id="transactionManager"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource" />
 </bean>
 <bean id="tr1" class="onj.edu.transaction.Tran1"/>
 <bean id="trMain" class="onj.edu.transaction.TransactionMain"/>
</beans>

7. /spring/onjServlet-context.xml

 <!-- Enables the Spring MVC @Controller programming model -->
 <annotation-driven/>
 <tx:annotation-driven proxy-target-class="true"/>

 <resources mapping="/resources/**" location="/resources/" />

 <!-- 뷰리졸버 -->
 <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <beans:property name="prefix" value="/views/" />
  <beans:property name="suffix" value=".jsp" />
 </beans:bean>
 
<!-- 스프링이 자동 빈을 스캐닝할 패키지 경로 -->
 <context:component-scan base-package="onj.edu.transaction"/>

</beans:beans>
 
8. src/main/resources/sql-map-config.xml
 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
  "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
    <settings useStatementNamespaces="true"/>   
    <sqlMap resource="sqlmap/sql.xml"/>
</sqlMapConfig>

9.  SLQ매퍼, src/main/resources/sqlmap/sql.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 namespace="sql">
 <insert id="empinsert1" parameterClass="hashMap">
  INSERT INTO emp (empno, ename) VALUES (#empno#, #ename#)
 </insert>
</sqlMap>

10.마지막으로 view 역할을 하는 jsp(/views/onj.jsp)
 
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
 <title>Home</title>
</head>
<body>
//트랜잭션처리결과 출력
<P> ${msg} </P>
</body>
</html>


오라클자바커뮤니티교육센터, 개발자전문교육, 개인80%환급
www.oraclejavacommunity.com


평일주간(9:30~18:10) 개강
(6/30)[기업100%환급]PL/SQL,ORACLE HINT,TUNING[개강확정]
(6/30)[기업100%환급]안드로이드개발자과정[개강확정]
(6/30)[기업100%환급]SQL기초에서 Schema Object까지[개강확정]
(7/07)[기업100%환급]C#4.0,WinForm,ADO.NET프로그래밍
(7/07)[기업100%환급]Spring ,MyBatis,Hibernate실무과정[개강확정]
(7/07)[기업100%환급]자바기초에서 JDBC, Servlet/JSP까지 
(7/07)[채용예정교육]오라클자바개발잘하는신입뽑기프로젝트,교육전취업확정

평일야간(19:00~21:50) 개강
(6/26)SQL초보에서실전전문가까지[개강확정]
(7/01)안드로이드개발자과정[개강확정]
(7/01)닷넷(C#,Network,ADO.NET,ASP.NET)마스터과정
(7/02)Spring3.X, MyBatis, Hibernate실무과정[개강확정]
(7/02)자바웹(JSP,Spring,MyBatis,XPlatform)프로젝트과정
(7/02)JAVA,Network&WEB&Framework(자바기초에서웹스프링까지)
(7/03)웹퍼블리싱 마스터
(7/15)MyBatis3.X, Hibernate4.X ORM실무과정
(7/22)자바기초에서JSP,Ajax,jQuery,Spring3.2,MyBatis까지

주말(10:00~17:50) 개강
(6/28)Spring3.X, MyBatis, Hibernate실무과정[개강확정]
(6/28)안드로이드개발자과정
(6/29)자바기초에서JSP,Ajax,jQuery,Spring3.2,MyBatis까지[개강확정]
(7/05)SQL초보에서 Schema Object까지
(7/12)자바웹(JSP,Spring,MyBatis,XPlatform)프로젝트과정
(7/12)MyBatis3.X, Hibernate4.X ORM실무과정
(7/12)개발자를위한PLSQL,SQL튜닝,힌트
(7/12)실무예제로 배워보는 jQuery(개발자/디자이너를위한)
(7/13)C#,ASP.NET마스터

주말저녁(18:30~22:20) 개강
(6/28)JAVA,Network&WEB&Framework
(6/28)SQL기초에서실무까지

댓글 없음:

댓글 쓰기