Jfinal中手动提交/回滚 事物
在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"));//指定方法名称匹配
}