Hibernate插入数据成功,不报错,但是数据库中没有值?

版权声明:努力去改变!!! https://blog.csdn.net/lq1759336950/article/details/89606512

今天在使用struts2+HIbernate时进行插入操作时,SQL语句已经打印,但是数据库中没值,很是纳闷,经过仔细查找并查阅相关资料,发现Hibernate在生成DAO时并没有为我们提交事务,实例代码:

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

这是Hibernate自动生成的代码,因为没有提交事务,导致虽然程序不报错,但数据就是不能加入数据库中,因此,应该这样写:

public void save(Users transientInstance) {
		log.debug("saving Users instance");
		/********************获取sessionFactory对象**********/
		Transaction tx=getSession().beginTransaction();
		try {
			getSession().save(transientInstance);
			log.debug("save successful");
			/***************提交事务*****************/
			tx.commit();
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}finally{
		/****************************关闭SessionFactory***************************/
			HibernateSessionFactory.closeSession();
		}
	}

这样写就能保证事务提交了,数据库中便可添加数据!

猜你喜欢

转载自blog.csdn.net/lq1759336950/article/details/89606512