程序员社区

【Spring学习及总结25】基于xml的声明式事务

首先写一个持久层类BookDao

@Repository
public class BookDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    //减去某个用户的余额
    public void updateBalance(String userName,int price){
        String sql = "update account set balance=balance-? where userName=?";
        jdbcTemplate.update(sql,price,userName);
    }

    //获取某本图书的价格
    public int getPrice(String isbn){
        String sql = "select price from book where isbn=?";
        return jdbcTemplate.queryForObject(sql,Integer.class,isbn);
    }

    //减库存:减去某本书的库存
    public void updateStock(String isbn){
        String sql = "update book_stock set stock=stock-1 where isbn=?";
        jdbcTemplate.update(sql,isbn);
    }

}

然后再service层写一个类BookService类,调用BookDao类中的方法:

public class BookService {
    @Autowired
    private BookDao bookDao;
    public void checkout(String username,String isbn) throws FileNotFoundException {
        //减库存
        bookDao.updateStock(isbn);
        //获取价格
        int price = bookDao.getPrice(isbn);
        //减价格
        bookDao.updateBalance(username,price);
    }
}

配置bean对象:

 <!--包扫描-->
<context:component-scan base-package="com.hh"/>

	<!--配置数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	 <property name="user" value="root"/>
	 <property name="password" value="123"/>
	 <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/tx"/>
	 <property name="driverClass" value="com.mysql.jdbc.Driver"/>
	</bean>

<!--配置JdbcTemplate操作数据库-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
	 <property name="dataSource" ref="dataSource"/>
</bean>

<!--配置声明式事务-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	 <property name="dataSource" ref="dataSource"/>
</bean>

<bean id="bookService" class="com.hh.service.BookService"/>
<!--
Spring中提供事务管理器(事务切面),配置这个事务管理器
配置事务方法
告诉Spring安哪些方法是事务方法(事务切面按照切入点表达式切入方法即可)
-->
<aop:config>
 	<aop:pointcut id="txPoint" expression="execution(* com.hh.*.*(..))"/>
 	<aop:advisor advice-ref="myAdvice" pointcut-ref="txPoint"/>
</aop:config>

<!--配置事务管理器-->
<tx:advice id="myAdvice" transaction-manager="dataSourceTransactionManager">
<!--事务属性-->
  <tx:attributes>
     <!--指明哪些方法时事务方法-->
     <tx:method name="*"/>
     <tx:method name="checkout"/>
  </tx:attributes>
</tx:advice>

测试类:

public class MyTest {
    ApplicationContext context =
            new ClassPathXmlApplicationContext("spring.xml");
    @Test
    public void test() throws FileNotFoundException {
        BookService bookService = context.getBean(BookService.class);
        bookService.checkout("Tom","ISBN-001");
    }
}

赞(0) 打赏
未经允许不得转载:IDEA激活码 » 【Spring学习及总结25】基于xml的声明式事务

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区