Deleting a persisted object

In this post under hibrenate, I will explain how to delete a persisted object.

We can delete a persisted object using Session interface delete method.

Below is the complete code

Main Class


1  import org.hibernate.Session;
2  import org.hibernate.SessionFactory;
3  
4  public class HibernateDemo9 {
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.get(Message.class, id);
22         System.out.println(message);
23         
24         session.beginTransaction();
25         session.delete(message);
26         session.getTransaction().commit();
27         session.close();
28         
29         session = sessionFactory.openSession();
30         
31         message = null;
32         message = session.get(Message.class, id);
33         System.out.println(message);
34         session.close();
35         
36         HibernateUtil.shutdown();
37  }
38 }

In the above code, between line 7 to 16, in a new session, I create a Message object, save it and close the session.

We confirm that the object is saved by calling the get method at line 21 in a new session.

At line 25, in a new session, I delete the object by calling the delete method in a new transaction, commit the transaction and close the session.

We confirm that the object is deleted by again calling the get method in a new session.

This time the get method will return null since the object is deleted.

Leave a Reply