在Jfinal中有個Tx類為事物聲明類 在方法或controller上面加@Before({Tx.class})即可,可是這樣並不能滿足有的業務場景
下面是今天寫的手動提交的事物處理方法,希望對大家有用
public void test(){
Connection conn=null;
try
{
conn=DbKit.getConfig().getDataSource().getConnection();
DbKit.getConfig().setThreadLocalConnection(conn);
conn.setAutoCommit(false);//自動提交變成false
for(int i=0;i<=3;i++){
Department d=new Department();
d.set("DEPID", "department_id.nextval")
.set("DEPNAME", "測試"+i)
.set("SUPDEPID", 0)
.save();
//if(i>2) System.out.println(1/0); //測試只要其中有一個地方發生異常,就會回滾前面所有事物
}
conn.commit();
}
catch (Exception e)
{
try
{
if(null!=conn) conn.rollback();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
throw new ActiveRecordException(e);
}finally{
try
{
if(null!=conn){
conn.close();
}
}
catch (Exception e2)
{
e2.printStackTrace();
}finally{
DbKit.getConfig().removeThreadLocalConnection();
}
}
//一下是jfinal開發文檔中說明處理事物的示例
boolean succeed = Db.tx(new IAtom(){
public boolean run() throws SQLException {
int count = Db.update("update account set cash = cash - ? where id = ?", 100, 123);
int count2 = Db.update("update account set cash = cash + ? where id = ?", 100, 456);
return count == 1 && count2 == 1;
}});
在初始化configInterceptor方法中配置一下是方法名稱有事物處理實現
public void configInterceptor(Interceptors me) {
me.add(new TxByRegex(".*save.*"));//正則匹配
me.add(new TxByActionKeys("/cash/trans", "/other"));//訪問方法路勁匹配
me.add(new TxByActionMethods("save", "update"));//指定方法名稱匹配
}