课程表

Spring 入门

Spring IoC 容器

Spring 依赖注入

Spring Beans 自动装配

Spring 基于注解的配置

Spring 框架

Spring 事务管理

Spring Web MVC 框架

工具箱
速查手册

Spring 声明式事务管理

当前位置:免费教程 » Java相关 » Spring

声明式事务管理方法允许你在配置的帮助下而不是源代码硬编程来管理事务。这意味着你可以将事务管理从事务代码中隔离出来。你可以只使用注释或基于配置的 XML 来管理事务。 bean 配置会指定事务型方法。这是与声明式事务相关的步骤:

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

  • 如果在事务型配置中包含了一个方法的名称,那么创建的建议在调用方法之前就会在事务中开始进行。

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

  • 如果方法正常结束,AOP 建议会成功的提交事务,否则它执行回滚操作。

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

  1. CREATE TABLE Student(
  2. ID INT NOT NULL AUTO_INCREMENT,
  3. NAME VARCHAR(20) NOT NULL,
  4. AGE INT NOT NULL,
  5. PRIMARY KEY (ID)
  6. );

第二个表是 Marks,我们用来存储基于年份的学生标记。在这里,SID 是 Student 表的外键。

  1. CREATE TABLE Marks(
  2. SID INT NOT NULL,
  3. MARKS INT NOT NULL,
  4. YEAR INT NOT NULL
  5. );

现在让我们编写 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 的内容:

  1. package com.tutorialspoint;
  2. import java.util.List;
  3. import javax.sql.DataSource;
  4. public interface StudentDAO {
  5. /**
  6. * This is the method to be used to initialize
  7. * database resources ie. connection.
  8. */
  9. public void setDataSource(DataSource ds);
  10. /**
  11. * This is the method to be used to create
  12. * a record in the Student and Marks tables.
  13. */
  14. public void create(String name, Integer age, Integer marks, Integer year);
  15. /**
  16. * This is the method to be used to list down
  17. * all the records from the Student and Marks tables.
  18. */
  19. public List<StudentMarks> listStudents();
  20. }

