Faizan Mohammad
Faizan Mohammad

Reputation: 33

Use case of detaching entity from persistence context?

When do we need to detach entity from persistence context ?

Upvotes: 0

Views: 92

Answers (1)

Rakesh
Rakesh

Reputation: 594

The detachment of entity means, the hibernate doesn't have the access to the entity anymore. Lets see using the below example.

//Thid is where the entity is in transient State (Ther data is not saved, but initialized)
User user = new user
user.setName("User1");
Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = (StandardServiceRegistryBuilder) new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    ServiceRegistry serviceRegistry = builder.build();
    SessionFactory factory = configuration.buildSessionFactory(serviceRegistry);

    Session session = factory.openSession();
    Transaction tx = session.beginTransaction();
    user.setUserName("Hello There");//Here the data is in persistent state
    session.save(user);
    user.setUserName("Hello There Again");//Here also the data is in persistent state
            user.setUserName("Hello There Again for second time");//Here also the data is in persistent state, but the hibernate will take the last update, if you see the query in log/console, you will find only one update query.
    tx.commit();
    session.close();
    user.setUserName("Hello Again Final");//Since the session is closed, the data is not persisted, Here the entity is detached
    factory.close();
    StandardServiceRegistryBuilder.destroy(serviceRegistry);

The detachment of the entity occurs after you close the database, usually happens once you do a session.close().

More information on workflows can be found here https://javabrains.io/courses/hibernate_run/lessons/Understanding-State-Changes

Upvotes: 1

Related Questions