10.5. 修改持久对象

事务中的持久实例(就是通过session装载、保存、创建或者查询出的对象) 被应用程序操作所造成的任何修改都会在Session刷出(flushed)的时候被持久化(本章后面会详细讨论)。 这里不需要调用某个特定的方法(比如update(),设计它的目的是不同的)将你的修改持久化。 所以最直接的更新一个对象的方法就是在Session处于打开状态时load()它,然后直接修改即可:

DomesticCat cat = (DomesticCat) sess.load( Cat.class, new Long(69) );
cat.setName("PK");
sess.flush();  // changes to cat are automatically detected and persisted

有时这种程序模型效率低下,因为它在同一Session里需要一条SQL SELECT语句(用于加载对象) 以及一条SQL UPDATE语句(持久化更新的状态)。 为此Hibernate提供了另一种途径,使用脱管(detached)实例。

Note that Hibernate does not offer its own API for direct execution of UPDATE or DELETE statements. Hibernate is a state management service, you don't have to think in statements to use it. JDBC is a perfect API for executing SQL statements, you can get a JDBC Connection at any time by calling session.connection(). Furthermore, the notion of mass operations conflicts with object/relational mapping for online transaction processing-oriented applications. Future versions of Hibernate may however provide special mass operation functions. See 第 13 章 批量处理(Batch processing) for some possible batch operation tricks.