프로 그래 밍 식 사무 관리

프로 그래 밍 식 사 무 는 TransactionTemplate 템 플 릿 류 를 제공 합 니 다. 이 종 류 는 트 랜 잭 션 작업 의 코드 를 크게 줄 일 수 있 습 니 다.따라서 TransactionTemplate 는 Callback 을 사용 하여 개발 자가 열 린 사무, 제출 사무 및 스크롤 백 사무 등 코드 를 반복 적 으로 쓰 지 않도록 합 니 다. 또한 TransactionTemplate 는 대량의 t.. catch 블록 을 쓸 필요 가 없습니다.HibernateTemplate 는 PlatformTransactionManager 인 스 턴 스 를 제공 해 야 합 니 다.이 인 스 턴 스 는 코드 에 수 동 으로 설정 할 수도 있 고 Spring 의 의존 주입 도 사용 할 수 있 습 니 다.한 마디 로 하면 PlatformTransactionManager 참조 만 가 져 오 면 TransactionTemplate 에서 트 랜 잭 션 을 수행 할 수 있 습 니 다.
TransactionTemplate 를 사용 하면 사 무 를 명시 적 으로 시작 할 필요 가 없고, 사 무 를 명시 적 으로 제출 할 필요 도 없습니다.이 절차 들 은 모두 템 플 릿 에 의 해 완성 된다.그러나 이상 이 발생 했 을 때 는 TransactionStatus 의 setRollback Only 디 스 플레이 를 통 해 사 무 를 해 야 합 니 다.
TransactionTemplate 의 execute 방법 은 TransactionCallback 인 스 턴 스 를 받 습 니 다.Callback 도 Spring 의 전형 적 인 디자인 으로 사용자 조작 을 간소화 하 는 데 사용 되 며 TransactionCallback 은 다음 과 같은 방법 을 포함한다.
ObjectdolnTransaction(TransactionStatusstatus)。
이 방법의 방법 체 는 바로 업무 의 집행 체 이다.
트 랜 잭 션 실행 체 가 값 을 되 돌려 주지 않 으 면 TransactionCallback Without Result 1 류 의 인 스 턴 스 를 사용 할 수 있 습 니 다.이것 은 추상 적 인 유형 으로 직접적 으로 예화 할 수 없고 익명 내부 클래스 를 만 드 는 데 만 사용 할 수 있다.이것 도 TransactionCallback 인터페이스의 하위 인터페이스 입 니 다. 이 추상 류 는 추상 적 인 방법 을 포함 합 니 다.
voiddolnTransactionWithoutResult(TransactionStatusstatus)
이 방법 은 dolnTransaction 의 효과 와 매우 비슷 하 다. 이 방법 은 반환 값 이 없다 는 것 과 차이 가 있다. 즉, 사무 집행 체 는 반환 값 이 필요 없다 는 것 이다.
다음 예시 에서 PlatformTransactionManager 실례 는 Hibernate 에 적용 되 는 사무 관리 자 를 사용 하여 클래스 HibernateTransactionManager 를 실현 한다. 이 실현 클래스 는 국부 사무 관리자 이 고 용기 에 이 사무 관리자 bean 만 배치 되 어 있 기 때문에 코드 에 TransactionTemplate 로 사무 관리자 bean 을 주입 해 야 한다.다음은 Hibernate 로 컬 트 랜 잭 션 관리 프로필 의 원본 코드 입 니 다.
<?xml version="1.0" encoding="gb2312"?>
<!--Spring     DTD  -->
<!DOCTYPE beansPUBLiC"-//SPRING//DTD BEAN//EN"''http://www.springfrarnework.org/dtd/spring-beans.dtd">
<!--Spring         beans-->
<beans>
<!--     , bean  ID   dataSource-->
<bean id="dataSource" class="org.springfrarnework.jdbc.datasource.DriverManagerDataSource">
<!--       -->
<property name="driverClassNarne"><value>corn.rnysql.jdbc.Driver</value>
</property>
<!--        URL-->
<property name="url"><vaiue>jdbc:rnysql://wonder:3306/j2ee</value>
</property>
<!--root         -->
<property name="username"><value>root</value></property>
<!--pass       -->
<property name="password"><value>pass</value></property></bean>
<!--  Hibernate  SessionFactory-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!--       ,       dataSource-->
<property name="dataSource"><ref local="dataSource"></property>
<!-- mappingResouces            >
<property name="mappingResources"><list>
<!         PO     -->
<value>lee/MyTest.hbm.xml</value></list></property>
<!--  Hibernate  SessionFactory   -->
<property name="hibernateProperties"><props>
<!--   Hibernate     -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!       ,     create,update, create-drop-->
<prop key="hibernate.hbm2ddl.auto">update</prop></props></property></bean>
<!--  Hibernate      -->
<!--  HibernateTransactionManager ,   PlatformTransactionManager      Hibernate          。-->
<bean id="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<!-- HibernateTransactionManager bean        SessionFactory bean   -->
<property name="sessionFactory">
<ref local="sessionFactory"></property></bean></beans>

다음은 TransactionTemplate 와 HibemateTemplate 를 사용 한 트 랜 잭 션 코드 입 니 다.
public class TransactionTest{
public static void main(String[] args){
//      web      ,        Spring     
final ApplicationContext ctx =new FileSystemXrnlApplicationContext("bean.xml");
//   Spring         
PlatformTransactionManager transactionManager=(PlatformTransactionManager)ctx.getBean("transactionManager");final SessionFactory sessionFactory =(SessionFactory)ctx.getBean("sessionFactory");
//           ,  TransactionTemplate  
TransactionTemplate tt = new TransactionTemplate(transactionManager);
//  TransactionTemplate       
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUlRED);
//  TransactionTemplate  execute  ,     TransactionCallback  tt.execute(newTransactionCallbackWithoutResult()
//   TransactionCallbackWithoutResult          
protectedvoid dolnTransactionWithoutResult(TransactionStatus ts)try{
//  SessionFactory         HibernateTemplateHibernateTemplate hibernateTemplate=new HibernateTemplate(sessionFactory);
MyTestpl=newMyTest ("Jack");
//       
hibernateTemplate.save(pl);
//                     。          
MyTestp2=new MyTest ("Jack");
//       ,  Person  name        ,          ,                 
hibernateTemplate.save(p2);
}catch (Exception e){
ts.setRollbackOnly();.,)} 

데이터 베 이 스 를 보 는 my table 표 는 기록 되 어 있 지 않 습 니 다. (사 무 를 사용 하지 않 으 면 첫 번 째 기록 은 들 어 갈 수 있 을 것 입 니 다. 두 번 의 저장 기록 은 doInTransactionWithout Result 방법 에서 실 행 됩 니 다) 이 방법 은 방법론 이 사무 적 이기 때문에 이 방법의 데이터 베 이 스 는 모두 유효 하거나 모두 효력 을 잃 습 니 다.두 번 째 기록 은 데이터베이스 의 메 인 키 제약 을 위 반 했 기 때문에 기록 은 모두 효력 을 잃 었 다.

좋은 웹페이지 즐겨찾기