在
service
类前加上
@Transactional
,声明这个
service
所有方法需要事务管理。每一个业务方法开始时都会打开一个事务。
Spring
默认情况下会对运行期例外
(RunTimeException)
进行事务回滚。这个例外是
unchecked
如果遇到
checked
意外就不回滚。
如何改变默认规则:
1
让
checked
例外也回滚:在整个方法前加上
@Transactional
(rollbackFor=Exception.
class
)
2
让
unchecked
例外不回滚:
@Transactional
(notRollbackFor=RunTimeException.
class
)
3
不需要事务管理的
(
只查询的
)
方法:
@Transactional
(propagation=Propagation.
NOT_SUPPORTED
)
在整个方法运行前就不会开启事务
还可以加上:
@Transactional
(propagation=Propagation.
NOT_SUPPORTED
,readOnly=
true
)
,这样就做成一个只读事务,可以提高效率。
(6)
CompanyService.java
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.dao.CompanyDao;
import com.entry.TCompanyInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.dao.CompanyDao;
import com.entry.TCompanyInfo;
@Service("companyService")
@Transactional
@Transactional
public class CompanyService {
@Resource(name="companyDao")
private CompanyDao companyDao;
public void setCompanyDao(CompanyDao companyDao) {
this.companyDao = companyDao;
}
this.companyDao = companyDao;
}
public CompanyDao getCompanyDao() {
return companyDao;
}
@Transactional(readOnly=false,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})//readOnly=true慎用(不可写事务)
public void test(TCompanyInfo tc){
try{
companyDao.createObj(tc);
String s=null;
s.length(); //假设会抛出NullPointerException,就会执行catch里的,如果不在catch里throw一个
return companyDao;
}
@Transactional(readOnly=false,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})//readOnly=true慎用(不可写事务)
public void test(TCompanyInfo tc){
try{
companyDao.createObj(tc);
String s=null;
s.length(); //假设会抛出NullPointerException,就会执行catch里的,如果不在catch里throw一个
RuntimeException子类,依然不会rollback
}
catch(Exception e){
//throw new Exception("runtimeException");
System.out.println("exception");
throw new NumberFormatException("format exception"); //重抛一个Exception,才能rollback
}
}
}
}
catch(Exception e){
//throw new Exception("runtimeException");
System.out.println("exception");
throw new NumberFormatException("format exception"); //重抛一个Exception,才能rollback
}
}
}
在Spring里,同样只会rollback unchecked exception(RuntimeExcption及子类),而checked exception(Exception及子类)是不会rollback的,除非你特别声明。
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW,rollbackFor = {MyException1.class,MyException2.class})
因此所有在service层方法中用throws定义的Exception,都必须在事务定义中进行rollback设定。(请勿善忘)
所有在service层方法中被catch处理了的异常,又希望容器辅助rollback的话,必须重抛一个预定义的RuntimeException的子类。(请勿回望)