加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Spring(十五)之声明式事务

发布时间:2020-12-15 07:12:43 所属栏目:Java 来源:网络整理
导读:声明式事务管理方法允许你在配置的帮助下而不是源代码硬编程来管理事务。这意味着你可以将事务管理从事务代码中隔离出来。你可以只使用注释或基于配置的 XML 来管理事务。 bean 配置会指定事务型方法。下面是与声明式事务相关的步骤: 我们使用标签,它创建

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

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

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

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

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

?

1.选择对应的数据库,执行数据库脚本

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

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

?

2.编写对应的实体

package com.tutorialspoint;
public class StudentMarks {
   private Integer age;
    String name;
    Integer id;
    Integer marks;
    Integer year;
    Integer sid;
   void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return setName(String name) {
      this.name = name;
   }
    String getName() {
       setId(Integer id) {
      this.id = id;
   }
    Integer getId() {
       setMarks(Integer marks) {
      this.marks = marks;
   }
    Integer getMarks() {
       setYear(Integer year) {
      this.year = year;
   }
    Integer getYear() {
       setSid(Integer sid) {
      this.sid = sid;
   }
    Integer getSid() {
       sid;
   }
}

?

3.编写对应的DAO

import java.util.List;
 javax.sql.DataSource;
interface StudentDAO {
   /** 
    * This is the method to be used to initialize
    * database resources ie. connection.
    */
    setDataSource(DataSource ds);
    
    * This is the method to be used to create
    * a record in the Student and Marks tables.
     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();
}

4.编写StudentMarksMapper

 java.sql.ResultSet;
 java.sql.SQLException;
 org.springframework.jdbc.core.RowMapper;
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"));
       studentMarks;
   }
}

?

5.编写StudentJDBCTemplate.java

 org.springframework.dao.DataAccessException;
 org.springframework.jdbc.core.JdbcTemplate;
class StudentJDBCTemplate implements StudentDAO{
    JdbcTemplate jdbcTemplateObject;
    setDataSource(DataSource dataSource) {
      this.jdbcTemplateObject =  JdbcTemplate(dataSource);
   }
   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 (?,?,1)">;
         jdbcTemplateObject.update( SQL3,sid,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;
      }
   }
    listStudents() {
      String SQL = "select * from Student,Marks where Student.id=Marks.sid";
      List <StudentMarks> studentMarks=jdbcTemplateObject.query(SQL, StudentMarksMapper());
       studentMarks;
   }
}

?

6.编写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"/>
      ="url"="jdbc:mysql://localhost:3306/TEST"="username"="root"="password"="1234"/>
   </beantx:advice ="txAdvice"  transaction-manager="transactionManager"tx:attributestx:method ="create">
   tx:adviceaop:configaop:pointcut ="createOperation" 
      expression="execution(* com.tutorialspoint.StudentJDBCTemplate.create(..))"aop:advisor advice-ref pointcut-ref="createOperation" Initialization for TransactionManager ="transactionManager"
   class="org.springframework.jdbc.datasource.DataSourceTransactionManager"  ref="dataSource" />    
    Definition for studentJDBCTemplate bean ="studentJDBCTemplate"  
   class="com.tutorialspoint.StudentJDBCTemplate"/>  
   >

beans>

?

7.编写MainApp.java并运行对应的main方法

 org.springframework.context.ApplicationContext;
 org.springframework.context.support.ClassPathXmlApplicationContext;
 MainApp {
   static  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,1)">);
      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());
      }
   }
}

?

最后结果为这样的表示事务起作用:

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读