Spring的声明式事务----Annotation注解方式(1)

这里列一个小的demo工程,直接利用Spring的jdbcTemplate访问Mysql数据库。

工程结构:


 

数据库中的tbl_student表结构如下:

数据实体类Student.java代码如下: 

Java代码  收藏代码
  1. package com.mysrc.entity;  
  2.   
  3. import java.sql.Date;  
  4.   
  5. public class Student {  
  6.     private int id;  
  7.     private String name;  
  8.     private Date birth;  
  9.     private float score;  
  10.   
  11.     public Student() {  
  12.   
  13.     }  
  14.   
  15.     public int getId() {  
  16.         return id;  
  17.     }  
  18.   
  19.     public void setId(int id) {  
  20.         this.id = id;  
  21.     }  
  22.   
  23.     public String getName() {  
  24.         return name;  
  25.     }  
  26.   
  27.     public void setName(String name) {  
  28.         this.name = name;  
  29.     }  
  30.   
  31.     public Date getBirth() {  
  32.         return birth;  
  33.     }  
  34.   
  35.     public void setBirth(Date birth) {  
  36.         this.birth = birth;  
  37.     }  
  38.   
  39.     public float getScore() {  
  40.         return score;  
  41.     }  
  42.   
  43.     public void setScore(float score) {  
  44.         this.score = score;  
  45.     }  
  46.   
  47.     @Override  
  48.     public String toString() {  
  49.         return "Student [id=" + id + ", name=" + name + ", birth=" + birth  
  50.                 + ", score=" + score + "]";  
  51.     }  
  52.   
  53. }  

数据访问类StudentDao.java代码如下:

Java代码  收藏代码
  1. package com.mysrc.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.springframework.jdbc.core.JdbcTemplate;  
  6.   
  7. import com.mysrc.entity.Student;  
  8. import com.mysrc.entity.StudentRowMapper;  
  9.   
  10. public class StudentDao {  
  11.   
  12.     private JdbcTemplate jdbcTemplate;  
  13.   
  14.     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
  15.         this.jdbcTemplate = jdbcTemplate;  
  16.     }  
  17.   
  18.     public Student getStudentById(int id) {  
  19.         return jdbcTemplate.queryForObject(  
  20.                 "select * from tbl_student where id = ?", new Object[] { id },  
  21.                 new StudentRowMapper());  
  22.     }  
  23.   
  24.     public List<Student> getAllStudent() {  
  25.         return jdbcTemplate.query("select * from tbl_student",  
  26.                 new StudentRowMapper());  
  27.     }  
  28.   
  29.     public int insertStudent(Student student) {  
  30.         return jdbcTemplate.update(  
  31.                 "insert into tbl_student(name,birth,score) values(?,?,?)",  
  32.                 new Object[] { student.getName(), student.getBirth(),  
  33.                         student.getScore() });  
  34.     }  
  35.   
  36.     public int deleteStudent(int id) {  
  37.         return jdbcTemplate.update("delete from tbl_student where id = ? ",  
  38.                 new Object[] { id });  
  39.     }  
  40.   
  41.     public int updateStudent(Student student) {  
  42.         return jdbcTemplate.update(  
  43.                 " update tbl_student set name=?,birth=?,score=? where id=? ",  
  44.                 new Object[] { student.getName(), student.getBirth(),  
  45.                         student.getScore(), student.getId() });  
  46.     }  
  47. }  

服务类StudentService.java代码如下:

