我有以下代码在transaction
:
try {
//start transaction
repository.startTransaction();
//carry out deletion logic
repository.deletedata()
//commit all 3 transactions
repository.commitTransaction();
}catch (Exception e) {
repository.rollback();
}
目前,如果运行时有error
,则应用仍然继续运行。但是,我希望在回滚数据后执行程序停止。
我怎样才能做到最好?
答案 0 :(得分:1)
首先,要终止执行,您应该使用自己的业务级异常。
其次,陈述repository.rollback();
也可能失败。只是一个想法。
我的方法是:
class MyApp {
public static final main(){
new MyApp().run();
}
private void run(){
MyRepositoryProcessor proc = new MyRepositoryProcessor();
try {
// Some loop here maybe...
proc.deleteFromRepo();
} catch (MyDatabaseCommunicationException ex) {
System.exit(-1);
}
}
}
class MyRepositoryProcessor {
public void deleteFromRepo() throws MyDatabaseCommunicationException {
try {
//start transaction
repository.startTransaction();
//carry out deletion logic
repository.deletedata()
//commit all 3 operations
repository.commitTransaction();
}catch (Exception e) {
try {
repository.rollback();
} catch (Exception ex){
// Database connection failed completely, could not even do a rollback.
}
throw new MyDatabaseCommunicationException("Deletion failed");
}
}
}
答案 1 :(得分:0)
System.exit(0)?
您可以在http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
找到一些文档