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;
4  public class HibernateDemo4 {
5   public static void main(String[] args) {
6          SessionFactory sessionFactory = HibernateUtil.createSessionFactory();
7          Session session = sessionFactory.openSession();
9          Message message = new Message();
10         message.setMessage("Hello World");
12         session.beginTransaction();
13         int id = (Integer)session.save(message);
14         session.getTransaction().commit();
16         session.close();
18         session = sessionFactory.openSession();
20         message = null;
21         message = session.load(Message.class, id);
22         System.out.println(message);
24         session.close();
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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s