Spring宣告式事務管理



宣告式事務管理方法允許您透過配置來管理事務,而不是在原始碼中進行硬編碼。這意味著您可以將事務管理與業務程式碼分離。您只需使用註解或基於XML的配置來管理事務。Bean配置將指定要進行事務處理的方法。以下是宣告式事務相關的步驟:

  • 我們使用``標籤,它建立一個事務處理advice,同時我們定義一個pointcut,匹配所有我們希望進行事務處理的方法,並引用事務advice。

  • 如果方法名稱包含在事務配置中,則建立的advice將在呼叫方法之前開始事務。

  • 目標方法將在一個try/catch塊中執行。

  • 如果方法正常結束,AOP advice將成功提交事務;否則,它將執行回滾。

讓我們看看上面提到的步驟是如何工作的,但在開始之前,重要的是至少有兩個資料庫表,我們可以使用事務對其執行各種CRUD操作。讓我們以一個**學生**表為例,它可以在MySQL TEST資料庫中使用以下DDL建立:

CREATE TABLE Student(
   ID   INT NOT NULL AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE  INT NOT NULL,
   PRIMARY KEY (ID)
);

第二個表是**成績**表,我們將在其中根據年份維護學生的成績。這裡**SID**是學生表的外部索引鍵。

CREATE TABLE Marks(
   SID INT NOT NULL,
   MARKS  INT NOT NULL,
   YEAR   INT NOT NULL
);

現在,讓我們編寫Spring JDBC應用程式,它將對學生和成績表執行簡單的操作。讓我們準備好一個可用的Eclipse IDE,並按照以下步驟建立一個Spring應用程式:

步驟 描述
1 建立一個名為SpringExample的專案,並在建立的專案中src資料夾下建立一個com.tutorialspoint包。
2 Spring HelloWorld示例章節中所述,使用新增外部JARs選項新增所需的Spring庫。
3 在專案中新增其他所需的庫mysql-connector-java.jaraopalliance-x.y.jarorg.springframework.jdbc.jarorg.springframework.transaction.jar。如果您還沒有這些庫,可以下載。
4 建立DAO介面StudentDAO並列出所有所需的方法。雖然這不是必需的,您可以直接編寫StudentJDBCTemplate類,但作為一個良好的實踐,讓我們這樣做。
5 com.tutorialspoint包下建立其他所需的Java類StudentMarksStudentMarksMapperStudentJDBCTemplateMainApp。如果需要,您可以建立其餘的POJO類。
6 確保您已在TEST資料庫中建立了**學生**和**成績**表。還要確保您的MySQL伺服器正常工作,並且您可以使用給定的使用者名稱和密碼訪問資料庫的讀/寫許可權。
7 src資料夾下建立Bean配置文 件Beans.xml
8 最後一步是建立所有Java檔案和Bean配置檔案的內容,並按如下所述執行應用程式。

以下是資料訪問物件介面檔案StudentDAO.java的內容

package com.tutorialspoint;

import java.util.List;
import javax.sql.DataSource;

public interface StudentDAO {
   /** 
      * This is the method to be used to initialize
      * database resources ie. connection.
   */
   public void setDataSource(DataSource ds);
   
   /** 
      * This is the method to be used to create
      * a record in the Student and Marks tables.
   */
   public void create(String name, Integer age, Integer marks, Integer year);
   
   /** 
      * This is the method to be used to list down
      * all the records from the Student and Marks tables.
   */
   public List<StudentMarks> listStudents();
}

以下是StudentMarks.java檔案的內容

package com.tutorialspoint;

public class StudentMarks {
   private Integer age;
   private String name;
   private Integer id;
   private Integer marks;
   private Integer year;
   private Integer sid;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public Integer getId() {
      return id;
   }
   public void setMarks(Integer marks) {
      this.marks = marks;
   }
   public Integer getMarks() {
      return marks;
   }
   public void setYear(Integer year) {
      this.year = year;
   }
   public Integer getYear() {
      return year;
   }
   public void setSid(Integer sid) {
      this.sid = sid;
   }
   public Integer getSid() {
      return sid;
   }
}

以下是StudentMarksMapper.java檔案的內容

