spring.xml 增加如下配置
<!--数据源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbcDriver}" />
<property name="url" value="${jdbcUrl}" />
<property name="username" value="${jdbcUname}" />
<property name="password" value="${jdbcUpwd}" />
</bean>
<!-- 项目的事务管理 控制在service层 -->
<!-- spring提供了声明式的事务管理器 -->
<!-- 1:创建一个事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 引入数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 2:配置事务的传播特性 (增强类的增强效果),这一部分可以不加,加上比较保险-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 配置切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.ssm.service.impl.*.*(..))" />
</aop:config>
使用 在servlice层引入@Transactional注解
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yitian.ssm.dao.UserinfoMapper;
import com.yitian.ssm.entity.Userinfo;
import com.yitian.ssm.entity.UserinfoExample;
import com.yitian.ssm.service.UserService;
@Service
@Transactional
public class UserServiceImpl implements UserService{
@Autowired
private UserinfoMapper um;
@Override
public List<Userinfo> findByUnameAndUpwd(UserinfoExample example) {
List<Userinfo> list=(List<Userinfo>) um.selectByExample(example);
return list;
}
//如果有删除有增加,或者其他,必须controller在请求service层1次,不能先调用del() 在调用add(),这种情况不是一个事务,容易出错!
public int add(){
del();
return 0;
}
public int del(){
return 0;
}
}