springside 删除数据库的记录的疑义

在研究SpingSide  Hibernate  DAO层。对数据的操作时发现了一个非常奇怪的问题。

我通过一个java 的主程序 main() 方法 去调用HibernateDao()里的删除方法。console 控制台只有查询出对象的操作,没有输出删除的操作。程序这样操作的。

主程序 main() 方法这样定义

SessionFactory sf2 = new Configuration().configure().buildSessionFactory();
HibernateDao hd = new HibernateDao(sf2,Test.class);
hd.delete(6); //6 是test 表里的id主键。

在HibernateDao 继承了SimpleHibernateDao类,在simpleHibernateDAO中 delete()方法抵用get(id) 获取这个对象,然后传入delete(final T entity)对象的删除操作。这个删除的方法是这样定义的。

Assert.notNull(entity, "entity不能为空");
Transaction tx = this.getSession().beginTransaction();
this.getSession().delete(entity);
tx.commit();
this.getSession().close();
logger.debug("delete entity: {}", entity);

程序运行控制台不报错误。但是却没有输出Hibernate的删除的sql语句。

我把出现的问题放到getSession() 中获得的session 是否是主程序传递过来的SessionFactory。

getSeesion的方法是这样定义的。

this.session=this.sessionFactory.openSession();
return this.session;

测试sessionFactory 就是主程序 SessionFactory sf2 = new Configuration().configure().buildSessionFactory(); 就是传递过来的sessionFactory。

查看simpleHibernateDAO的构造函数

public SimpleHibernateDao(SessionFactory sessionFactory, final Class entityClass) {
this.sessionFactory = sessionFactory;
this.entityClass = entityClass;
//this.session =sessionFactory.openSession();
}
也很正常,没有错误。

于是我在SimpleHibernateDao构造函数中最后一行加入this.session =sessionFactory.openSession();  不用getSession() 方法获取session,就可以执行删除操作了。

很奇怪,为什么这样就能删除对象呢。详细测试程序在附件中。


public void update(Object o){
Session session=this.getSession();
Transaction tx = session.beginTransaction();
session.update(o);
tx.commit();
this.closeSession(session);
}
public void closeSession(){
try
{
if(session!=null){
session.close();
session=null;
}
}catch(Exception ex)
{
ex.printStackTrace();
}

}
你这么写试试

Transaction tx = this.getSession().beginTransaction();
this.getSession().delete(entity);
tx.commit();
this.getSession().close();

你这个问题,首先this.getSession().beginTransaction(); 和this.getSession().delete(entity); 所获得的 Session对象不是一个对象,执行DELETE方法的那个session没有执行事务,所以运行不成功