当前位置: 首页 > 文档资料 > Spring 中文教程 >

声明式事务管理(Declarative transaction management)

优质
小牛编辑
121浏览
2023-12-01

声明式事务管理方法允许您在配置的帮助下管理事务,而不是源代码中的硬编码。 这意味着您可以将事务管理与业务代码分开。 您只能使用注释或基于XML的配置来管理事务。 bean配置将指定要进行事务的方法。 以下是与声明性交易相关的步骤 -

  • 我们使用标签,它创建一个事务处理建议,同时我们定义一个切入点,匹配我们希望进行事务的所有方法并引用事务建议。

  • 如果事务配置中包含方法名称,则创建的通知将在调用方法之前开始事务。

  • 目标方法将在try/catch块中执行。

  • 如果方法正常完成,则AOP建议会成功提交事务,否则会执行回滚。

让我们看看上述步骤是如何工作的,但在开始之前,至少有两个数据库表是很重要的,我们可以在事务的帮助下执行各种CRUD操作。 让我们拿一个Student表,可以使用以下DDL在MySQL TEST数据库中创建 -

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

第二个表是Marks ,我们将根据年份为学生保留分数。 这里SID是Student表的外键。

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

现在,让我们编写Spring JDBC应用程序,它将在Student和Marks表上实现简单的操作。 让我们有一个可用的Eclipse IDE,并按照以下步骤创建一个Spring应用程序 -

描述
1创建一个名为SpringExample的项目,并在创建的项目中的src文件夹下创建一个包cn.xnip
2使用Add External JARs选项添加所需的Spring库,如Spring Hello World Example章节中所述。
3在项目中添加其他必需的库mysql-connector-java.jaraopalliance-xyjarorg.springframework.jdbc.jarorg.springframework.transaction.jar 。 如果您还没有库,可以下载所需的库。
4创建DAO接口StudentDAO并列出所有必需的方法。 虽然它不是必需的,你可以直接写StudentJDBCTemplate课程,但作为一个好习惯,让我们这样做。
5cn.xnip包下创建其他所需的Java类StudentJDBCTemplateMainAppStudentJDBCTemplateMainApp 。 如果需要,您可以创建其余的POJO类。
6确保您已在TEST数据库中创建了StudentMarks表。 还要确保您的MySQL服务器工作正常,并且您使用给定的用户名和密码对数据库具有读/写访问权限。
7src文件夹下创建Beans配置文件Beans.xml
8最后一步是创建所有Java文件和Bean配置文件的内容并运行应用程序,如下所述。

以下是数据访问对象接口文件StudentDAO.java

package cn.xnip;
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 cn.xnip;
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 cn.xnip;
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接口StudentJDBCTemplate.java的实现类文件StudentJDBCTemplate.java

package cn.xnip;
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 cn.xnip;
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://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(* cn.xnip.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 = "cn.xnip.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

您可以在删除异常后尝试上面的示例,在这种情况下,它应该提交事务,您应该在数据库中看到一条记录。