独自快乐|spring框架的入门学习:AOP和面向切面的事务( 九 )

() {@Overridepublic User mapRow(ResultSet rs, int arg1) throws SQLException {User u=new User();u.setAge(rs.getInt("age"));u.setName(rs.getString("name"));u.setId(rs.getInt("id"));return u;}}, id);return u; } @Override //获取用户的数量 public int getTotalCount() {String sql="select count(*) from user";Integer c=super.getJdbcTemplate().queryForObject(sql,Integer.class);return c; } @Override //获取所有的用户 public List getAll() {String sql="select * from user";List userList=super.getJdbcTemplate().query(sql, new RowMapper(){@Overridepublic User mapRow(ResultSet rs, int arg1) throws SQLException {User u=new User();u.setAge(rs.getInt("age"));u.setId(rs.getInt("id"));u.setName(rs.getString("name"));return u;}});return userList; }}将数据库连接池的配置到配置文件中:
jdbc.jdbcUrl=jdbc:mysql:///spring_datajdbc.driverClass=com.mysql.jdbc.Driverjdbc.user=rootjdbc.password=root之后在xml中就可以这样进行配置了
事务
独自快乐|spring框架的入门学习:AOP和面向切面的事务事务的传播行为:
PROPAGION_XXX :事务的传播行为 * 保证同一个事务中 PROPAGATION_REQUIRED 支持当前事务 , 如果不存在 就新建一个(默认) PROPAGATION_SUPPORTS 支持当前事务 , 如果不存在 , 就不使用事务 PROPAGATION_MANDATORY 支持当前事务 , 如果不存在 , 抛出异常
* 保证没有在同一个事务中 PROPAGATION_REQUIRES_NEW 如果有事务存在 , 挂起当前事务 , 创建一个新的事务 PROPAGATION_NOT_SUPPORTED 以非事务方式运行 , 如果有事务存在 , 挂起当前事务
PROPAGATION_NEVER 以非事务方式运行 , 如果有事务存在 , 抛出异常
PROPAGATION_NESTED 如果当前事务存在 , 则嵌套事务执行
独自快乐|spring框架的入门学习:AOP和面向切面的事务事务 , 转账
首先在xml中配置好数据库连接池 , 事务 , 以及service和dao:
首先配置事务的核心管理器 , 里面需要依赖数据库连接池 , 然后配置事务模板对象 , 这个依赖事务的核心管理器 。
之后配置service和dao , dao中由于使用了继承JdbcDaoSupport , 所以这里需要依赖数据库连接池 , 然后Service不仅依赖dao , 而且还依赖事务模板对象 。
package com.huanfeng.dao;public interface AccountDao { void increaseMoney(Integer id,Double money); void decreaseMoney(Integer id,Double money);}package com.huanfeng.dao;import org.springframework.jdbc.core.support.JdbcDaoSupport;public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao { @Override public void increaseMoney(Integer id, Double money) {String sql="update table_count set money=money+? where id=?";super.getJdbcTemplate().update(sql,money,id); } @Override public void decreaseMoney(Integer id, Double money) {String sql="update table_count set money=money-? where id=?";super.getJdbcTemplate().update(sql,money,id); }}


推荐阅读