Spring 編程式事務(wù)管理

2022-05-16 15:42 更新

Spring 編程式事務(wù)管理

編程式事務(wù)管理方法允許你在對(duì)你的源代碼編程的幫助下管理事務(wù)。這給了你極大地靈活性,但是它很難維護(hù)。

在我們開始之前,至少要有兩個(gè)數(shù)據(jù)庫表,在事務(wù)的幫助下我們可以執(zhí)行多種 CRUD 操作。以 Student 表為例,用下述 DDL 可以在 MySQL TEST 數(shù)據(jù)庫中創(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
);

讓我們直接使用 PlatformTransactionManager 來實(shí)現(xiàn)編程式方法從而實(shí)現(xiàn)事務(wù)。要開始一個(gè)新事務(wù),你需要有一個(gè)帶有適當(dāng)?shù)?transaction 屬性的 TransactionDefinition 的實(shí)例。這個(gè)例子中,我們使用默認(rèn)的 transaction 屬性簡(jiǎn)單的創(chuàng)建了 DefaultTransactionDefinition 的一個(gè)實(shí)例。

當(dāng) TransactionDefinition 創(chuàng)建后,你可以通過調(diào)用 getTransaction() 方法來開始你的事務(wù),該方法會(huì)返回 TransactionStatus 的一個(gè)實(shí)例。 TransactionStatus 對(duì)象幫助追蹤當(dāng)前的事務(wù)狀態(tài),并且最終,如果一切運(yùn)行順利,你可以使用 PlatformTransactionManagercommit() 方法來提交這個(gè)事務(wù),否則的話,你可以使用 rollback() 方法來回滾整個(gè)操作。

現(xiàn)在讓我們編寫我們的 Spring JDBC 應(yīng)用程序,它能夠在 Student 和 Mark 表中實(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 庫,解釋見 Spring Hello World Example chapter.
3 在項(xiàng)目中添加 Spring JDBC 指定的最新的庫 mysql-connector-java.jar,org.springframework.jdbc.jarorg.springframework.transaction.jar。如果你還沒有這些庫,你可以下載它們。
4 創(chuàng)建 DAO 接口 StudentDAO 并列出所有需要的方法。盡管它不是必需的并且你可以直接編寫 StudentJDBCTemplate 類,但是作為一個(gè)好的實(shí)踐,我們還是做吧。
5 com.tutorialspoint 包下創(chuàng)建其他必需的 Java 類 StudentMarks,StudentMarksMapper,StudentJDBCTemplateMainApp。如果需要的話,你可以創(chuàng)建其他的 POJO 類。
6 確保你已經(jīng)在 TEST 數(shù)據(jù)庫中創(chuàng)建了 StudentMarks 表。還要確保你的 MySQL 服務(wù)器運(yùn)行正常并且你使用給出的用戶名和密碼可以讀/寫訪問數(shù)據(jù)庫。
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;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
public class StudentJDBCTemplate implements StudentDAO {
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;
   private PlatformTransactionManager transactionManager;
   public void setDataSource(DataSource dataSource) {
      this.dataSource = dataSource;
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }
   public void setTransactionManager(
      PlatformTransactionManager transactionManager) {
      this.transactionManager = transactionManager;
   }
   public void create(String name, Integer age, Integer marks, Integer year){
      TransactionDefinition def = new DefaultTransactionDefinition();
      TransactionStatus status = transactionManager.getTransaction(def);
      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,null,Integer.class );
         String SQL3 = "insert into Marks(sid, marks, year) " + 
                       "values (?, ?, ?)";
         jdbcTemplateObject.update( SQL3, sid, marks, year);
         System.out.println("Created Name = " + name + ", Age = " + age);
         transactionManager.commit(status);
      } catch (DataAccessException e) {
         System.out.println("Error in creating record, rolling back");
         transactionManager.rollback(status);
         throw e;
      }
      return;
   }
   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;
import com.tutorialspoint.StudentJDBCTemplate;
public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");
      StudentJDBCTemplate studentJDBCTemplate = 
      (StudentJDBCTemplate)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" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-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="password"/>
   </bean>

   <!-- 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" />
      <property name="transactionManager"  ref="transactionManager" />    
   </bean>

</beans>

當(dāng)你完成了創(chuàng)建源和 bean 配置文件后,讓我們運(yùn)行應(yīng)用程序。如果你的應(yīng)用程序運(yùn)行順利的話,那么將會(huì)輸出如下所示的消息:

------Records creation--------
Created Name = Zara, Age = 11
Created Name = Nuha, Age = 20
Created Name = Ayan, Age = 25
------Listing all the records--------
ID : 1, Name : Zara, Marks : 99, Year : 2010, Age : 11
ID : 2, Name : Nuha, Marks : 97, Year : 2010, Age : 20
ID : 3, Name : Ayan, Marks : 100, Year : 2011, Age : 25
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)