Spring声明式事务管理(xml和纯注解方式)

案例环境准备:
数据库表、实体类参考案例:https://blog.csdn.net/friendA3103/article/details/104983388
dao层:

/**
 * 账户的持久层实现类
 * 此版本dao,只需要给它的父类注入一个数据源
 */
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
    
    

    @Override
    public Account findAccountById(Integer accountId) {
    
    
        List<Account> accounts = getJdbcTemplate().query("select * from account where id = ? ", new AccountRowMapper(), accountId);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
    
    
        getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
    }
}

业务层:

/**
 * 账户的业务层实现类
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    
    
    @Resource(name = "accountDao")
    private AccountDao accountDao;

    @Override
    public Account findAccountById(Integer accountId) {
    
    
        return accountDao.findAccountById(accountId);

    }

    @Override
    public void transfer(Integer sourceId, Integer targetId, Float money) {
    
    
        //1.根据名称查询转出账户
        Account source = accountDao.findAccountById(sourceId);
        //2.根据名称查询转入账户
        Account target = accountDao.findAccountById(targetId);
        //3.转出账户减钱
        source.setMoney(source.getMoney() - money);
        //4.转入账户加钱
        target.setMoney(target.getMoney() + money);
        //5.更新转出账户
        accountDao.updateAccount(source);
//            int i=1/0;
        //6.更新转入账户
        accountDao.updateAccount(target);
    }
}

返回映射

public class AccountRowMapper implements RowMapper<Account> {
    
    
    @Override
    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
    
    
        Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));
        return account;
    }
}

bean.xml

<!-- 告知spring在创建容器时要扫描的包 -->
    <context:component-scan base-package="com.cn"/>
    <!-- 配置dao -->
    <bean id="accountDao" class="com.cn.dao.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///ideawork?useSSL=false&amp;serverTimezone=UTC"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

事务配置步骤:
bean.xml

	<!--配置事务步骤:-->
    <!--1.配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--2.配置 事务的通知引用 管理器 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--3.这里 配置事务的属性-->
        <tx:attributes>
            <!--name:匹配 方法名,是业务核心方法
                read-only:是否是只读事务。默认false,不只读。
                isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。
                propagation:指定事务的传播行为。
                timeout:指定超时时间。默认值为:-1。永不超时。
                rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。
                                产生其他异常,事务不回滚。
                                没有默认值,任何异常都回滚。
                no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,
                                产生其他异常时,事务回滚。
                                没有默认值,任何异常都回滚。
            -->
            <tx:method name="*" read-only="false" propagation="REQUIRED"/>
            <tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
            <tx:method name="get*" read-only="true" propagation="SUPPORTS"/>
            <tx:method name="select*" read-only="true" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>
    <!--4.配置aop-->
    <aop:config>
        <aop:pointcut id="pt" expression="execution(* com.cn.service.*.*())"/>
        <!--5.配置切入点和事务通知的对应关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
    </aop:config>

纯注解配置方式

在业务层使用@Transactional注解

@Transactional(readOnly=true,propagation= Propagation.SUPPORTS)
public class AccountServiceImpl implements AccountService {
    
    
    @Resource(name = "accountDao")
    private AccountDao accountDao;
    ....
    ....

该注解的属性和xml中的属性含义一致。该注解可以出现在接口上,类上和方法上。

  • 出现接口上,表示该接口的所有实现类都有事务支持。
  • 出现在类上,表示类中所有方法有事务支持
  • 出现在方法上,表示方法有事务支持。

以上三个位置的优先级:方法>类>接口
配置文件bean.xml当中

	<!-- 配置一个事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入DataSource -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 开启spring对注解事务的支持 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

或者通过配置类(注解方式):

@Configuration 
@EnableTransactionManagement 
public class SpringTxConfiguration {
    
     
	//配置数据源,配置JdbcTemplate,配置事务管理器。 
}

猜你喜欢

转载自blog.csdn.net/friendA3103/article/details/105045505