Fetch the Data from Database using Hibernate Query
Here we are going to fetch the data of table emp1000 from the database using hibernate Query
Prerequisite: Hibernate libraries and ojdbc.jar already linked to the project.(Hibernate save data example)
Employees.java
package com.studyskymate.hib;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
//POJO
@Entity
@Table(name = "emp1000")
public class Employees {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String firstName, lastName;
public int getId()
{
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
2. TestHibernate2.java
package
com.studyskymate.hib;
import
java.util.List;
import
org.hibernate.Session;
import
org.hibernate.SessionFactory;
import
org.hibernate.Transaction;
import
org.hibernate.boot.Metadata;
import
org.hibernate.boot.MetadataSources;
import
org.hibernate.boot.registry.StandardServiceRegistry;
import
org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import
org.hibernate.query.Query;
public class TestHibernate2 {
public static void main(String[] args) {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata
meta = newMetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
//Here
this query will fetch data from Employees Table
Query q = session.createQuery("from Employees");
//fetching
list of Employees class objects
List<Employees> list = q.list();
//if
list has data then iterate
if (list != null && !list.isEmpty()) {
//iterate
over list and fetch Employee Data
for (Employees e : list) {
System.out.println("Id: " + e.getId());
System.out.println("Name:
" +
e.getFirstName() + "
" +e.getLastName());
}
}
factory.close();
session.close();
}
}