0

Как известно у Hibernate сущностей есть 3 основных состояния:

  1. transient объект который еще не связан не с сессией.
  2. persistent объект который связан с открытой сессией.
  3. detached объект который уже не связан с открытой сессией.

Поправьте меня пожалуйста если я написал не верно.

Но если все так, то получается что transient и detached практически не отличимы если transient объект был заполнен данными не через базу и поля у него не null? Или transient объект может считаться только если он пустой, тоесть создан при помощи конструктора без параметров и поля имеют значения по умолчанию?

Помогите более детально разобраться в разнице между состояниями, в отношении четких критериев каким требованиям объект должен соответствовать чтобы считаться transient, persistent, detached.

2 ответа 2

8

Цитата из документации:

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).

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.

Detached - a detached instance is an object that has been persistent, but its Session has been closed. 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 a later 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.

Объект проходит состояния в следующем порядке: Transient -> Persistent -> Detached
Объект находится в состоянии Transient после его создания (Person person = new Person();) и до момента сохранения (Long id = (Long) session.save(person);).
После сохранения объекта (либо при чтении ранее сохраненного объекта из БД) он находится в состоянии Persistent пока не закрыта сессия. После закрытия сессии объект становится Detached.
Подытоживая вышесказанное:

Но если все так, то получается что transient и detached практически не отличимы если transient объект был заполнен данными не через базу и поля у него не null? Или transient объект может считаться только если он пустой, тоесть создан при помощи конструктора без параметров и поля имеют значения по умолчанию?

Объект transient если он был создан при помощи конструктора (какой был контруктор (по умолчанию или с параметрами) и какие значения имеют поля - неважно) и не был сохранен.

каким требованиям объект должен соответствовать чтобы считаться transient, persistent, detached

Состояние зависит от того, связан ли объект с БД (сохранялся или нет) и от состояния сессии.

2

Pavel, открою Вам тайну - у entity предусмотрено четыре состояния. Отцы-основатели HIBERNATE в своей книге называют следующие названия: transient, persistent, detached и removed. В спецификации JPA 2.1 их тоже четыре, но с немного другими именами: new, managed, detached и removed. New и detached сходны между собой в том, что они не хранятся в кэш первого уровня, а отличаются тем, что у new нет в БД образа (с тем же ID), а у detached - есть. JPA 2.1 предполагает разную реакцию new и detached объектов на действия. Например, если применить метод persist к new, то он станет managed, а если применить метод persist к detached, то должна быть поднята ошибка.

Sometimes you need to know whether an entity instance is transient, persistent, or detached. An entity instance is in persistent state if EntityManager#contains(e) returns true. It’s in transient state if PersistenceUnitUtil#getIdentifier(e) returns null. It’s in detached state if it’s not persistent, and Persistence- UnitUtil#getIdentifier(e) returns the value of the entity’s identifier property. You can get to the PersistenceUnitUtil from the EntityManagerFactory.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.