这几天正在使用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;
}
}