1.结构图
2.实体类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 + '}'; } }
3.业务层接口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); }
4.业务层实现类AccountServiceImpl:
package com.itheima.service.impl; import com.itheima.dao.IAccountDao; import com.itheima.pojo.Account; import com.itheima.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; //业务层实现类 @Service("accountService") @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)//只读型事务 public class AccountServiceImpl implements IAccountService { @Autowired private IAccountDao accountDao; @Override public Account findAccountById(Integer accountId) { return accountDao.findAccountById(accountId); } @Transactional(propagation = Propagation.REQUIRED,readOnly = false)//这里需要读写型事务 @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); } /*这里使用的事务不一样导致每使用一次配一次注解:所以最好的还是使用纯的XML配置*/ }
5.持久层接口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); } 6.持久层实现类AccountDaoImpl:
package com.itheima.dao.impl; import com.itheima.dao.IAccountDao; import com.itheima.pojo.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; //持久层实现类 @Repository("accountDao") public class AccountDaoImpl implements IAccountDao { @Autowired //配置模版,加了继承使用不了注解 private JdbcTemplate jdbcTemplate; //按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());*/ } }
7.主配置类SpringConfiguration(注解的理解):
package com.itheima.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.transaction.annotation.EnableTransactionManagement; /* * spring的配置类,相当于bean.xml * */ //开启spring配置类 @Configuration //扫描包 @ComponentScan("com.itheima") //配置数据库类 @Import({JdbcConfig.class,TransactionConfig.class}) //引入数据库资源 @PropertySource("jdbcConfig.properties") //事务管理:开启事务的注解支持:<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven> @EnableTransactionManagement public class SpringConfiguration { }
8.事务相关的配置类TransactionConfig(引入主类):
package com.itheima.config; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; /* * 和事务相关的配置类 * */ public class TransactionConfig { /* * 用于创建事务管理器对象 * */ @Bean(name = "transactionManager") public PlatformTransactionManager createTransactionManager(DataSource dataSource){ return new DataSourceTransactionManager(dataSource); } }
9.连接上数据库的配置类JdbcConfig:
package com.itheima.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; /* * 和连接数据库相关的配置类 * */ public class JdbcConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; /* * 创建JdbcTemplate * */ @Bean(name = "jdbcTemplate") public JdbcTemplate createJdbcTemplate(DataSource dataSource){ return new JdbcTemplate(dataSource); } /* * 创建数据库对象 * */ @Bean(name = "dataSource") public DataSource createDataSource(){ DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName(driver); ds.setUrl(url); ds.setUsername(username); ds.setPassword(password); return ds; } }
10.jdbcConfig.properties配置数据库连接
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/eesy jdbc.username=root jdbc.password=123456
11.pom文件
<dependencies> <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> <scope>runtime</scope> </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> </dependencies>
12.TestCode
package com.itheima; import com.itheima.config.SpringConfiguration; 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(classes = SpringConfiguration.class) /*pom.xml加上spring-test依赖*/ public class TestCode { @Autowired /*在这个时候:就有两个AccountService,通过@Qualifier来指定名称*/ //@Qualifier("proxyAccountService") //@Resource(name="proxyAccountService") /*这时候当然也可以用@Resource替换上面两个,但是需要导入相关依赖,否则会报空指针异常*/ private IAccountService as; @Test public void testTransfer(){ as.transfer("test","zhou",1000f); } }