📄 transactions.html
字号:
foo.setProperty("bar");session = factory.openSession();session.saveOrUpdate(foo);session.flush();session.connection().commit();session.close();</pre><p> 你也可以调用<tt class="literal">lock()</tt>而非<tt class="literal">update()</tt>,如果你确信对象没有被修改过,可以使用<tt class="literal">LockMode.READ</tt>(进行一次版本检查,而跳过所有的缓存)。 </p></div><div class="sect2" lang="zh-cn"><div class="titlepage"><div><div><h3 class="title"><a name="transactions-optimistic-manual"></a>10.4.3. 应用程序自己进行版本检查</h3></div></div><div></div></div><p> 每当一个新的<tt class="literal">Session</tt>中与数据库出现交互的时候,这个session会在操作持久化实例前重新把它们从数据库中装载进来。我们现在所说的方式就是你的应用程序自己使用版本检查来确保应用事务的隔离性。(当然,Hibernate仍会为你<span class="emphasis"><em>更新</em></span>版本号)。从数据库访问方面来看,这种方法是最没有效率的,与entity EJB方式类似。 </p><pre class="programlisting">// foo is an instance loaded by a previous Sessionsession = factory.openSession();int oldVersion = foo.getVersion();session.load( foo, foo.getKey() );if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException();foo.setProperty("bar");session.flush();session.connection().commit();session.close();</pre><p> 当然,如果在低数据并行(low-data-concurrency)的环境中,并不需要版本检查,你仍可以使用这个方法,只需要忽略版本检查。 </p></div></div><div class="sect1" lang="zh-cn"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="transactions-disconnection"></a>10.5. 会话断开连接(Session disconnection)</h2></div></div><div></div></div><p> The first approach described above is to maintain a single <tt class="literal">Session</tt> for a whole business process thats spans user think time. (For example, a servlet might keep a <tt class="literal">Session</tt> in the user's <tt class="literal">HttpSession</tt>.) For performance reasons you should </p><p> 上面提到的第一种方法是对于对一个用户的一次登录产生的整个商业过程维护一个<tt class="literal">Session</tt>。(举例来说,servlet有可能会在用户的<tt class="literal">HttpSession</tt>中保留一个<tt class="literal">Session</tt>)。为性能考虑,你必须 </p><div class="orderedlist"><ol type="1" compact><li><p> 提交<tt class="literal">Transaction</tt>(或者JDBC连接),然后 </p></li><li><p> (在等待用户操作前,)断开<tt class="literal">Session</tt>与JDBC连接。 </p></li></ol></div><p> <tt class="literal">Session.disconnect()</tt>方法会断开会话与JDBC的连接,把连接返还给连接池(除非是你自己提供这个连接的)。 </p><p> <tt class="literal">Session.reconnect()</tt>方法会得到一个新的连接(你也可以自己提供一个),重新开始会话。在重新连接后,你可以通过对任何可能被其它事务更新的对象调用<tt class="literal">Session.lock()</tt>方法,来强迫对你没有更新的数据进行版本检查。你不需要对<span class="emphasis"><em>正在</em></span>更新的数据调用lock()。 </p><p> 这是一个例子: </p><pre class="programlisting">SessionFactory sessions;List fooList;Bar bar;....Session s = sessions.openSession();Transaction tx = null;try { tx = s.beginTransaction(); fooList = s.find( "select foo from eg.Foo foo where foo.Date = current date" // uses db2 date function ); bar = (Bar) s.create(Bar.class); tx.commit();}catch (Exception e) { if (tx!=null) tx.rollback(); s.close(); throw e;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -