目录

10.5. 修改持久对象

优质
小牛编辑
113浏览
2023-12-01

事务中的持久实例(就是通过 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)实例。

重要

Hibernate does not offer its own API for direct execution of UPDATE or DELETE statements. Hibernate is a state management service, you do not 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 can, however, provide special mass operation functions. See 第 14 章 批量处理(Batch processing) for some possible batch operation tricks.