SSH框架下数据库事务锁等待问题

最近接手使用SSH开发一个信息管理系统,遇到了数据库事务锁等待的问题。具体表现就是系统运行使用一段时间后, 数据库无法插入修改数据的问题。经过排查问题出在事务管理代码上。
以下是示例代码

public String someMethod(){
        DefaultTransactionDefinition def=new DefaultTransactionDefinition();
        TransactionStatus status=transactionManager.getTransaction(def);
        try{
				if(someObject==null){
					//put error message in Session
					this.getSession().put("errorMsg","someObject is null.");
					return ERROR;
				}
                //update or insert or delete some date
        
                transactionManager.commit(status);
                return SUCCESS;
        
        }catch(Exception e){
                e.printStackTrace();
				this.getSession().put("errorMsg", "something is wrong");
                transactionManager.rollback(status);
                return ERROR;
        }
}
 

ERROR和SUCCESS在Struts中进行了配置,有统一的页面来显示成功和错误信息。 以上代码的问题出在事务管理的try块中,如果其中someObject为null,则返回错误页面提示错误信息,而在return ERROR前没有rollback。

在return ERROR前将事务rollback即可解决问题。


public String someMethod(){
        DefaultTransactionDefinition def=new DefaultTransactionDefinition();
        TransactionStatus status=transactionManager.getTransaction(def);
        try{
				if(someObject==null){
					//put error message in Session
					this.getSession().put("errorMsg","someObject is null.");
					transactionManager.rollback(status);
					return ERROR;
				}
                //update or insert or delete some date
        
                transactionManager.commit(status);
                return SUCCESS;
        
        }catch(Exception e){
                e.printStackTrace();
				this.getSession().put("errorMsg", "something is wrong");
                transactionManager.rollback(status);
                return ERROR;
        }
}
 
该具体应用在判断某些条件不成立的时候返回错误提示,但此时数据库的事务已经存在,在返回错误提示时需要将事务rollback,否则数据库会一直维持事务状态,数据也就无法插入修改和删除了。
实际上数据库事务的成本是非常高的,建议先进行各种错误判断,最后进行事务操作。如果是在高性能,高并发,同时对数据一致性要求不高的情况下,可以干脆不使用事务。
以上是个人的一点看法,小弟刚入门Web开发,大家一起交流~

猜你喜欢

转载自bdkj.iteye.com/blog/1750746
今日推荐