Spring基础 专题
专题目录
您的位置:java > Spring基础专题 > Spring 声明式事务管理
Spring 声明式事务管理
作者:--    发布时间:2019-11-20

声明式事务管理方法允许你在配置的帮助下而不是源代码硬编程来管理事务。这意味着你可以将事务管理从事务代码中隔离出来。你可以只使用注释或基于配置的 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 文件夹下创建包 com.tutorialspoint
2 使用 add external jars 选项添加必需的 spring 库,解释见 spring hello world example chapter.
3 在项目中添加其它必需的库 mysql-connector-java.jarorg.springframework.jdbc.jarorg.springframework.transaction.jar。如果你还没有这些库,你可以下载它们。
4 创建 dao 接口 studentdao 并列出所有需要的方法。尽管它不是必需的并且你可以直接编写 studentjdbctemplate 类,但是作为一个好的实践,我们还是做吧。
5 com.tutorialspoint 包下创建其他必需的 java 类 studentmarksstudentmarksmapperstudentjdbctemplatemainapp。如果需要的话,你可以创建其他的 pojo 类。
6 确保你已经在 test 数据库中创建了 studentmarks 表。还要确保你的 mysql 服务器运行正常并且你使用给出的用户名和密码可以读/写访问数据库。
7 src 文件夹下创建 beans 配置文件 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://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>

当你完成了创建源和 bean 配置文件后,让我们运行应用程序。如果你的应用程序运行顺利的话,那么会输出如下所示的异常。在这种情况下,事务会回滚并且在数据库表中不会创建任何记录。

------records creation--------
created name = zara, age = 11
exception in thread "main" java.lang.runtimeexception: simulate error condition

在删除异常后,你可以尝试上述示例,在这种情况下,会提交事务并且你可以在数据库中看见一条记录。

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册