package com.tutorialspoint;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class StudentMarksMapper implements RowMapper<StudentMarks> {
   public StudentMarks mapRow(ResultSet rs, int rowNum) throws SQLException {
      StudentMarks studentMarks = new StudentMarks();
      studentMarks.setId(rs.getInt("id"));
      studentMarks.setName(rs.getString("name"));
      studentMarks.setAge(rs.getInt("age"));
      studentMarks.setSid(rs.getInt("sid"));
      studentMarks.setMarks(rs.getInt("marks"));
      studentMarks.setYear(rs.getInt("year"));

      return studentMarks;
   }
}

以下是為定義的DAO介面StudentDAO編寫的實現類檔案StudentJDBCTemplate.java

package com.tutorialspoint;

import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

public class StudentJDBCTemplate implements StudentDAO {
   private JdbcTemplate jdbcTemplateObject;

   public void setDataSource(DataSource dataSource) {
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }
   public void create(String name, Integer age, Integer marks, Integer year){
      try {
         String SQL1 = "insert into Student (name, age) values (?, ?)";
         jdbcTemplateObject.update( SQL1, name, age);

         // Get the latest student id to be used in Marks table
         String SQL2 = "select max(id) from Student";
         int sid = jdbcTemplateObject.queryForInt( SQL2 );

         String SQL3 = "insert into Marks(sid, marks, year) " + "values (?, ?, ?)";
         jdbcTemplateObject.update( SQL3, sid, marks, year);
         System.out.println("Created Name = " + name + ", Age = " + age);
         
         // to simulate the exception.
         throw new RuntimeException("simulate Error condition") ;
      } 
      catch (DataAccessException e) {
         System.out.println("Error in creating record, rolling back");
         throw e;
      }
   }
   public List<StudentMarks> listStudents() {
      String SQL = "select * from Student, Marks where Student.id = Marks.sid";
      List <StudentMarks> studentMarks = jdbcTemplateObject.query(SQL, 
         new StudentMarksMapper());
      
      return studentMarks;
   }
}

現在讓我們來看主應用程式檔案MainApp.java,內容如下

package com.tutorialspoint;

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      StudentDAO studentJDBCTemplate = 
         (StudentDAO)context.getBean("studentJDBCTemplate");
      
      System.out.println("------Records creation--------" );
      studentJDBCTemplate.create("Zara", 11, 99, 2010);
      studentJDBCTemplate.create("Nuha", 20, 97, 2010);
      studentJDBCTemplate.create("Ayan", 25, 100, 2011);

      System.out.println("------Listing all the records--------" );
      List<StudentMarks> studentMarks = studentJDBCTemplate.listStudents();
      
      for (StudentMarks record : studentMarks) {
         System.out.print("ID : " + record.getId() );
         System.out.print(", Name : " + record.getName() );
         System.out.print(", Marks : " + record.getMarks());
         System.out.print(", Year : " + record.getYear());
         System.out.println(", Age : " + record.getAge());
      }
   }
}

以下是配置檔案Beans.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:tx = "http://www.springframework.org/schema/tx"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

   <!-- Initialization for data source -->
   <bean id="dataSource" 
      class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
      <property name = "url" value = "jdbc:mysql://:3306/TEST"/>
      <property name = "username" value = "root"/>
      <property name = "password" value = "cohondob"/>
   </bean>
  
   <tx:advice id = "txAdvice" transaction-manager = "transactionManager">
      <tx:attributes>
      <tx:method name = "create"/>
      </tx:attributes>
   </tx:advice>
	
   <aop:config>
      <aop:pointcut id = "createOperation" 
         expression = "execution(* com.tutorialspoint.StudentJDBCTemplate.create(..))"/>
      
      <aop:advisor advice-ref = "txAdvice" pointcut-ref = "createOperation"/>
   </aop:config>
	
   <!-- Initialization for TransactionManager -->
   <bean id = "transactionManager"
      class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
      
      <property name = "dataSource" ref = "dataSource" />    
   </bean>

   <!-- Definition for studentJDBCTemplate bean -->
   <bean id = "studentJDBCTemplate"  
      class = "com.tutorialspoint.StudentJDBCTemplate">
      <property name = "dataSource" ref = "dataSource"/>  
   </bean>

</beans>

建立原始碼和Bean配置檔案後,讓我們執行應用程式。如果您的應用程式一切正常,它將列印以下異常。在這種情況下,事務將回滾,並且不會在資料庫表中建立任何記錄。

------Records creation--------
Created Name = Zara, Age = 11
Exception in thread "main" java.lang.RuntimeException: simulate Error condition

您可以移除異常後嘗試上面的示例,在這種情況下,它應該提交事務,您應該在資料庫中看到一條記錄。

spring_transaction_management.htm
廣告