05_传智播客hibernate教程_实体对象的三种状态与saveOrUpdate方法 1

为什么要关注对象及其状态?而不是sql语句?

Hibernate is a full object/relational mapping solution that not only shields the developer from

the details of the underlying database management system, but also offers state management

of objects. This is, contrary to the management of SQL statements in common JDBC/SQL

persistence layers, a natural object-oriented view of persistence in Java applications.

In other words, Hibernate application developers should always think about the state of their

objects, and not necessarily about the execution of SQL statements. This part is taken care of

by Hibernate and is only relevant for the application developer when tuning the performance of

the system.

   

Hibernate object states

Hibernate defines and supports the following object states:

Transient - an object is transient if it has just been instantiated using the new operator, and it

is not associated with a Hibernate Session. It has no persistent representation in the database

and no identifier value has been assigned. Transient instances will be destroyed by the garbage

collector if the application does not hold a reference anymore. Use the Hibernate Session to

make an object persistent (and let Hibernate take care of the SQL statements that need to be

executed for this transition).

1 数据库中不存在与瞬时对象相对应的记录 (根据配置文件unsaved-value来判断)

2 没有hibernate根据配置文件设置主键生成生成策略分配的identifier

Persistent - a persistent instance has a representation in the database and an identifier value.

It might just have been saved or loaded, however, it is by definition in the scope of a Session.

Hibernate will detect any changes made to an object in persistent state and synchronize the

state with the database when the unit of work completes. Developers do not execute manual

UPDATE statements, or DELETE statements when an object should be made transient.

1 数据库中存在与持久对象相对应的记录

2 hibernate根据配置文件设置主键生成生成策略分配的identifier

3 通过执行saved (从对象到sessionor loaded(从dbsession

4 因为持久对象在session的管理范围之内 hibernate 可以将 持久对象的任何改变在事务提交时同步到数据库中(对持久对象调用update方法没有意义)

 

Detached - a detached instance is an object that has been persistent, but its Session has been closed. (注意这句话,如果这个对象在session被删除了,那么这个对象是什么状态?)The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at alater point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.

1 脱管对象 是曾经容纳过这个持久对象的session,现在已经关闭了。(脱管对象有identifier,

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章