1、新建项目,名为transactionExample
2、导入jar包
导入了spring中的所有jar包和另外两个jar包:
clipboard.png
3、applicationContext.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:util="http://www.springframework.org/schema/util"
         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/context 
         http://www.springframework.org/schema/context/spring-context-3.0.xsd 
         http://www.springframework.org/schema/util  
         http://www.springframework.org/schema/util/spring-util-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
         ">
     

<!-- 使用jdbc作为持久方案,仅仅是得到连接 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
    <property name="url" value="jdbc:mysql://localhost:3306/book" />  
    <property name="username" value="root" />  
    <property name="password" value="sll" /> 
</bean>

<bean id="jdbcDaoSupport" class="dao.JdbcDaoSupport" abstract="true">
    <property name="dataSource" ref="dataSource"></property>    
</bean>

<!-- 定义jdbcTemplateDao的bean -->
<bean id="jdbcTemplateDao" class="dao.JdbcTemplateDao" parent="jdbcDaoSupport">    
</bean>

<!-- 定义jdbcTemplateService的bean -->
<bean id="jdbcTemplateService" class="service.JdbcTemplateService">
    <property name="jdbcTemplateDao">
        <ref bean="jdbcTemplateDao"/>
    </property>
</bean>


<!-- 配置jdbc事务管理器 -->
<bean id="jdbcTxManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<!-- 对domain这个方法实现事务 -->
<tx:advice id="txAdvice" transaction-manager="jdbcTxManager">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
    </tx:attributes>
</tx:advice>

<!-- 事务控制位置 -->
<aop:config expose-proxy="true">  
    <aop:pointcut id="serviceOperation"  
        expression="execution(* service.*.service.*(..))" />  
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />  
</aop:config> 

</beans>

4、JdbcTemplateService.java
service方法中含有save、update的delete三个方法。在save方法之后,程序出错,所以事务会回滚,之前的save操作会失效,不会保存到数据库中。

public class JdbcTemplateService {
    
    private JdbcTemplateDao jdbcTemplateDao; 
    
    public void domain(){
        jdbcTemplateDao.save();
        int i = 2/0;//这里出错了,事务会回滚,之前的save无效
        jdbcTemplateDao.update();
        jdbcTemplateDao.delete();
    }

    public JdbcTemplateDao getJdbcTemplateDao() {
        return jdbcTemplateDao;
    }

    public void setJdbcTemplateDao(JdbcTemplateDao jdbcTemplateDao) {
        this.jdbcTemplateDao = jdbcTemplateDao;
    }
}

5.JdbcTemplateDao.java
在这里需要注意的是,jdbc默认是一个语句一个事务,所以,当要实现spring配置的事务的时候,需要加上conn.setAutoCommit(false);否则回滚操作会失效。

public class JdbcTemplateDao extends JdbcDaoSupport{
    
    private PreparedStatement pre = null;
    private Connection conn;
    
    //异常向上层抛出
    public void save() {
        String insertSql = "insert into user values(?,?)";
        try {
            conn = getDataSource().getConnection();
            conn.setAutoCommit(false);
            pre = conn.prepareStatement(insertSql);
            pre.setString(1, "hahaha");
            pre.setString(2, "happy");
            pre.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public void delete(){
        ...
    }
    public void update(){
        ...
    }
}

6、JdbcDaoSupport.java
本来JdbcDaoSupport 这个类应该是本来就存在的,但是当我在JdbcTemplateDao.java中继承了JdbcDaoSupport.java这个类之后,得到的DataSource总是为空,所以我另写了一个JdbcDaoSupport.java,里面有set和get方法,这样就能正确地得到DataSource的值。

public class JdbcDaoSupport {
    
    private DriverManagerDataSource driverManagerDataSource;

    public DriverManagerDataSource getDataSource() {
        return driverManagerDataSource;
    }

    public void setDataSource(DriverManagerDataSource driverManagerDataSource) {
        this.driverManagerDataSource = driverManagerDataSource;
    }
}

7、测试类

/**
 * 用于测试的main函数
 * @author Administrator
 *
 */
public class test {

    /**
     * @param args
     * @throws SQLException 
     * @throws SQLException 
     */
    public static void main(String[] args){
        String[] configLocations = new String[] {"applicationContext.xml"};
        //应该引入spring的jar包
        ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocations);
        JdbcTemplateService j = ctx.getBean(JdbcTemplateService.class);
        j.domain();
    }

}

sll
23 声望2 粉丝