Spring事務處理(註解版)
準備:jdbc.properties
第一步:連線資料庫
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
第二步:書寫Dao層和Service層
//Dao層
public class AccountDao extends JdbcDaoSupport {
public AccountDao() {
}
//出錢
public void out(String name,double monney){
String sql="update account set monney=monney-? where name=? ";
Object[] paramarr={monney,name};
this.getJdbcTemplate().update(sql,paramarr);
}
//金錢
public void in(String name,double monney){
String sql="update account set monney=monney+? where name=? ";
Object[] paramarr={monney,name};
this.getJdbcTemplate().update(sql,paramarr);
}
}
//service層
public class AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao){
this.accountDao=accountDao;
}
@Transactional
public void transaction(String name1,String name2,Double monney){
accountDao.out(name1,monney);
int num=1/0;
accountDao.in(name2,monney);
}
}
第三步:配置Dao層和Service層
<!--配置dao層-->
<bean id="accountDao" class="it.heima.dao_annotation.AccountDao">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置service層-->
<bean id="accountService" class="it.heima.service_annotation.AccountService">
<property name="accountDao" ref="accountDao"/>
</bean>
第四步:開啟事務註釋
<!--開啟事務註釋-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>