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

工程结构:

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

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

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

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

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

服务类StudentService.java代码如下:

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

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

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

测试类MyTester.java代码如下:

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

@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

Spring的声明式事务----Annotation注解方式(1)的更多相关文章

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

    使用步骤: 步骤一.在spring配置文件中引入<tx:>命名空间<beans xmlns="http://www.springframework.org/schema/b ...

  2. spring4声明式事务--01注解方式

    1.在spring配置文件中引入 tx 命名空间 xmlns:tx="http://www.springframework.org/schema/tx" 2.配置事务管理器 < ...

  3. Spring中声明式事务的注解@Transactional的参数的总结(REQUIRED和REQUIRES_NEW的与主方法的回滚问题)

    一.事务的传播行为1.介绍 当事务方法被另一个事务方法调用时,必须指定事务应该如何传播.例如:方法可能继续在现有事务中运行,也可能开启一个新事务,并在自己的事务中运行.2.属性 事务的传播行为可以由传 ...

  4. 使用注解实现Spring的声明式事务管理

    使用注解实现Spring的声明式事务管理,更加简单! 步骤: 1) 必须引入Aop相关的jar文件 2) bean.xml中指定注解方式实现声明式事务管理以及应用的事务管理器类 3)在需要添加事务控制 ...

  5. Spring声明式事务的实现方式选择(JDK动态代理与cglib)

    1.简介 Spring声明式事务的具体实现方式是动态决定的,与具体配置.以及事务代理对象是否实现接口等有关. 2.使用JDK动态代理的情况 在满足下面两个条件时,Spring会选择JDK动态代理作为声 ...

  6. Spring添加声明式事务

    一.前言 Spring提供了声明式事务处理机制,它基于AOP实现,无须编写任何事务管理代码,所有的工作全在配置文件中完成. 二.声明式事务的XML配置方式 为业务方法配置事务切面,需要用到tx和aop ...

  7. Spring(四)Spring JdbcTemplate&声明式事务

    JdbcTemplate基本使用 01-JdbcTemplate基本使用-概述(了解) JdbcTemplate是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装.spr ...

  8. Spring之声明式事务

    在讲声明式事务之前,先回顾一下基本的编程式事务 编程式事务: //1.获取Connection对象 Connection conn = JDBCUtils.getConnection(); try { ...

  9. 【Spring】——声明式事务配置详解

    项目中用到了spring的事务: @Transactional(rollbackFor = Exception.class, transactionManager = "zebraTrans ...

随机推荐

  1. 再写一篇ubuntu服务器的环境配置文

    三年前写过一篇,但是环境和三年前比已经发生了比较大的变化,于是重新写一篇,自己以后再次配置也比较方便.我个人而言并没有觉得centos比ubuntu好用多少,所以继续选用ubuntu. 一.硬盘分区  ...

  2. 科学计算基础包——Numpy

    一.NumPy简介 NumPy是高性能科学计算和数据分析的基础包.它是pandas等其他各种工具的基础. 1.NumPy的主要功能 (1)ndarray:一个多维数组结构,高效且节省空间. (2)无需 ...

  3. rbac——界面、权限

    一.模板继承 知识点: users.html / roles.html 继承自 base.html 页面滚动时,固定 .menu { background-color: bisque; positio ...

  4. 【数据库】1.0 MySQL入门学习(一)——常识性知识

    1.0 什么是MySQL(官方发音 My Ess Que Ell)? 是一个快速.多线程.多用户和强壮的SQL数据库服务器,SQL是世界上最流行的标准化数据库语言. 名字来源:共同创办人Monty W ...

  5. 软件项目技术点(2)——Canvas之坐标系转换

    AxeSlide软件项目梳理   canvas绘图系列知识点整理 默认坐标系与当前坐标系 canvas中的坐标是从左上角开始的,x轴沿着水平方向(按像素)向右延伸,y轴沿垂直方向向下延伸.左上角坐标为 ...

  6. 导出word的另类做法

    一.背景 项目中经常有导出word的功能,一般用poi来做,但在要求外观较高的情况下,用poi来做基本不能满足需求 而事实上word除了我们一般使用的模式外,还存在xml.与html模式(你没看错,右 ...

  7. 视频监控——从其他浏览器打开低版本IE方案

    1. 方案背景 由于低版本IE浏览器并不支持很多新的页面技术,导致部分页面效果难以实现;另一方面IE浏览器版本与操作系统绑定,难以统一,不同版本IE间的不兼容导致多种兼容性问题,因此本项目暂定采用Ch ...

  8. solidity语言9

    输入参数 pragma solidity ^0.4.16; contract Simple { function taker(uint _a, uint _b) public pure { // do ...

  9. 再学UML-Bug管理系统UML2.0建模实例(四)

    3.3 顺序图(实现模型) 在系统设计与实现阶段我们也可以使用顺序图进行建模,此时通过顺序图可以明确表示系统设计中对象之间的交互,考虑到具体系统实现,对象之间通过方法调用传递消息.在BMS系统中,对每 ...

  10. 7 - py面向对象一条龙服务

    Python从设计之初就已经是一门面向对象的语言,在python里所有东西皆是对象. 下面通过一个实例来说明什么是面向对象. 引子 你是一家公司的员工,公司现在要开发一款“人狗战争”的游戏,人狗战争肯 ...