Spring 聲明式事務(wù)管理

2022-05-16 15:47 更新

Spring 聲明式事務(wù)管理

聲明式事務(wù)管理方法允許你在配置的幫助下而不是源代碼硬編程來管理事務(wù)。這意味著你可以將事務(wù)管理從事務(wù)代碼中隔離出來。你可以只使用注釋或基于配置的 XML 來管理事務(wù)。 bean 配置會(huì)指定事務(wù)型方法。下面是與聲明式事務(wù)相關(guān)的步驟:

  • 我們使用標(biāo)簽,它創(chuàng)建一個(gè)事務(wù)處理的建議,同時(shí),我們定義一個(gè)匹配所有方法的切入點(diǎn),我們希望這些方法是事務(wù)型的并且會(huì)引用事務(wù)型的建議。

  • 如果在事務(wù)型配置中包含了一個(gè)方法的名稱,那么創(chuàng)建的建議在調(diào)用方法之前就會(huì)在事務(wù)中開始進(jìn)行。

  • 目標(biāo)方法會(huì)在 try / catch 塊中執(zhí)行。

  • 如果方法正常結(jié)束,AOP 建議會(huì)成功的提交事務(wù),否則它執(zhí)行回滾操作。

讓我們看看上述步驟是如何實(shí)現(xiàn)的。在我們開始之前,至少有兩個(gè)數(shù)據(jù)庫(kù)表是至關(guān)重要的,在事務(wù)的幫助下,我們可以實(shí)現(xiàn)各種 CRUD 操作。以 Student 表為例,該表是使用下述 DDL 在 MySQL TEST 數(shù)據(jù)庫(kù)中創(chuàng)建的。

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

第二個(gè)表是 Marks,我們用來存儲(chǔ)基于年份的學(xué)生標(biāo)記。在這里,SID 是 Student 表的外鍵。

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

現(xiàn)在讓我們編寫 Spring JDBC 應(yīng)用程序來在 Student 和 Marks 表中實(shí)現(xiàn)簡(jiǎn)單的操作。讓我們適當(dāng)?shù)氖褂?Eclipse IDE,并按照如下所示的步驟來創(chuàng)建一個(gè) Spring 應(yīng)用程序:

步驟 描述
1 創(chuàng)建一個(gè)名為 SpringExample 的項(xiàng)目,并在創(chuàng)建的項(xiàng)目中的 src 文件夾下創(chuàng)建包 com.tutorialspoint
2 使用 Add External JARs 選項(xiàng)添加必需的 Spring 庫(kù),解釋見 Spring Hello World Example chapter.
3 在項(xiàng)目中添加其它必需的庫(kù) mysql-connector-java.jarorg.springframework.jdbc.jarorg.springframework.transaction.jar。如果你還沒有這些庫(kù),你可以下載它們。
4 創(chuàng)建 DAO 接口 StudentDAO 并列出所有需要的方法。盡管它不是必需的并且你可以直接編寫 StudentJDBCTemplate 類,但是作為一個(gè)好的實(shí)踐,我們還是做吧。
5 com.tutorialspoint 包下創(chuàng)建其他必需的 Java 類 StudentMarks,StudentMarksMapperStudentJDBCTemplateMainApp。如果需要的話,你可以創(chuàng)建其他的 POJO 類。
6 確保你已經(jīng)在 TEST 數(shù)據(jù)庫(kù)中創(chuàng)建了 StudentMarks 表。還要確保你的 MySQL 服務(wù)器運(yùn)行正常并且你使用給出的用戶名和密碼可以讀/寫訪問數(shù)據(jù)庫(kù)。
7 src 文件夾下創(chuàng)建 Beans 配置文件 Beans.xml 。
8 最后一步是創(chuàng)建所有 Java 文件和 Bean 配置文件的內(nèi)容并按照如下所示的方法運(yùn)行應(yīng)用程序。

下面是數(shù)據(jù)訪問對(duì)象接口文件 StudentDAO.java 的內(nèi)容:

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 文件的內(nèi)容:

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 文件的內(nèi)容:

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 實(shí)現(xiàn)類文件 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;
   }
}

現(xiàn)在讓我們改變主應(yīng)用程序文件 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 的內(nèi)容:

<?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://localhost: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>

當(dāng)你完成了創(chuàng)建源和 bean 配置文件后,讓我們運(yùn)行應(yīng)用程序。如果你的應(yīng)用程序運(yùn)行順利的話,那么會(huì)輸出如下所示的異常。在這種情況下,事務(wù)會(huì)回滾并且在數(shù)據(jù)庫(kù)表中不會(huì)創(chuàng)建任何記錄。

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

在刪除異常后,你可以嘗試上述示例,在這種情況下,會(huì)提交事務(wù)并且你可以在數(shù)據(jù)庫(kù)中看見一條記錄。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)