本文主要是在看了 关于spring声明式事务管理异常处理的测试和小结http://www.javaeye.com/topic/34867一文以后想写的,而且前段时间与jbpm整合的时候才发现自己的事务设置一直有问题,根本无法回滚(汗,都是网络上照抄的,没测试),再加上它的使用的spring版本1.2,所以觉得有必要自己再测试,加深影像。
对事务有任何不清楚的,可以参考一下这个 http://bhsc-happy.javaeye.com/blog/288983
开发环境:
OS:windows XP
Web Server: jakarta-tomcat-5.0.28
Databbse Server: MS SQL Server 2000 (打了SP3补丁)
IDE: MyEclipse 6.0.1
测试案例系统结构:
web层<---->Service层<---->DAO层
web层就是Struts2,DAO使用hibernate -3.3.1.GA-dist.zip,spring是spring-framework-2.5.5
数据库表和它一样吧:
student1和Student2,表结构相同:id,name,address.其中id为主键且为自增长型.
student1表中有一条记录:
测试情形一:
web层捕获异常并处理,DAO层不捕获异常,Service也不捕获异常.
Service层接口:
Java代码
- public interface Student1Service {
-
- void addStudent1(Student1 stu);
-
- }
-
- public interface StudentSService {
-
- void addStudent2(Student2 stu) throws SaveException;
-
- }
public interface Student1Service {
void addStudent1(Student1 stu);
}
public interface StudentSService {
void addStudent2(Student2 stu) throws SaveException;
}
Service实现
Java代码
- public void addStudent1(Student1 stu) {
- stufDAO.insertStuF(stu);
- }
-
- public void addStudent2(Student2 stu) throws SaveException {
- String[] aa={"ww","ww","ww"};
- for(int i=0;i<5;i++){
- System.out.println(aa);
- }
- stusDAO.insertStuS(stu);
- }
public void addStudent1(Student1 stu) {
stufDAO.insertStuF(stu);
}
public void addStudent2(Student2 stu) throws SaveException {
String[] aa={"ww","ww","ww"};
for(int i=0;i<5;i++){ //出错
System.out.println(aa);
}
stusDAO.insertStuS(stu);
}
DAO层接口
Java代码
- public interface StudentFDAO {
- void insertStuF(Student1 stu);
- }
-
- public interface StudentSDAO {
- void insertStuS(Student2 stu);
- }
public interface StudentFDAO {
void insertStuF(Student1 stu);
}
public interface StudentSDAO {
void insertStuS(Student2 stu);
}
DAO实现
Java代码
- public void insertStuF(Student1 stu) {
- getHibernateTemplate().save (stu);
- }
- public void insertStuS(Student2 stu) {
- getHibernateTemplate().save (stu);
- }
public void insertStuF(Student1 stu) {
getHibernateTemplate().save (stu);
}
public void insertStuS(Student2 stu) {
getHibernateTemplate().save (stu);
}
Action
Java代码
- public String execute() throws Exception{
- Student1 sti=new Student1(stu1Name,stu1Address);
- Student2 stu=new Student2(stu1Name,stu1Address);
- try{
- studentfService.addStudent1(sti);
- studentsService.addStudent2(stu);
- }catch(DataAccessException e){
- System.out.println(“error”);
- return “failer”:
- }
-
- return SUCCESS;
- }
public String execute() throws Exception{
Student1 sti=new Student1(stu1Name,stu1Address);
Student2 stu=new Student2(stu1Name,stu1Address);
try{
studentfService.addStudent1(sti);
studentsService.addStudent2(stu);
}catch(DataAccessException e){
System.out.println(“error”);
return “failer”:
}
return SUCCESS;
}
JSP
Java代码
-
-
-
名: | "text" value="stu1Name" name="stu1Name"> |
-
地址: | "text" value="stu1Address" name="stu1Address"> |
-
| "submit" value="提交" style="width:80px"> |
-