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
Continue Reading...

Hibernate operations (Data Update) - Part 2

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 update through hibernate. (Data insertion article can be found at Part 1 of this 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 Update
Before writing codes for updating let me introduce the HQL for the hibernate. This HQL can be use to update the db. It is essential to get know about HQL  before move to further operations of hibernate.

HQL - The Hibernate Query Language
HQL is similar in appearance to SQL that can be used as a a powerful query language for Hibernate.HQL is a case insensitive query language. Therefore as an example the keyword fRoM, FrOm, from and FROM are identical for a query.

The first HQL query.

from
from is the simplest possible Hibernate query. Let's clarify this by using few examples.

from Person

This will return all the data from Person table. The equaling sql query is,

/*this is equaling sql query for 'from Person'*/
select * from Person

In order to refer to the Person in other parts of the query, you can assign an alias for Person using 'as' keyword.

from Person as P
/*Now P refer the Person table*/

Also this can be acquired without using 'as' keyword.

from Person P
/*Now P refer the Person table*/

Parameters
These parameters can be used within the the query to pass values when they are executing in the java program.

The sign  :  used to define the parameters.

from Person as p where p.id = :personId

Here 'personId' is a parameter. Now lets execute a HQL query in java. Basically to execute a HQL query the method 'createQuery' in the class 'org.hibernate.classic.Session' is used.

String searchId = "1";
String query = "from Person as p where p.id = :personId";

session.createQuery(query).setString("personId", searchId);

When call the method 'createQuery' the value of 'searchId' will assign to the parameter 'personId' in the query. Finally the query for execute is,

from Person as p where p.id = 1

Now let's combine update and these 2 concepts to execute the update query. 'createQuery' method can be used execute the update query. A update query uses the keyword 'update' as follows


'keyId' is a parameter for the query which can be used to pass a value when it execute.

The complete java program for the update is,

package 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();
             
        //beginning of the session
        Session session = factory.openSession();
        session.beginTransaction();//beginning of the transaction
       
        String name = "New_Milinda";//this is new name for 'id'
        String id = "1";//this is the key id for field being updated
       
        //create the update query
        String query = "update Person as p set p.name = :newName where p.id = :keyId";
       
        session.createQuery(query)
            .setString("newName", name)//this will set the string 'newName' to name variable
            .setString("keyId", id)
            .executeUpdate();
        

        session.getTransaction().commit();//end of transaction
        session.close();//end of  session
       
       
        }

}

After this code segment run the data's which having id equal 1 will change its name into 'New_Milinda'. Here I used 'where' keyword to implement the condition for the update. (similar method used in mysql queries)

Finally the query to be executed is,

update Person as p set p.name = New_Milinda where p.id = 1

Also this is the query after setting all the parameters(newName and keyId).


I hope to post more articles for other operations of hibernate such as
  • Data retrieve
  • Data delete
from the db. Will be soon........

Related posts

Continue Reading...

Hibernate operations (Data insertion) - Part 1

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 insertion to the db through hibernate.

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.

Hibernate is a ORM tool. Therefore it is not necessary to care about db type (whether MySql or derbydb or another) when you programming a application for a db. But you have to concern only about the 'connection.driver_class' and 'connection.url' in the 'hibernate.cfg.xml' file to match the db type.

Therefore you can change your database type at anytime without changing whole java codes or queries written for da operations. It is the power of 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.

Data insertion
Data insertion can be done using this persistent class's object. Following sample code shows the way to insert data to a database through hibernate.

 Create a java class named "TestPerson.java" with main method.

package pkg;

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) {

  //create configurations for Person class
  AnnotationConfiguration config = new AnnotationConfiguration();
  config.addAnnotatedClass(Person.class);
  config.configure("hibernate.cfg.xml");

  //create new schema(db and table)
  new SchemaExport(config).create(true, true);//comment this line if you already created the table Person
 
  SessionFactory factory = config.buildSessionFactory();
  Session session = factory.getCurrentSession();
 
  session.beginTransaction();//begin the db operations
 
  //Insertion to the table
  Person person = new Person();//create the object from persistent class
  //set data that you want to store in db
  person.setId(1);
  person.setName("Milinda");
  person.setAge(24);
  
  session.save(person);//save the object to db
 
  session.getTransaction().commit();//save permanently to db(end of db operations)
 }
}

Now data(id=1, name=Milinda and age=24) will be stored in the 'Person' table. Finally the 'Person' table's data can be shows as follows.

+----+-----+----------+
| id | age | name     |
+----+-----+----------+
|  3 |  24 | Milinda  |
+----+-----+----------+

Note- You can remove(or comment) the code line new SchemaExport(config).create(true, true); if you already create the db and particular tables.(This code line responsible for create tables on th db)

I hope to post more articles for other operations of hibernate such as
  • Data update
  • Data retrieve
  • Data delete
from the db. Will be soon........


Related posts
Continue Reading...

Add Hibernate javadoc to eclipse

Javadoc is a convenient way to learn and get help from documents which are provided by the programmer. These javadoc can be added to Eclipse IDE to view appropriate javadoc for a particular class or method or interface etc. These javadocs views on eclipse when auto complete (or content assist) appear. You can view the content assist by pressing 'Ctrl+Space'.

 
You can see the javadoc window on right hand side of this figure.

By default the javadoc for hibernate distribution does not exists. To add the javadoc to eclipse follow these steps.

Step 1
Download javadoc jar file from following link
hibernate-3.2.2.ga-javadoc.jar
Any how you should download the hibernate-3.2.2.ga-javadoc.jar file.

Step2 
Open eclipse and add above jar file to hibernate3.jar as a javadoc for it. To do that follow the steps explained below.

Step 3
Right click on 'hibernate3.jar' by expanding user library which contain all your hibernate reference jar files. And select 'Properties'.

Step 4
Select 'Javadoc Location' from side pane and click on 'Javadoc in archive' to select it.

Step 5
Browse for downloaded jar file and add that jar file location as javadoc location for 'hibernate3.jar'.

Step 6
Click 'Apply' and 'OK' to save the changes.


Now it is done you can view javadoc from eclipse.


Continue Reading...