java中事务是什么?

事务是访问数据库的一个操作序列,DB应用系统通过事务集来完成对数据的存取。

事务必须遵循4个原则,即常说的 ACID

A,Automicity,原子性,即事务要么被全部执行,要么被全部不执行。如果事务下的子事务全部提交成功,则所有数据库操作被提交,否则,应进行事务回滚。

C,Consistency,一致性,即状态转换必须是由一种正确的状态转换到另外一种正确的状态。

I,Isolation,隔离性,即相互间必须不能被影响。

D,Durabillity,持久性,即事务提交后将被永久保存,即便出现其他故障,事务处理结果也应得到保存。

事务的隔离级别

串行化,Serializable,一个事务在执行过程中完全看不到其他事务对数据库所做的更新。

可重复读,Repeatable Read,一个事务在执行过程中可以看到其他事务已经提交的记录,但是不能看到其他事务对已有记录的更新。

读已提交数据,Read Commited,一个事务在执行过程中可以看到其他事务已经提交的记录,而且能看到其他事务对已有记录的更新。

读未提交数据,Read UnCommited,一个事务在执行过程中可以看到其他事务没有提交的记录,而且能看到其他事务没有提交的记录的更新

简单介绍完事务之后,我们用一个例子来具体使用一下事务:购买股票的案例

第一步:准备工作

1)数据表

股票表:stock

账户余额表:account

2)实体类

Account类

package demo22tx.entity;

/**
* Created by mycom on 2018/3/15.
*/
public class Account {
private Integer aid;
private String aname; public Integer getAid() {
return aid;
} public void setAid(Integer aid) {
this.aid = aid;
} public String getAname() {
return aname;
} public void setAname(String aname) {
this.aname = aname;
} public Integer getAblance() {
return ablance;
} public void setAblance(Integer ablance) {
this.ablance = ablance;
} private Integer ablance;
}

Stock类

package demo22tx.entity;

import javax.jnlp.IntegrationService;

/**
* Created by mycom on 2018/3/15.
*/
public class Stock {
private Integer sid;
private String sname;
private Integer scount; public Integer getSid() {
return sid;
} public void setSid(Integer sid) {
this.sid = sid;
} public String getSname() {
return sname;
} public void setSname(String sname) {
this.sname = sname;
} public Integer getScount() {
return scount;
} public void setScount(Integer scount) {
this.scount = scount;
}
}

3)dao层

AccountDao接口

package demo22tx.dao;

/**
* Created by mycom on 2018/3/15.
*/
public interface IAccountDao {
public boolean updateAccount(int aid,int ablance,boolean isbuy);
}

AccountDaoImpl实现类

package demo22tx.dao;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
* Created by mycom on 2018/3/15.
*/
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
public boolean updateAccount(int aid, int ablance, boolean isbuy) {
String sql="";
boolean flag=false;
if(isbuy){
//买入购票
sql="update account set balance=balance-? where aid=?";
}else{
sql="update account set balance=balance+? where aid=?";
}
int update = this.getJdbcTemplate().update(sql, ablance, aid);
if(update>0){
flag=true;
}
return flag;
}
}

StockDao接口

package demo22tx.dao;

/**
* Created by mycom on 2018/3/15.
*/
public interface IStockDao {
public boolean updateStock(int sid,int count,boolean isbuy);
}

StockDaoImpl实现类

package demo22tx.dao;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
* Created by mycom on 2018/3/15.
*/
public class StockDaoImpl extends JdbcDaoSupport implements IStockDao {
public boolean updateStock(int sid, int count, boolean isbuy) {
String sql="";
boolean flag=false;
if(isbuy){
//买入购票
sql="update stock set count=count+? where sid=?";
}else{
sql="update stock set count=count+? where sid=?";
}
int update = this.getJdbcTemplate().update(sql, count, sid);
if(update>0){
flag=true;
}
return flag;
}
}

4)service层

IStockService接口

package demo22tx.service;

import demo22tx.entity.StockException;
import org.springframework.transaction.annotation.Transactional; /**
* Created by mycom on 2018/3/15.
*/
public interface IStockService {
public boolean buyStock(int aid,int abalance,int sid,int count) throws StockException;
}

StockServiceImpl实现类

package demo22tx.service;

