Spring jdbctemplate and transaction manager

Internal bean object structure:

@Autowired
private IAccountService accountService;

 
@Service("accountService")
@Transactional(propagation= Propagation.SUPPORTS,readOnly=true)//只读型事务的配置
public class AccountServiceImpl implements IAccountService{

@Autowired
private IAccountDao accountDao;


@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

@Autowired
private JdbcTemplate jdbcTemplate;
 

There are documents in bean.xml
<!-- 配置spring创建容器时要扫描的包-->
<context:component-scan base-package="com.itheima"></context:component-scan>

<!-- 配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<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"></property>
<name = Property "username" value = "root"> </ Property> <-! annotation-based declarative transaction control in spring configuration steps</ bean>
<Property name = "password" value = "1234"> </ Property>



1, configure the transaction manager
2, open spring support for annotation affairs
3, the @Transactional annotation transaction support local needs


->
<! - Configure Transaction Manager ->
<bean the above mentioned id = "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
<Property name = "dataSource" ref = "dataSource"> </ Property>
</ bean>



<- open spring support for annotation affairs ->!
<tx: annotation-driven transaction-manager = " transactionManager"> </ tx: annotation-driven>

 

Persistence layer implementation class

 

@Override
public Account findAccountByName(String accountName) {
List<Account> accounts = jdbcTemplate.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);
}

业务层实现类
//需要的是读写型事务配置
@Transactional(propagation= Propagation.REQUIRED,readOnly=false)//可以读写
@Override
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("transfer....");
//2.1根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//2.2根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//2.3转出账户减钱
source.setMoney(source.getMoney()-money);
//2.4转入账户加钱
target.setMoney(target.getMoney()+money);
//2.5更新转出账户
accountDao.updateAccount(source);

int i=1/0;//异常源 byzero

//2.6更新转入账户
accountDao.updateAccount(target);
}

junit单元测试
@Test
public void testTransfer(){

accountService.transfer("aaa","bbb",100f);

}





 

Guess you like

Origin www.cnblogs.com/yitaqiotouto/p/12607810.html