Elbek
Elbek

Reputation: 3484

Hibernate object state

I am testing Hibernate here is the situation and code:

public static void main(String[] args) {
    SessionFactory factory = HibernateUtil.getSessionFactory();
    Tag tag;

    // (case A)    
    Session session = factory.getCurrentSession();
    Transaction tx = session.beginTransaction();
    tag = (Tag) session.get(Tag.class, 1);
    tag.setName("A");
    tx.commit();
    // session is automatically closed since it is current session and I am committing the transaction
    // session.close();     

    //here the tag object should be detached

    //(case B)
    session = factory.getCurrentSession();
    tx = session.beginTransaction();
    // tag = (Tag) session.merge(tag); // I am not merging
    tag.setName("B"); //changing
    // session.update(tag); 
    tx.commit();
    // session.close();
}

It does not updates for case B (tag.setName("B") does not work).

Then I uncomment session.update(tag); in case B, now it is working. It should give error due to object is not merged to case B transaction.

We may say we are using factory.getCurrentSession() that is why no need to merge it, but if replace it with factory.openSession(); and closing session after each case it is still working (with calling update in case B). So in what sense we call an object is detached?

Upvotes: 3

Views: 2953

Answers (1)

Nandkumar Tekale
Nandkumar Tekale

Reputation: 16158

case A : session is not closed, and object tag is in persistent state and it(tag object) is attached with current session.

case B : here session may be same from first transaction, you change value of tag object which is in Persistent state. Persistent state represents existence of object in permanent storage. There will be connection between the object in memory and in database through the identifier. Any change in either of these two will be reflected in other (when transaction is committed). Persistent state is dependent on session object. First, session has to be open (unclosed)[this is true in your case], and second, the object has to be connected to the session. If either of these two is not true, then the object moves into either transient state or detached stage.

Object is in detached state in following case : Detached state arises when a persistent state object is not connected to a session object. No connection may be because the session itself is closed or the object is moved out of session.

Upvotes: 2

Related Questions