import demo22tx.dao.IAccountDao;
import demo22tx.dao.IStockDao;
import demo22tx.entity.StockException;
import org.springframework.transaction.annotation.Transactional; /**
* Created by mycom on 2018/3/15.
*/
public class StockServiceImpl implements IStockService{
private IAccountDao accountDao;
private IStockDao stockDao;
@Transactional
public boolean buyStock(int aid, int abalance, int sid, int count) throws StockException {
boolean isbuy=true;
//异常
if(1==1){
throw new StockException("出错了");
}
boolean account = accountDao.updateAccount(aid, abalance, isbuy);
boolean stock = stockDao.updateStock(sid, count, isbuy);
if(account&&stock){
return true;
}else{
return false;
}
} public IAccountDao getAccountDao() {
return accountDao;
} public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
} public IStockDao getStockDao() {
return stockDao;
} public void setStockDao(IStockDao stockDao) {
this.stockDao = stockDao;
}
}

第二步:配置文件

JDBC.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///s2228
jdbc.username=root
jdbc.password=
applicationContextdemo22tx.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--配置数据源-->
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean> <!--识别到jdbc.properties-->
<!--配置1-->
<!--<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>-->
<!--配置2-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"></property>
</bean>
<!--配置Dao-->
<bean id="accountDao" class="demo22tx.dao.AccountDaoImpl">
<property name="dataSource" ref="dateSource"></property>
</bean>
<bean id="stockDao" class="demo22tx.dao.StockDaoImpl">
<property name="dataSource" ref="dateSource"></property>
</bean>
<!--service id-->
<bean id="stockService" class="demo22tx.service.StockServiceImpl">
<property name="accountDao" ref="accountDao"></property>
<property name="stockDao" ref="stockDao"></property>
</bean>
<!--事务-->
<!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dateSource"></property>
</bean>
<!--事务代理工厂bean 方式一-->
<!--<bean id="stockServiceProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">-->
<!--<property name="transactionManager" ref="transactionManager"></property>-->
<!--<property name="target" ref="stockService"></property>-->
<!--<property name="transactionAttributes">-->
<!--<props>-->
<!--<prop key="buyStock">ISOLATION_DEFAULT,PROPAGATION_REQUIRED</prop>-->
<!--</props>-->
<!--</property>-->
<!--</bean>-->
<!--事务代理工厂bean 方式二-->
<!--<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>-->
<!--事务代理工厂bean 方式三-->
<tx:advice id="stockAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="buyStock" isolation="DEFAULT" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="mypointcut" expression="execution(* demo22tx.service.*.*(..))"></aop:pointcut>
<aop:advisor advice-ref="stockAdvice" pointcut-ref="mypointcut"></aop:advisor>
</aop:config>
</beans>

第三步:测试类

import demo21.entity.Book;
import demo21.service.IBookservice;
import demo22tx.entity.StockException;
import demo22tx.service.IStockService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; /**
* Created by mycom on 2018/3/3.
*/
public class TestTrasaction20180315 {
//JDBCtemplate测试类
@Test
public void t1() throws StockException {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContextdemo22tx.xml");
IStockService stockService =(IStockService) context.getBean("stockService");
stockService.buyStock(1,100,1,10);
}
}

