Under_stand
Under_stand

Reputation: 69

Does session.getTransaction().commit() closes session in hibernate?

I am beginner in hibernate i just want to know whether object is detached from only session.close() or with session.getTransaction().commit() also.Because i can't update object from another transaction it throws an exception.

Here is my code.

package com.steve.hibernate.HibernateDemo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.steve.hibernate.HibernateDemo.entity.Student;

/**
 * Hello world!
 *
 */
public class App {
    public static void main(String[] args) {
        SessionFactory sessionFactory = new Configuration().configure().addAnnotatedClass(Student.class)
                .buildSessionFactory();

        Session session = sessionFactory.getCurrentSession();

        session.beginTransaction();
        Student student = session.get(Student.class, 17);
        System.out.println(student);
        session.getTransaction().commit();

        session.beginTransaction();
        student.setFirstName("BOOM");
        session.getTransaction().commit();

        session.close();

        sessionFactory.close();

    }
}

Output:

Hibernate: select student0_.id as id1_0_0_, student0_.email as email2_0_0_, student0_.first_name as first_na3_0_0_, student0_.last_name as last_nam4_0_0_ from student student0_ where student0_.id=?
Student [id=17, firstName=BOOM, lastName=asd, [email protected]]
Exception in thread "main" java.lang.IllegalStateException: Session/EntityManager is closed
    at org.hibernate.internal.AbstractSharedSessionContract.checkOpen(AbstractSharedSessionContract.java:357)
    at org.hibernate.engine.spi.SharedSessionContractImplementor.checkOpen(SharedSessionContractImplementor.java:138)
    at org.hibernate.internal.AbstractSharedSessionContract.beginTransaction(AbstractSharedSessionContract.java:449)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:350)
    at com.sun.proxy.$Proxy33.beginTransaction(Unknown Source)
    at com.steve.hibernate.HibernateDemo.App.main(App.java:25)

If object can be detached from session.close() only why i can't update my value of persistent object?

Upvotes: 0

Views: 941

Answers (1)

Avinash Singh Bagri
Avinash Singh Bagri

Reputation: 1

You need not initialise another transaction. After you fetched the student, try updating it before committing as unless Flush mode is set to be manual, the transaction may be flushed which is the case here. Try doing it in single transaction.

Upvotes: 0

Related Questions