1.结构图
2.bean配置文件:
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--配置accountService--> <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"> <property name="accountDao" ref="accountDao"></property> </bean> <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"> <property name="dataSource" ref="dataSource"></property> </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://localhost:3306/eesy?serverTimezone=UTC"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean> <!--XML配置事务:取消了一些不必要的通知(开始事务,最终通知[释放连接])--> <!-- Spring中基于XML的声明式事务控制配置步骤 1.配置事务管理器 2.配置事务的通知 此时我们需要导入事务的约束 :tx名称空间和约束,同时也需要aop的 使用tx:advice标签配置事务的通知 属性: id:给事务的通知起一个唯一的标识 transaction-manager:给事务通知提供一个事务管理器 3.配置AOP中的通用切入点表达式 4.建立事务通知和切入点表达式的对应关系 5.配置事务的属性 是在事务的通知tx:advice标签的内部——transfer为业务层接口的方法 总结: 我们声明了一个事务,通过写了一个通知txAdvice, 通知里面有回滚和提交,然后通过事务接入的实现类DataSourceTransactionManager实现这些个方法, 然后这些方法对execution(* com.itheima.service.impl.*.*(..))进行方法增强, 前三点都要满足他们之间有关系: --> <!--1.事务声明--> <bean id="transaction" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--2.配置事务的通知--> <tx:advice id="txAdvice" transaction-manager="transaction"> <!--5.配置事务的属性 isolation: 用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。 propagation: 用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS read-only: 用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写 timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位 rollback-for:用于指定一个异常,当产生该异常的时候,事务回滚,产生其他异常时,事务不回滚。没有默认值,表示任何异常的回滚 no-rollback-for: 用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚 --> <tx:attributes> <!--5.1事务的接口方法--> <!--<tx:method name="transfer"/>--> <!--相比之下:第二个的优先级比第一个要高--> <tx:method name="*" propagation="REQUIRED" read-only="false"></tx:method> <!--使用通配符,但是一定要规范命名规则--> <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method> </tx:attributes> </tx:advice> <!--3.配置aop--> <aop:config> <!--配置切入点表达式--> <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"/> <!--4.建立切入点表达式和事物通知的对应关系--> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor> </aop:config> </beans>
3.实体类Account
package com.itheima.pojo; public class Account { private Integer id; private String name; private Float money; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Float getMoney() { return money; } public void setMoney(Float money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }
4.业务层接口IAccountService
package com.itheima.service; import com.itheima.pojo.Account; //业务层接口 public interface IAccountService { //根据id查询 Account findAccountById(Integer accountId); //转账 void transfer(String sourceName ,String targetName,Float money); }
5.业务层实现类AccountServiceImpl:
package com.itheima.service.impl; import com.itheima.dao.IAccountDao; import com.itheima.pojo.Account; import com.itheima.service.IAccountService; //业务层实现类 public class AccountServiceImpl implements IAccountService { private IAccountDao accountDao; /*注入*/ public void setAccountDao(IAccountDao accountDao) { this.accountDao = accountDao; } @Override public Account findAccountById(Integer accountId) { return accountDao.findAccountById(accountId); } @Override public void transfer(String sourceName, String targetName, Float money) { //1.根据转出账户 Account source = accountDao.findAccountByName(sourceName); //2.根据转入账户 Account target = accountDao.findAccountByName(targetName); //3.转出账户减钱 source.setMoney(source.getMoney()-money); //4.转入账户加钱 target.setMoney(target.getMoney()+money); // int i = 1/0; //5.更新保存转出账户 accountDao.updateAccount(source); //6.更新保存转入账户 accountDao.updateAccount(target); } }
6.持久层接口IAccountDao
package com.itheima.dao; import com.itheima.pojo.Account; //持久层接口 public interface IAccountDao { //根据id查询 Account findAccountById(Integer accountId); //根据名称查询 Account findAccountByName(String accountName); //更新操作 void updateAccount(Account account); }
7.持久层实现类AccountDaoImpl
package com.itheima.dao.impl; import com.itheima.dao.IAccountDao; import com.itheima.pojo.Account; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.support.JdbcDaoSupport; import java.util.List; //持久层实现类 public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao { //按id查询(return accounts.isEmpty()?null:accounts.get(0);id的结果只有一个,查来查去只有一个,所以能使用这种方法) @Override public Account findAccountById(Integer accountId) { /*List<Account> accounts = jdbcTemplate.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId); return accounts.isEmpty()?null:accounts.get(0);*/ //第二种抽取代码块之后 List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId); return accounts.isEmpty()?null:accounts.get(0); } //这个名字能有多个 @Override public Account findAccountByName(String accountName) { //未抽取代码块之前 /*List<Account> accounts = jdbcTemplate.query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);*/ List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName); if (accounts.isEmpty()){ return null; }if (accounts.size()>1){ throw new RuntimeException("结果集不唯一"); } return accounts.get(0); } //更新账户 @Override public void updateAccount(Account account) { /*jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());*/ //使用第二种方法:抽取代码块 super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId()); /*jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());*/ } }
8.TestCode
package com.ithiema; import com.itheima.service.IAccountService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) /*说明位置*/ @ContextConfiguration(locations ="classpath:bean.xml") /*pom.xml加上spring-test依赖*/ public class TestCode { @Autowired private IAccountService as; @Test public void testTransfer(){ as.transfer("test","zhou",1000f); } }
9.pom文件
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- jdbc模版依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!-- spring环境依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!-- 事务依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!-- 连接数据库的依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <!--aop依赖--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.7</version> </dependency> <!--整合依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.2.RELEASE</version> </dependency>