1.加入jar包
aopalliance-1.0.jar
commons-collections.jar
commons-dbcp.jar
commons-logging-1.1.1.jar
commons-pool.jar
junit-4.4.jar
jstl.jar
log4j-1.2.15.jar
mysql-connector-java-5.1.6-bin.jar
spring-aop-2.5.6.jar
spring-beans-2.5.6.jar
spring-context-2.5.6.jar
spring-context-support-2.5.6.jar
spring-core-2.5.6.jar
spring-jdbc-2.5.6.jar
spring-tx-2.5.6.jar
spring-test-2.5.6.jar
spring-web-2.5.6.jar
spring-webmvc-2.5.6.jar
standard.jar
2.配置中事务的配置
<bean id="zsTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="transactionManager" transaction-manager="zsTransactionManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException" />
<tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.RuntimeException" />
<tx:method name="add*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.RuntimeException" />
<tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="select*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
3.单元测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/applicationContext.xml" })
@Transactional
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class admininfotest {
//private ApplicationContext applicationContext;
@Autowired
private AdmininfoService admininfoService ;
@Test
public void testFindadmininfobyid() throws Exception{
Admininfo admininfo =new Admininfo();
admininfo = admininfoService.getById(admininfo,"1");
System.out.println(admininfo);
}
@Test
public void testadd() throws Exception{
Admininfo admininfo =new Admininfo();
admininfo.setAname("wang2345678");
admininfo.setApassword("123456");
admininfo.setAlevel("1");
admininfoService.add(admininfo);
}
@ContextConfiguration(locations = "classpath:applicationContext.xml")导入配置文件。这时候,我们可以看出之前使用applicationContext.xml文件作为系统总控文件的好处! 当然,Spring-Test的这个配置只认classpath,很无奈,我必须拷贝这些文件到根目录!
@RunWith(SpringJUnit4ClassRunner.class)SpringJUnit支持,由此引入Spring-Test框架支持!
@Transactional这个非常关键,如果不加入这个注解配置,事务控制就会完全失效!
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)这里的事务关联到配置文件中的事务控制器(transactionManager = "transactionManager"),同时指定自动回滚(defaultRollback = true)。这样做操作的数据才不会污染数据库!