09 - Working with Objects in Hibernate: Page 4 of 4

Case 6 - MergeBook.java – Update Object with same identifier which is already in session

  There will be no exception raised.

SessionFactory factory = cfg.buildSessionFactory();

Session session = factory.openSession();
Book book = (Book)session.get(Book.class, 4);

session.close();
Session session2=  factory.openSession();

Book book1 = (Book)session2.get(Book.class, 4);
Transaction tx = session2.beginTransaction();
    
book.setName("Hibernate  Tutorial !!!");

session2.merge(book);

tx.commit();
session2.close();

Hiberanate does provide a method saveOrUpdate() which save the object if there is no row available for given identifier and update the row if found. In case object with the same identifier is available in session, it will throw an exception.

Let’s create SaveOrUpdateBook.java

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.tutorial.hibernate.Book;

public class SaveOrUpdateBook {
    public static void main(String args[])
    {
       Configuration cfg = new Configuration().configure();        
        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();

        Book book = (Book)session.get(Book.class, 8);Book book = (Book)session.get(Book.class, 8);

        session.close();

        Session session2=  factory.openSession();

        Transaction tx = session2.beginTransaction();

        book.setAuthor("Author");

       session2.saveOrUpdate(book);

       Book book2  =new Book();
       book2.setAuthor("Book2 Author");
       book2.setName("Hibernate Book !!");

       session2.saveOrUpdate(book2);

       tx.commit();
       session2.close();

       factory.close();
    }
}

 

Update code to call saveOrUpdate method on object  with same identifier is available in session, it will throw an exception.

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.tutorial.hibernate.Book;

public class SaveOrUpdateBook {

       public static void main(String args[])
       {
         Configuration cfg = new Configuration().configure();        
         SessionFactory factory = cfg.buildSessionFactory();
         Session session = factory.openSession();
         Book book = (Book)session.get(Book.class, 8);
 
         session.close();

        Session session2=  factory.openSession();        
        Transaction tx = session2.beginTransaction();        
        Book book3 = (Book)session2.get(Book.class, 8);
 
        book.setAuthor("Author");        
        session2.saveOrUpdate(book);

        tx.commit();
        session2.close();

        factory.close();
    }
}


 

 

Like us on Facebook