Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Retrive records from Database using Hibernate

As of now we have seen how to store data into the Database using Hibernate Application. Now let us see, how to retrieve the data from the Database. To retrieve the data from the database, Hibernate uses two methods, they are                                        

Storing data into DataBase using Hibernate

To store data into Database using Hibernate Framework we use the following three methods.
  1. save
  2. persist
  3. save or update
save() : This method is used to store the data in Database. When we use save() method, it generates a new identifier and INSERT record into the database using INSERT query. It generates a new identifier and returns the Serializable identifier back. The following is the syntax of save() method.
  • serializable save(Object object)
persist() : This method is also used for storing the data in the DataBase.This method is same as the save(). But this method does not returns a value. The following is the syntax of persist() method.
  • void persist(Object object)
saveorupdate() : This method also used to store the data into the database. When we use this method it checks for the record, if the record exists it just updates the record. If the record is not exist then it inserts a new record.

The following is the Hibernate application which inserts the data into Database. Here we are using save().

Program to Insert values into database using Hibernate
Program to Insert values into database using Hibernate

                                              

Analyzing Hibernate Application

We have seen how to write a Hibernate Application, which inserts the values into DataBase Server. Now let us know what each step is doing in the background. 


Step1: When we create the Configuration object a plain java object will be created. This configuration object stores all the configuration details. Initially when we create the object no data is available in that.


