休眠 session.save() 不反映在数据库中 [英] hibernate session.save() does not reflect in database
问题描述
根据我在hibernate中的理解(请确认)
According to my understanding in hibernate (please confirm)
1- 如果您通过 getSessionFactory().openSession()
获得它,您必须 session.close()
.
2- 如果您通过 getSessionFactory().getCurrentSession()
获得它,则无需 session.close()
.commit() 之后它会自动关闭.
1- You have to session.close()
if you get it by getSessionFactory().openSession()
.
2- No need to session.close()
if you get it by getSessionFactory().getCurrentSession()
. It is automatically closed after commit().
3- @2 使用 getSessionFactory().getCurrentSession()
时,我们必须在活动事务中执行所有数据库活动,以便我们可以在结束.
3- @2 When using getSessionFactory().getCurrentSession()
, we have to do all DB activities inside an active transaction so that we can commit() at the end.
4- Hibernate 将所有保存、更新和删除操作排入队列,并仅在 flush() 操作或 提交事务或关闭会话,其中发生这些操作.(根据 javadoc)
4- Hibernate en-queues all save, update, and delete operations and submits them to the database server only after a flush() operation or committing the transaction or closing of the session in which these operations occur.(as per javadoc)
从以上几点如果我考虑1 &4,那么下面的代码应该可以工作:
From the above points if I consider 1 & 4, then the following code should work:
Session session = HibernateUtil.getSessionFactory().openSession();
AccountDetails ac = new AccountDetails();
//perform set operations
session.save(ac);
session.close();
System.out.println("new account stored.");
但是它不工作,即它运行平稳但没有反映(存储)在数据库中.为什么会这样?当我在事务中编写代码并提交时,它就会被存储.
BUT it is not working i.e. it runs smoothly but does not reflect(store) in database.Why this is so ? When I write the code inside a transaction and commit, then it is stored.
我想我错过了一个基本的东西.请澄清.
I think I am missing a basic thing. Please clarify.
推荐答案
当您使用 SessionFactory.openSession() 创建会话时,不会创建任何事务,因此您的操作是在事务上下文之外执行的.为了查看您的更改,您必须开始一个新事务,或者将您的操作作为正在进行的事务的一部分来执行.来自文档:
When you create session using SessionFactory.openSession(), no transaction is created, so your operations are executed outside of transaction context. In order to see your changes, you have to start a new transaction, or perform your operations as a part of ongoing transaction. From documentation:
一个典型的交易应该使用以下习惯用法:
A typical transaction should use the following idiom:
Session sess = factory.openSession();
Transaction tx;
try {
tx = sess.beginTransaction();
//do some work
...
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
sess.close();
}
这篇关于休眠 session.save() 不反映在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!