hibernate save失敗

這幾天正在使用hibernate進行數據庫的開發,通過myeclipse的hibernate reverse engieering生產的StuDao,其中的save方法並不能生效.

後來到網上查找了一下,找到了解決方法,但其中原因並不是很清楚.

原始的方法:

public void save(Stu transientInstance) {
        log.debug("saving Stu instance");
        try {

             getSession().save(transientInstance);

        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }

}


方法一:

public void save(Stu transientInstance) {
        log.debug("saving Stu instance");
        try {
            Session session = getSession();
            Transaction tran = session.beginTransaction();
            session.save(transientInstance);
            tran.commit();
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }

}


方法二:

在hibernate配置文件hibernate.cfg.xml中添加如下語句

<property name="connection.autocommit">true</property>

修改代碼爲:

public void save(Stu transientInstance) {
     log.debug("saving Stu instance");
     try {
	getSession().save(transientInstance);
	getSession().flush();
	log.debug("save successful");
     } catch (RuntimeException re) {
	log.error("save failed", re);
	throw re;
     }
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章