Step2: When we call cfg.configure() it searches for hibernate.cfg.xml file(Configuration file) in the WEB-INF folder. If the Configuration file is not found it throws an exception "org.hibernate.HibernateException/hibernate.cfg.xml not found".
  • If the configuration file is found, parser will validate the xml file. If the file is not valid parser throws an exception "could not parse the xml file". If the xml file(configuration file) is valid  configure() method gets the values of Driverclass, url, username, password, and the information about Hibernate Mapping Files. Then it reads the contents from Hibernate mapping files and stores the entire data into Configuration Object(JVM's Memory).
Step3: When we call cfg.buildSessionFactory() it gets the driverclass, url, username, and password from the configuration object and supply as the input to the internal connection pool of Hibernate(hibernate internally uses c3p connection pool).
  • Now the connection pool program acquires connections from DBServer. Now, buildSessionFactory() picks the connection from the connection pool and establish the connection with DBServer. 
  • Now it will check weather the required tables are available or not. If the tables are not available buildSessionFactory() creates the table.
  • It is the responsibility of the buildSessionFactory() to create and process all the query operations(CURD operations) for each table. After processing the buildSessionFactory() returns the connection to the connection pool.
  • As the buildSessionFactory method is doing more work, it is recommended to call this method only once in the life cycle of the project.
Note: Repeatedly calling the configure() and buildSessionFactory() methods decreases the performance. So, it is recommended to call them only once in the project life cycle.

Step4: When we open the session object by using sf.openSession().
  1. Hibernate creates an object which is similar to hashtable object. We call this object as First Level Cache.
  2. Hibernate associates this object with Session Object.
  3. This First level cache is available until the Session object is closed. Only the session object can access the data from First Level Cache.
  • Opening the session object is nothing but getting the connection object. This method is not an expensive operation. It is always recommended to open a new session object whenever it is required. 
Step5: Whenever we create or ask the hibernate to start the transaction, internally it uses JTA (Java Transaction API) to start and end transactions. To perform Insert, update, delete operations we must start transaction, whereas to perform retrieval operation it is optional.

Step6: Create POJO class object corresponding to the table. When the object is created all the instance variables are initialized with default values.
POJO Class object in which values are initialized with null values
Fig: POJO Class object in which values are initialized with null values
Step7: Storing the data into POJO class object by calling setter methods.
variables initialized with values
Fig: variables initialized with values
Step8: When we call save() method internally hibernate take the object and add the object to First level cache, by using a key TBS(To Be Saved). The method like delete uses a key TBD(To Be Deleted). To check weather the object is available in the First Level Cache, we use a method contains().

  • Ex: hsession.contains(e);

Step9: When we call tx.commit(), hibernate checks for any objects in the First Level Cache which are waiting for an operation to be taken care. If the objects are available hibernate finds, to which POJO class these objects belongs to(Hibernate internally uses getClass() to find the class). 

  • Now hibernate finds to which table this POJO class is mapped, and from that table it gets the registration code. Based on this code it has got the query form the JVM's memory. Now hibernate get the data from the POJO class and supply as the input to the query. This query is added to batch object and send to the DBServer.
  • By default hibernate will not display the query sent to the DB. If we want to see the query we have to add a property in the hibernate configuration file. The following is the property to show SQL queries.

<property name="show-sql">true</property> 

Step10: When we call hsession.close(), the connection is returned to the connection pool as well as it removes the First Level Cache object.
Step11: When we call sf.close(), it removes second level cache as well as returns all the connections from the connection pool to DBServer.


                    

First Hibernate Application

First let us know, what are the important interfaces ans classes. The following are the most important interfaces and classes. 
Important interfaces and classes in Hibernate
Fig: Important interfaces and classes in Hibernate


The following are the steps which will be used to develop Hibernate Application:
  • Create Configuration object by using configuration class.
  • Call the configure() method using the above configuration object.
  • Get SessionFactory object by using configuration object by using "buildSessionFactory()" method.
  • Get Session object using SessionFactory object, by calling openSession() method. 
  • Get Transaction object by calling the method beginTransaction().
  • Create the POJO class object corresponding to the table.
  • Store the data in the form of object.
  • Ask Hibernate to perform CURD operations.The following are the curd operations. The following are the operations.

      1. save()        // create  
      2. update()   //  update
      3. load()       //  select /Retrieve
      4. delete()   //  delete

  • End the Transaction by calling commit() and rollback().
  • Close the session object.
  • Close the SessionFactory object.
Now let us develop the first Hibernate application, let us insert a record into the emp table. The following program inserts the record into emp table.
Hibernate application to Insert Record into Employee table
Fig: Hibernate application to Insert Record into Employee table

                                                               

Towards Hibernate Application

To develop a Hibernate application first we need to create the user in Database and assign some privileges. The following commands helps you to create the user in Database.
  • Login to the DBServer using administrative username and create the user as follows:
SQL> create user HIBER identified by NATE;
Grant connect,resource to HIBER;
Grant create sequence to HIBER;

  •  Now create a table with primary key.
we can get Hibernate software from www.hibernate.org  Hibernate software is a collection of jar files, the most important jar file is Hibernate.jar. To develop hibernate application we need the following three files. 
  1. Hibernate Configuration file
  2. POJO classes (Plain Old Java Object)
  3. Hibernate Mapping Files (hbm) 

Hibernate Configuration File: 

       Generally every Framework uses the Configuration file, this is the starting point of any framework. Generally Configuration files are .xml files or properties files. In Hibernate we use Hibernate.cfg.xml as the configuration file. It contains the data that is required to communicate with database server. The following figure shows the contents of configuration file.

Hibernate Configuration File
Hibernate Configuration File

POJO Classes:

         Generally in hibernate we represent the database records in the form of objects, this can be done by using java programs, Because of this reason we have to develop a couple of java programs. These program contains instance variables, setXXX() and getXXX() methods. Developing these programs are easy because of this reason they are called as POJO(Plain Old Java Object). The no.of POJO classes are based on the no.of tables present in the database server. Suppose if we have two tables, we need to develop two POJO classes. Let us think we have emp and product tables in our database, then we need to develop two POJO classes.

  • Emp.java
  • Product.java

Note: There is no rule saying that POJO class names and table names should be same.

The POJO class must follow the following rules:

  • It must contain a default constructor.
  • It must be placed inside a package.
  • The POJO class supports properties,setXXX() and getXXX() methods are called as Properties.

HBM Files:

         To work with Hibernate we have to develop Hibernate Mapping Files. These files contains the information about which POJO class is mapped with which table and which property is mapped with which column. The following is the sample POJO class.

Procedure to generate Configuration file using MyEclipse:

The following are the steps to generate configuration file.
Step1: Start MyEclipse IDE pointing to workspace folder.
Step2:Configure MyEclipse IDE to interact with the Database Server.
Step3:Create a java project and add a package to it.
Procedure to generate Configuration file using MyEclipse
Fig: Adding Package to the Project
Step4: Add Hibernate capabilities to the above project. To do this select Project --> MyEclipse in menu bar --> select Hibernate capabilities.
Procedure to generate Configuration file using MyEclipse
Fig: Adding Hibernate capabilities to Project
Step5: The above step displays a dialogue box, choose the required jar files to be added. 
Procedure to generate Configuration file using MyEclipse
Fig: Add required jar files
Step6: Choose new Hibernate Configuration file and click on Next.
Procedure to generate Configuration file using MyEclipse
Fig: Configuration file name
Step7: Choose the DB driver and provide url, username and password click on Next.
Procedure to generate Configuration file using MyEclipse
Fig: Choose the driver
Step8: Choose the package and click on Finish.

Procedure to generate POJO classes and HBM files: 

Step1: Go to MyEclipse DB explorer perspective and establish the connection with Database server.
Step2: Select the DB --> open --> Expand DB --> Expand User(The user you have created in Database) --> Expand Table --> select the required tables --> Right click --> Select Hibernate reverse engineering option. 
Procedure to generate POJO classes and HBM files
Fig: generating POJO classes and HBM files
Hence, as of now we have created Configuration file, POJO classes and HBM files. Now our responsibility is to develop a java program. Let us see that.

                                                                      

    Working with MyEclipse IDE

    IDE (Integrated Development Environment):
    There are so many IDE's available in market, some of them are:
    • Eclipse 
    • MyEclipse
    • Net Beans
    • RAD    etc,.,,,
    Every IDE contains Editors, compilers, servers, browser, console etc..., If we use IDE, we no need to take the help of any external tools. Now let us know how to work with MyEclipse IDE.
    When we start MyEclipse IDE, it asks for workspace folder, as shown in the figure1. We can provide any folder as Workspace folder.


    MyEclipse IDE Startup screen
    MyEclipse IDE Startup screen

    When we supply the workspace folder in the back IDE creates a folder whose name is .metadata. This folder contains all the files related to IDE. We should no modify these files. When we carryout any operation on IDE it will be recorded in .metadata folder. 

    Procedure to create a project in MY ECLIPSE IDE: 

    Step1: File ==> New ==>  Project 
    To open new project in MyEclipse IDE
    Fig: To open new project in MyEclipse IDE
      Step2: Select the appropriate project and click on NEXT button.
    Procedure to create a project in MY ECLIPSE IDE
    Fig: Select from List of projects
    Step3: When we select JAVA PROJECT, it displays a window, in that window enter the Project Name and click on Finish.   
    Procedure to create a project in MY ECLIPSE IDE
    Fig: Enter the project Name and Finish
    If we want to delete the project, just Right click on the project and select delete option, then you can see a dialogue box, check the checkbox in the dialogue box and click ok, as shown in figure:
    Procedure to create a project in MY ECLIPSE IDE
    Fig: Delete Project

    Procedure to create a Web Based Application: 


    Now let us see how to build a web based project using MyEclipse IDE. The following are the steps to follow: 

    Step1: File  à New à WebProject   
    Step2: The above step displays a dialogue box, Enter projectName in that and make sure that ProjectName and Web Root Folder name is same and click on Finish.
    Procedure to create a web based project in MY ECLIPSE IDE
    Fig: WebProject
    When we use IDE we no need to deploy the project manually, we can configure IDE to deploy the project. In JEE perspective we can use server view to configure the project in IDE. The following are the steps to configure IDE:
    Step1: Goto server view, right click and select an option Choose Server Connector, as shown in figure:
    Procedure to create a web based project in MY ECLIPSE IDE
    Fig: Server View
    Step2: Choose the appropriate server, home directory of the server and click on OK, or use the default servers of MyEclipse. 
    Step3: To add the project to the server, just right click on the server, choose the option add deployment.

    Procedure to configure IDE to interact with Database Server:

    Step1: Open MyEclipse Database Perspective. 
    Procedure to configure IDE to interact with Database Server
    Fig: Database Perspective in MyEclipse
    Step2: In Database prescriptive, right click and select New option, as shown in figure.
    Procedure to configure IDE to interact with Database Server
    Fig: Add Database
    Step3: The above step displays a Dialogue box, provide all the values and click on Finish.
    Procedure to configure IDE to interact with Database Server
    Fig: Add Database server



                           

    Introduction to Hibernate

    Hibernate Logo
    Hibernate is a framework which is used to interact with Database Servers. We use Hibernate framework as an alternative to JDBC. Apart from Hibernate there are many tools available in the market which are responsible to interact with Database Servers. The following are some of them:
    • JDO
    • JPA
    • Toplink
    • SDO    etc...,
    Comarision with JDBC:
    • In JDBC once if the connection is established with the database server, and if we do not close it, then we get a problem saying maximum number of cursors exceeded. To resolve this problem we use connection pool. If we use framework like hibernate internally they uses connection pool.
    • In Real time projects we always divide the projects into multiple parts. Some programs are responsible to retrieve data from DBServers and some are responsible to display them. But in JDBC ResultSet object(rs) is not transferable. This problem can be resolved by using Hibernate or JPA frameworks.
    • In JDBC every method throws an unreported exception, due to this the JDBC code becomes huge. But in Hibernate no method throws an unreported exception. 
    • If we develop a project to communicate with DBServer using JDBC, we need to take care of queries. This is because some queries are specific to some databases, they will not work for all the DBServers. This problem is resolved in Hibernate by introducing HQL queries. HQL queries interact with any DBServers.
    • In real time projects, we always create tables with Primary keys, by using JDBC we have to write huge amount of code to generate the value for Primary key. But in Hibernate, its internal code takes care of generating primary key values.
    • In JDBC we have write the code to take care of Transactions, In Hibernate, the internal code will take care of Transactions. 
    The following is the architecture of Hibernate:

    Architecture of Hibernate
    Fig2: Architecture of Hibernate.
    Hibernate is an ORM(Object Relational Mapping) tool. In market we have so many ORM frameworks like: JPA(Java Persistence API), JDO(Java Data Object), SDO, Toplink etc..., In Database Servers we represent the data in the form of Relational tables. The representation of Relational data(Tables) in the form of Objects is called as Object Relational Mapping. 
    ORM representation
    Fig: ORM representation