Spring(十二)Spring之事务的更多相关文章

  1. Java开发学习(二十二)----Spring事务属性、事务传播行为

    一.事务配置 上面这些属性都可以在@Transactional注解的参数上进行设置. readOnly:true只读事务,false读写事务,增删改要设为false,查询设为true. timeout ...

  2. Spring(十二)之JDBC框架

    JDBC 框架概述 在使用普通的 JDBC 数据库时,就会很麻烦的写不必要的代码来处理异常,打开和关闭数据库连接等.但 Spring JDBC 框架负责所有的低层细节,从开始打开连接,准备和执行 SQ ...

  3. 学习 Spring (十二) AOP 基本概念及特点

    Spring入门篇 学习笔记 AOP: Aspect Oriented Programming, 通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术 主要功能是:日志记录.性能统计.安全控 ...

  4. Spring(十二)使用Spring的xml文件配置方式实现AOP

    配置文件与注解方式的有非常大不同,多了非常多配置项. beans2.xml <?xml version="1.0" encoding="UTF-8"? & ...

  5. Spring学习(十二)-----Spring @PostConstruct和@PreDestroy实例

    实现 初始化方法和销毁方法3种方式: 实现标识接口 InitializingBean,DisposableBean(不推荐使用,耦合性太高) 设置bean属性 Init-method destroy- ...

  6. Spring学习(十二)-----Spring Bean init-method 和 destroy-method实例

    实现 初始化方法和销毁方法3种方式: 实现标识接口 InitializingBean,DisposableBean(不推荐使用,耦合性太高) 设置bean属性 Init-method destroy- ...

  7. spring cloud深入学习(十二)-----Spring Cloud Zuul网关 Filter、熔断、重试、高可用的使用方式

    Zuul的核心 Filter是Zuul的核心,用来实现对外服务的控制.Filter的生命周期有4个,分别是“PRE”.“ROUTING”.“POST”.“ERROR”,整个生命周期可以用下图来表示. ...

  8. Spring Boot2 系列教程(三十二)Spring Boot 整合 Shiro

    在 Spring Boot 中做权限管理,一般来说,主流的方案是 Spring Security ,但是,仅仅从技术角度来说,也可以使用 Shiro. 今天松哥就来和大家聊聊 Spring Boot ...

  9. 十二 Spring的AOP开发入门,整合Junit单元测试(AspectJ的XML方式)

    创建web项目,引入jar包 引入Spring配置文件

  10. Spring MVC(二)--Spring MVC登陆实例

    本文通过一个简单的登陆实例实现Spring MVC的流程,同时整合 MyBatis使用,流程是这样的: 1.访问一个URL进入登陆界面 2.输入正确的用户名和密码,成功则进入index页面,否则留在登 ...

随机推荐

  1. es6变量声明和解构赋值

    /*声明: * 本文内容多为学习借鉴性内容,大部分非原创 * 特别感谢阮一峰的 ECMAScript6 入门,推荐大家学习 */ 一.es5变量声明的不足 1.变量提升和函数声明提升 es5的代码加载 ...

  2. Linux服务器上安装MySql数据库(默认安装,密码为空),首次使用需要修改密码

    1,在/etc/my.cnf末尾  加入skip-grant-tables,保存,跳过身份验证. 2,重启MySql,使刚才修改的配置生效. 3,终端输入mysql,然后再输入use mysql; 4 ...

  3. SpringMVC实现返回不同视图

    在spring mvc中应该怎么实现可以返回不同结果呢,其实就是配置多个视图解析器,最常用的就是freemaker视图解析器,有时候要又要同时又jsp,html,那么应该怎么配置呢? 具体配置如下 & ...

  4. python 小练习之删除文件夹下的所有文件,包括子文件夹中的文件

    先屡一下思路 一步步怎么实现 1  要求是要删除所有文件(只是删除文件 而不是文件夹),所以 我们肯定要遍历这个文件目录 (for  in遍历) 2 每遍历一个元素时(文件),我们要判断该元素的属性是 ...

  5. javascript垃圾收集与性能问题

    一.垃圾收集 JavaScript具有自动垃圾收集功能,也就是说,执行环境会负责管理代码所占用的内存. 不同于C和类C语言,这些语言都需要手动监听内存的使用情况.JavaScript实现了自动管理内存 ...

  6. eclipse导入/编译hadoop源代码

    1. 确保安装好JDK和eclipse 详细教程见: http://blog.csdn.net/kangdakangdaa/article/details/11364985 2. 安装 Subclip ...

  7. hive:框架理解

    1. 什么是hive  •Hive是基于Hadoop的一个数据仓库工具,可以将结构化的数据文件映射为一张数据库表,并提供类SQL查询功能. •本质是将HQL转换为MapReduce程序  2. 为什么 ...

  8. 浅谈 Glide - BitmapPool 的存储时机 & 解答 ViewTarget 在同一View显示不同的图片时,总用同一个 Bitmap 引用的原因

    作者:林冠宏 / 指尖下的幽灵 掘金:https://juejin.im/user/587f0dfe128fe100570ce2d8 博客:http://www.cnblogs.com/linguan ...

  9. linux zabbix监控服务器搭建

    搭建Zabbix监控服务器 准备运行环境(lamp) [root@zhuji1 ~]# yum -y install httpd [root@zhuji1 ~]# yum -y install php ...

  10. 关于服务器的CPU的几个概念学习总结

    物理CPU 物理CPU: 物理CPU是指插在主板上面的CPU芯片.即指在主板上肉眼能看到的CPU的个数.一般而言,个人台式机或笔记本上只会有一个物理CPU芯片.而服务器主板上往往有多个物理CPU. L ...