Loading a Persistent Object

In this post under hibernate, I will explain how to load a persistent object from the database.

We load a persistent object using Session interface “load” method.

Several overloadded version of the “load” method exists, all these methods require the primary key id of the object to be loaded.

Below is the complete code

Main Class


1  import org.hibernate.Session;
2  import org.hibernate.SessionFactory;
3  
4  public class HibernateDemo4 {
5   public static void main(String[] args) {
6          SessionFactory sessionFactory = HibernateUtil.createSessionFactory();
7          Session session = sessionFactory.openSession();
8          
9          Message message = new Message();
10         message.setMessage("Hello World");
11         
12         session.beginTransaction();
13         int id = (Integer)session.save(message);
14         session.getTransaction().commit();
15         
16         session.close();
17         
18         session = sessionFactory.openSession();
19         
20         message = null;
21         message = session.load(Message.class, id);
22         System.out.println(message);
23         
24         session.close();
25         
26         HibernateUtil.shutdown();
27  }
28 }

Between line 7 and 16, we create a transient object of Message class and save it in the database using save method.

The method returns the id of the newly saved object.

We use that id to load the object using load method at line 21.

Leave a Reply