Java代码  收藏代码
  1. package com.mysrc.service;  
  2.   
  3. import java.sql.Date;  
  4. import java.util.List;  
  5.   
  6. import org.springframework.transaction.annotation.Isolation;  
  7. import org.springframework.transaction.annotation.Propagation;  
  8. import org.springframework.transaction.annotation.Transactional;  
  9.   
  10. import com.mysrc.dao.StudentDao;  
  11. import com.mysrc.entity.Student;  
  12.   
  13. public class StudentService {  
  14.     private StudentDao dao;  
  15.   
  16.     public void setDao(StudentDao dao) {  
  17.         this.dao = dao;  
  18.     }  
  19.   
  20.     @Transactional(propagation = Propagation.NESTED, timeout = 1000, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class, noRollbackFor = CustomRuntimeException.class)  
  21.     public void doComplexLogic() {  
  22.   
  23.         // select  
  24.         List<Student> list = dao.getAllStudent();  
  25.         for (Student student : list) {  
  26.             System.out.println(student);  
  27.         }  
  28.   
  29.         // update  
  30.         Student student = list.get(0);  
  31.         student.setName("zhejiang");  
  32.         dao.updateStudent(student);  
  33.         System.out.println("did update temporarily...");  
  34.   
  35.         // int a = 9 / 0; // 遇到异常,整个事务回滚  
  36.         // 如果try catch捕获这个异常,那整个事务会顺利执行,不会回滚  
  37.   
  38.         int b = 2;  
  39.         if (b > 1) {  
  40.             throw new CustomRuntimeException();  
  41.             // 事务不会回滚,也就是上面的update操作会提交  
  42.         }  
  43.   
  44.         // insert  
  45.         student = new Student();  
  46.         student.setName("hello");  
  47.         student.setBirth(new Date(354778));  
  48.         student.setScore(78.9f);  
  49.         dao.insertStudent(student);  
  50.         System.out.println("did insert...");  
  51.   
  52.         // delete  
  53.         dao.deleteStudent(3);  
  54.         System.out.println("did delete...");  
  55.     }  
  56.   
  57.     class CustomRuntimeException extends RuntimeException {  
  58.         public CustomRuntimeException() {  
  59.             super();  
  60.         }  
  61.   
  62.         public CustomRuntimeException(String msg) {  
  63.             super(msg);  
  64.         }  
  65.     }  
  66. }  

 doComplexLogic()方法模拟一个复杂的数据库操作过程,方法上加上了@Transactional,其中的各个注解的属性后面再详细研究。网上有人说@Transactional 只能被应用到public方法上, 对于其它非public的方法,如果标记了@Transactional也不会报错,但方法没有事务功能,这个未验证。

Spring的上下文配置文件applicationContext.xml内容如下:

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" xmlns:p="http://www.springframework.org/schema/p"  
  4.     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.xsd"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx">  
  6.   
  7.     <bean id="basicDataSource" class="org.apache.commons.dbcp.BasicDataSource">  
  8.         <property name="url"  
  9.             value="jdbc:mysql://127.0.0.1:3306/mytestdb?characterEncoding=utf8" />  
  10.         <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
  11.         <property name="username" value="root" />  
  12.         <property name="password" value="123456" />  
  13.         <property name="maxActive" value="100" />  
  14.         <property name="maxIdle" value="30" />  
  15.         <property name="maxWait" value="1000" />  
  16.         <property name="validationQuery" value="select 1" />  
  17.     </bean>  
  18.   
  19.     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
  20.         <constructor-arg name="dataSource" ref="basicDataSource">  
  21.         </constructor-arg>  
  22.     </bean>  
  23.   
  24.     <bean id="transactionManager"  
  25.         class="org.springframework.jdbc.datasource.DataSourceTransactionManager ">  
  26.         <property name="dataSource">  
  27.             <ref bean="basicDataSource" />  
  28.         </property>  
  29.     </bean>  
  30.   
  31.     <bean id="studentDao" class="com.mysrc.dao.StudentDao">  
  32.         <property name="jdbcTemplate">  
  33.             <ref bean="jdbcTemplate" />  
  34.         </property>  
  35.     </bean>  
  36.   
  37.     <bean id="studentService" class="com.mysrc.service.StudentService">  
  38.         <property name="dao">  
  39.             <ref bean="studentDao" />  
  40.         </property>  
  41.     </bean>  
  42.   
  43.     <tx:annotation-driven transaction-manager="transactionManager" />  
  44.     <!--这句话的作用是注册事务注解处理器 -->  
  45.   
  46. </beans>  

测试类MyTester.java代码如下:

Java代码  收藏代码
  1. package com.mysrc.test;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. import com.mysrc.service.StudentService;  
  7.   
  8. public class MyTester {  
  9.   
  10.     public static void main(String[] args) {  
  11.         ApplicationContext context = new ClassPathXmlApplicationContext(  
  12.                 "applicationContext.xml");  
  13.         StudentService studentService = (StudentService) context  
  14.                 .getBean("studentService");  
  15.         studentService.doComplexLogic();  
  16.     }  
  17.   
  18. }  

@Transactional 的所有可选属性如下

属性 类型 默认值 说明
propagation  Propagation枚举  REQUIRED  事务传播属性
isolation  isolation枚举  DEFAULT  事务隔离级别
readOnly  boolean  false  是否只读
timeout  int  -1  超时(秒)
rollbackFor  Class[]  {}  需要回滚的异常类
rollbackForClassName  String[]  {}  需要回滚的异常类名
noRollbackFor  Class[]  {}  不需要回滚的异常类
noRollbackForClassName  String[]  {}  不需要回滚的异常类名

 整个eclipse工程代码文件下载地址:

http://dl.iteye.com/topics/download/6c63c292-88e0-33de-91bb-8b0f38d507e3

原文地址:https://www.cnblogs.com/holdon521/p/4505301.html