以下是 StudentMarks.java 文件的内容:

  1. package com.tutorialspoint;
  2. public class StudentMarks {
  3. private Integer age;
  4. private String name;
  5. private Integer id;
  6. private Integer marks;
  7. private Integer year;
  8. private Integer sid;
  9. public void setAge(Integer age) {
  10. this.age = age;
  11. }
  12. public Integer getAge() {
  13. return age;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setId(Integer id) {
  22. this.id = id;
  23. }
  24. public Integer getId() {
  25. return id;
  26. }
  27. public void setMarks(Integer marks) {
  28. this.marks = marks;
  29. }
  30. public Integer getMarks() {
  31. return marks;
  32. }
  33. public void setYear(Integer year) {
  34. this.year = year;
  35. }
  36. public Integer getYear() {
  37. return year;
  38. }
  39. public void setSid(Integer sid) {
  40. this.sid = sid;
  41. }
  42. public Integer getSid() {
  43. return sid;
  44. }
  45. }

下面是 StudentMarksMapper.java 文件的内容:

  1. package com.tutorialspoint;
  2. import java.sql.ResultSet;
  3. import java.sql.SQLException;
  4. import org.springframework.jdbc.core.RowMapper;
  5. public class StudentMarksMapper implements RowMapper<StudentMarks> {
  6. public StudentMarks mapRow(ResultSet rs, int rowNum) throws SQLException {
  7. StudentMarks studentMarks = new StudentMarks();
  8. studentMarks.setId(rs.getInt("id"));
  9. studentMarks.setName(rs.getString("name"));
  10. studentMarks.setAge(rs.getInt("age"));
  11. studentMarks.setSid(rs.getInt("sid"));
  12. studentMarks.setMarks(rs.getInt("marks"));
  13. studentMarks.setYear(rs.getInt("year"));
  14. return studentMarks;
  15. }
  16. }

下面是定义的 DAO 接口 StudentDAO 实现类文件 StudentJDBCTemplate.java

  1. package com.tutorialspoint;
  2. import java.util.List;
  3. import javax.sql.DataSource;
  4. import org.springframework.dao.DataAccessException;
  5. import org.springframework.jdbc.core.JdbcTemplate;
  6. public class StudentJDBCTemplate implements StudentDAO{
  7. private JdbcTemplate jdbcTemplateObject;
  8. public void setDataSource(DataSource dataSource) {
  9. this.jdbcTemplateObject = new JdbcTemplate(dataSource);
  10. }
  11. public void create(String name, Integer age, Integer marks, Integer year){
  12. try {
  13. String SQL1 = "insert into Student (name, age) values (?, ?)";
  14. jdbcTemplateObject.update( SQL1, name, age);
  15. // Get the latest student id to be used in Marks table
  16. String SQL2 = "select max(id) from Student";
  17. int sid = jdbcTemplateObject.queryForInt( SQL2 );
  18. String SQL3 = "insert into Marks(sid, marks, year) " +
  19. "values (?, ?, ?)";
  20. jdbcTemplateObject.update( SQL3, sid, marks, year);
  21. System.out.println("Created Name = " + name + ", Age = " + age);
  22. // to simulate the exception.
  23. throw new RuntimeException("simulate Error condition") ;
  24. } catch (DataAccessException e) {
  25. System.out.println("Error in creating record, rolling back");
  26. throw e;
  27. }
  28. }
  29. public List<StudentMarks> listStudents() {
  30. String SQL = "select * from Student, Marks where Student.id=Marks.sid";
  31. List <StudentMarks> studentMarks=jdbcTemplateObject.query(SQL,
  32. new StudentMarksMapper());
  33. return studentMarks;
  34. }
  35. }

现在让我们改变主应用程序文件 MainApp.java,如下所示:

  1. package com.tutorialspoint;
  2. import java.util.List;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. public class MainApp {
  6. public static void main(String[] args) {
  7. ApplicationContext context =
  8. new ClassPathXmlApplicationContext("Beans.xml");
  9. StudentDAO studentJDBCTemplate =
  10. (StudentDAO)context.getBean("studentJDBCTemplate");
  11. System.out.println("------Records creation--------" );
  12. studentJDBCTemplate.create("Zara", 11, 99, 2010);
  13. studentJDBCTemplate.create("Nuha", 20, 97, 2010);
  14. studentJDBCTemplate.create("Ayan", 25, 100, 2011);
  15. System.out.println("------Listing all the records--------" );
  16. List<StudentMarks> studentMarks = studentJDBCTemplate.listStudents();
  17. for (StudentMarks record : studentMarks) {
  18. System.out.print("ID : " + record.getId() );
  19. System.out.print(", Name : " + record.getName() );
  20. System.out.print(", Marks : " + record.getMarks());
  21. System.out.print(", Year : " + record.getYear());
  22. System.out.println(", Age : " + record.getAge());
  23. }
  24. }
  25. }

以下是配置文件 Beans.xml 的内容:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:tx="http://www.springframework.org/schema/tx"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/tx
  9. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  10. http://www.springframework.org/schema/aop
  11. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
  12.  
  13. <!-- Initialization for data source -->
  14. <bean id="dataSource"
  15. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  16. <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  17. <property name="url" value="jdbc:mysql://localhost:3306/TEST"/>
  18. <property name="username" value="root"/>
  19. <property name="password" value="cohondob"/>
  20. </bean>
  21.  
  22. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  23. <tx:attributes>
  24. <tx:method name="create"/>
  25. </tx:attributes>
  26. </tx:advice>
  27.  
  28. <aop:config>
  29. <aop:pointcut id="createOperation"
  30. expression="execution(* com.tutorialspoint.StudentJDBCTemplate.create(..))"/>
  31. <aop:advisor advice-ref="txAdvice" pointcut-ref="createOperation"/>
  32. </aop:config>
  33.  
  34. <!-- Initialization for TransactionManager -->
  35. <bean id="transactionManager"
  36. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  37. <property name="dataSource" ref="dataSource" />
  38. </bean>
  39.  
  40. <!-- Definition for studentJDBCTemplate bean -->
  41. <bean id="studentJDBCTemplate"
  42. class="com.tutorialspoint.StudentJDBCTemplate">
  43. <property name="dataSource" ref="dataSource" />
  44. </bean>
  45.  
  46. </beans>

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

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

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

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号