Pages

Hibernate operations (Data Retriving) - Part 3

Hibernate is an object-relational mapping (ORM) library for the Java language. Hibernate provides data query and retrieval facilities that significantly reduce the development time. Hibernate facilitates you to develop persistent classes following an object-oriented styles such as inheritance, polymorphism, composition, association, and collections.

This article only concern about data retrieving through hibernate. (Data insertion article can be found at Part 1 of this series and data update article can be found at Part 2 of this article series)

And also I have to mention here this article not describing all the hibernate from the beginning. Therefore this is not the best way to start your first hibernate java project. Simply this article very much suitable for the people those who having basis of the hibernate.

To start these all the sample programs you should do the initial thing such as adding related jar files, referring those jars, establish MySql db connection(from eclipse or netbeans to view db's data), etc.


Initiating............
First let's create java class which used as a persistent class.
Create a java class named "Person.java"

package pkg;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {
 private int id;
 private String name;
 private int age;

 @Id
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

This class is now persistent class through annotations.
(This class is identical to the class that we used in part 1)

Data Retriving
Before writing codes for data retrieving, you should have a knowledge about HQL for the hibernate. This HQL can be use to data retrieve from db. If you do not have at least basis of the HQL please refer part 2 of this article series.

It is very easy to retrieve data from the db by just executing HQL query but getting data in java program from the result of the executed query is some what hard.

The query for retrieve all data from Person class is,

from Person

This query can be execute by executing following java code segment.

String query = "from Person";
session.createQuery(query);

These codes will be executed successfully but where is the result which returned from the executed query?
In hibernate the result of the HQL query can be caught by java.util.List. Therefore code for retrieving data can be update as follows.


Now list object hold the all of data which return from the executed query.

Now let's see how to access to the list in order to get the real data. To acquire this we have to use java.util.Iterator class. So do not forget this is Hibernate(a ORM tool) therefore we can use getters from 'Person' class to get the particular data. If we going to use getters, it should be included some data into instance variables in the class. Therefore we can assign data into Person type object.

String query = "from Person";
List list = session.createQuery(query).list();
       
Iterator iterator = list.iterator();

Person obj = (Person) iterator.next();//cast and assign data to Person type object

System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n");

We can use while loop to view all data on the result set.

String query = "from Person";
List list = session.createQuery(query).list();
       
Iterator iterator = list.iterator();

while (iterator.hasNext()) {
        Person obj = (Person) iterator.next();//cast and assign data to Person type object
           
        System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n");
}

Also you can implement conditional retrieving using 'where' keyword.

String searchId = "1";
String query = "from Person as p where p.id = :sId";
List list = session.createQuery(query)
        .setString("sId", searchId).list();
       
Iterator iterator = list.iterator();
       
while (iterator.hasNext()) {
        Person obj = (Person) iterator.next();//cast and assign data to Person type object
           
        System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n");
}

The complete java code for data retrieving is,

apackage pkg;

import java.util.Iterator;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
//import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson {

    public static void main(String[] args) {

        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Person.class);
        config.configure("hibernate.cfg.xml");
             
        SessionFactory factory = config.buildSessionFactory();
        Session session = factory.getCurrentSession();


        session.beginTransaction();

        String searchId = "1";
        String query = "from Person as p where p.id = :sId";
        List list = session.createQuery(query)
                    .setString("sId", searchId).list();
       
        Iterator iterator = list.iterator();
       
        while (iterator.hasNext()) {//is next data exist? then loop
            Person obj = (Person) iterator.next();//cast and assign next data to Person type object
           
            System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n");
        }
       
        session.close();

Now as an example let's consider our table data are looks like this,

+----+-----+-------------------+
| id | age | name              |
+----+-----+-------------------+
|  1 |  23 | Milinda           |
|  2 |  24 | Milinda Aruna     |
|  4 |  25 | Aruna Milinda UWU |
|  5 |  25 | Aruna UWU Milinda |
+----+-----+-------------------+
The output of this code segment is,

1    23    Milinda

Related posts

9 comments:

  1. If these things are helpful to anybody, I can be happy......!
    If any errors on the code, please let me know.

    ReplyDelete
  2. Nice stuff!Thanks for taking time to share your great experience and knowledge here with us..pcb manufacture

    ReplyDelete
  3. if
    String query = "from Person as p where p.id = :sId";
    List list = session.createQuery(query)
    .setString("sId", searchId).list();

    how can i set two param of "where"?

    ReplyDelete
    Replies
    1. You can code like this

      List list = session.createQuery(query)
      .setString("param1", searchId1)
      .setString("param2", searchId2).list();

      Delete
  4. Thanks .. you helped me by this tutorial

    ReplyDelete
  5. Thanks for the example. Do you know how to retrieve data from two database tables to one jtable using inner join?

    ReplyDelete