Skip to main content

Retrieve Data from table using Hibernate

Retrieve Data from table using Hibernate

We have already Create table Myphonebook now in this example we are going to Retrieve data of that table.
Myphonebook table
createphonebook

Program to Retrieve data from table

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.spy.hibernate.First;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class RetrieveContact 
{
 
public static void main(String[] args)
 
 {
 
 
    SessionFactory sf=newConfiguration().configure().buildSessionFactory();
 
    Session session=sf.openSession();
 
    session.beginTransaction();
 
    //this will Retrieve contact with index 1
    Myphonebook contact2= (Myphonebook)session.get(Myphonebook.class, 1);
 
    System.out.println("Contact name : "+contact2.getName());
 
    System.out.println("mobile Number: "+contact2.getMobilenumber());
 
 
 }
 
}

1
2
3
4
5
6
Output:
Hibernate: select myphoneboo0_.id as id0_0_, myphoneboo0_.mobilenumber as mobilenu2_0_0_, 
           myphoneboo0_.name as name0_0_ from Myphonebook myphoneboo0_ where myphoneboo0_.id=?
 
 Contact name : bhavesh
 mobile Number: 8866766995