後端-框架-Spring-MyBatis-事物增強
阿新 • • 發佈:2018-11-11
後端-框架-Spring-MyBatis-事物增強
xml配置方式
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd " >
<!-- 資料來源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8& useSSL=true"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
<!-- 建立事物管理bean -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 事物增強 -->
<tx:advice id="txAdvice" transaction-manager="txManager" >
<tx:attributes>
<tx:method name="find*" timeout="1000"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 切點切面設定 -->
<aop:config>
<aop:pointcut id="userServiceImpl" expression="execution(* cn.smbms.service.*.*(..))"/>
<aop:advisor pointcut-ref="userServiceImpl" advice-ref="txAdvice"/>
</aop:config>
</beans>
註解方式
//註解主要是@Transactional("")
@Service("userService")
@Transactional("propagation=Propagation.REQUIRES_NEW")
public class UserServiceImpl implements UserService {
@Autowired
@Qualifier("userMapper")
private UserMapper userMapper;
public UserMapper getUserMapper() {
return userMapper;
}
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public List<User> findUsers(User user) {
return userMapper.getUserList(user);
}
@Override
public int addNewUser(User user){
return userMapper.add(user);
}
@Override
public int addNewUserList(List<User> users) {
int count = 0;
for(User user:users){
count += addNewUser(user);
// throw new RuntimeException("ERROR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
return count;
}
}