java的事务运用
这个若要想成为公共的就要写在baseDaoImpl中。因为这个要继承 HibernateDaoSupport,然后在dao及其他相关里的进行继承、实现
session= getHibernateTemplate().getSessionFactory().openSession();
这句是关键在之前没有写这句时总是会报一个org.springframework.transaction.TransactionSystemException:
Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started
at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:661)
不过在用了opensession这个方法后必须在后面给它手动关闭session.close()
/****
* 这是利用事务来进行批处理的操作 用户只需传入hql的集合,
*/
public List <String> deleteSiteBySite(final List<String> list )
{
// TODO Auto-generated method stub
return (List <String>) this.getHibernateTemplate().execute(new HibernateCallback()
{
public Object doInHibernate(Session session)throws HibernateException, SQLException
{
List <String> result=new ArrayList<String>();
session= getHibernateTemplate().getSessionFactory().openSession();
session.beginTransaction();
// TODO Auto-generated method stub
try
{
String re="";
for(int i=0; i<list.size();i++)
{
int a = session.createSQLQuery(list.get(i)).executeUpdate();
if(a<0)
{
re=re+"*";
}
}
if (re=="")
{
session.getTransaction().commit();
result.add("success");
}
else
{
session.getTransaction().rollback();
result.add("error");
}
}
catch (Exception e)
{
session.getTransaction().rollback();
result.add("error");
}
finally{session.close();}
return result;
}
});
}
附上两张出错的图片 方便以后查阅