Spring对事务的管理有丰富的支持,Spring提供了编程式配置事务和声明式配置事务:
一种是使用Annotation注解的方式(官方推荐)
一种是基于Xml的方式
采用任何一种方式我们都需要在我们的bean.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driverClassName}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}" />
<!-- 连接池的最大值 -->
<property name="maxActive" value="${maxActive}" />
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}" />
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="${minIdle}" />
</bean>
<bean id="personService"
class="com.royzhou.jdbc.PersonServiceImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
</beans>
<tx:annotation-driven transaction-manager="txManager" /> 这句话的作用是注册事务注解处理器
定义好配置文件后我们只需要在我们的类上加上注解@Transactional,就可以指定这个类需要受Spring的事务管理
默认Spring为每个方法开启一个事务,如果方法发生运行期错误unchecked(RuntimeException),事务会进行回滚
如果发生checked Exception,事务不进行回滚.
例如在下面的例子中,我们为PersonServiceImpl添加事务支持:
package com.royzhou.jdbc;
import java.util.List;
import javax.sql.DataSource;
import java.sql.Types;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class PersonServiceImpl implements PersonService {
private JdbcTemplate jdbcTemplate;
/**
* 通过Spring容器注入datasource
* 实例化JdbcTemplate,该类为主要操作数据库的类
* @param ds
*/
public void setDataSource(DataSource ds) {
this.jdbcTemplate = new JdbcTemplate(ds);
}
public void addPerson(PersonBean person) {
/**
* 第一个参数为执行sql
* 第二个参数为参数数据
* 第三个参数为参数类型
*/
jdbcTemplate.update("insert into person values(null,?)", new Object[]{person.getName()}, new int[]{Types.VARCHAR});
throw new RuntimeException("运行期例外");
}
public void deletePerson(int id) {
jdbcTemplate.update("delete from person where id = ?", new Object[]{id}, new int[]{Types.INTEGER});
}
@SuppressWarnings("unchecked")
public PersonBean queryPerson(int id) {
/**
* new PersonRowMapper()是一个实现RowMapper接口的类,
* 执行回调,实现mapRow()方法将rs对象转换成PersonBean对象返回
*/
List<PersonBean> pbs = (List<PersonBean>)jdbcTemplate.query("select id,name from person where id = ?", new Object[]{id}, new PersonRowMapper());
PersonBean pb = null;
if(pbs.size()>0) {
pb = pbs.get(0);
}
return pb;
}
@SuppressWarnings("unchecked")
public List<PersonBean> queryPersons() {
List<PersonBean> pbs = (List<PersonBean>) jdbcTemplate.query("select id,name from person", new PersonRowMapper());
return pbs;
}
public void updatePerson(PersonBean person) {
jdbcTemplate.update("update person set name = ? where id = ?", new Object[]{person.getName(), person.getId()}, new int[]{Types.VARCHAR, Types.INTEGER});
}
}
在addPerson方法中我们抛出了一个运行期例外,以此来检查Spring的事务管理。后台输出异常:java.lang.Exception: checked 例外 ,查看数据库发现数据插入,说明事务没有进行了回滚.
说明了Spring的事务支持默认只对运行期异常(RuntimeException)进行回滚,这里可能有个疑问,我们执行sql操作的时候会发生sql异常,不属于运行期异常,那Spring是怎么进行事务回滚的呢 ???? 查看了一下JdbcTemplate的源代码发现,JdbcTemplate的处理方法如下:
public int[] batchUpdate(String sql, final BatchPreparedStatementSetter pss) throws DataAccessException {
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL batch update [" + sql + "]");
}
return (int[]) execute(sql, new PreparedStatementCallback() {
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
try {
int batchSize = pss.getBatchSize();
if (JdbcUtils.supportsBatchUpdates(ps.getConnection())) {
for (int i = 0; i < batchSize; i++) {
pss.setValues(ps, i);
ps.addBatch();
}
return ps.executeBatch();
}
else {
int[] rowsAffected = new int[batchSize];
for (int i = 0; i < batchSize; i++) {
pss.setValues(ps, i);
rowsAffected[i] = ps.executeUpdate();
}
return rowsAffected;
}
}
finally {
if (pss instanceof ParameterDisposer) {
((ParameterDisposer) pss).cleanupParameters();
}
}
}
});
}
在代码中捕获了SQLException然后抛出一个org.springframework.dao.DataAcceddException,该异常继承自org.springframework.core.NestedRuntimeException,NestedRuntimeException 是一个继承自RuntimeException的抽象类,Spring jdbcTemplate处理发生异常处理后抛出来得异常基本上都会继承NestedRuntimeException,看完之后才确信了Spring默认只对RuntimeException进行回滚
当然我们可以修改Spring的默认配置,当发生RuntimeException我们也可以不让他进行事务回滚 只需要加上一个@Transactional(noRollbackFor=RuntimeException.class) 。注意@Transactional只能针对public属性范围内的方法添加
对于一些查询工作,因为不需要配置事务支持,我们配置事务的传播属性:
@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
readOnly=true表示事务中不允许存在更新操作.
关于事务的传播属性有下面几种配置:
REQUIRED:业务方法需要在一个事务中运行,如果方法运行时,已经处于一个事务中,那么加入到该事务中,否则自己创建一个新的事务.(Spring默认的事务传播属性)
NOT_SUPPORTED:声明方法不需要事务,如果方法没有关联到一个事务,容器不会为它开启事务,如果方法在一个事务中被调用,该事务被挂起,在方法调用结束后,原先的事务便会恢复执行
REQUIRESNEW:不管是否存在事务,业务方法总会为自己发起一个新的事务,如果方法运行时已经存在一个事务,则该事务会被挂起,新的事务被创建,知道方法执行结束,新事务才结束,原先的事务才恢复执行.
MANDATORY:指定业务方法只能在一个已经存在的事务中执行,业务方法不能自己发起事务,如果业务方法没有在事务的环境下调用,则容器会抛出异常
SUPPORTS:如果业务方法在事务中被调用,则成为事务中的一部分,如果没有在事务中调用,则在没有事务的环境下执行
NEVER:指定业务方法绝对不能在事务范围内运行,否则会抛出异常.
NESTED:如果业务方法运行时已经存在一个事务,则新建一个嵌套的事务,该事务可以有多个回滚点,如果没有事务,则按REQUIRED属性执行. 注意:业务方法内部事务的回滚不会对外部事务造成影响,但是外部事务的回滚会影响内部事务