Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); //Detached entity Country country = new Country(); country.setId(1); country.setName("India"); //Merging the state of detached entity Country mergedCountry = (Country)session.merge(country); tx.commit();
Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); //Fetching the persistent entity Country country = (Country) session.get(Country.class, 1); //Detaching the entity session.evict(country); //Updating the detached entity country.setName("USA"); //Merging the detached entity state Country mergedCountry = (Country)session.merge(country); tx.commit();In this example, we fetch a persistent entity from the database using the Hibernate Session object. Then we detach the entity from the session by calling the evict() method. After that, we update the detached entity state and call the merge() method to merge the updated state into the database. Finally, we commit the transaction. The org.hibernate Session merge() method is part of the Hibernate Core package library.