Skip to main content

Hibernate introduction

Hibernate is an Object/Relational Mapping tools that provides services to map the data of object’s properties into columns of database-tables. It persist Java objects to database table automatically and vice versa. Java Programmer will able to map domain model of their project to data model into database design. It emphasis programmer to think for their programming only. It removes all SQL requirements to work with database while using any RDBMS into project.

Data stored into instance variables of an Object is retired by Hibernate toll and it Stores it to the specified column of database table. It uses some configurations that determine what to map and how to map. This configuration is stored into XML file along with class file that is going to be mapped. Classes are simple POJOs and no require any dependency on any other class. These classes are called Entity or Entity Bean classes also. In entity classes all members are kept private and each member is accessed through public getX() and setX() method of corresponding  member. For example if class has name member, then it is declared as a private (i.e. private String name; ) and it will have two methods public void getName() and public void setName(String name).


This approach reduces time to develop database driven application. This framework replaces JDBC for developers, but it uses it to process all data. If you are using Hibernate or hibernate like Persistent tool, you no need to know about SQL, Database System because all complexities have been overlapped by framework. Hibernate provides its own query language to perform some advance operations with data tables instead of SQL. Almost all operations can be done using Hibernate Query Language and you can update, retrieve and delete data of tables.

Hibernate have some interesting features that simplify your life by reducing effort to programming for database logics.

  • Hibernate allows you to develop POJO(plain old java object) Based persistence classes following object oriented features inheritance, polymorphism, association, composition and the java collection frame work.

  • Hibernate allows to program persistence classes without using any dependency on other classes or package. Persistence class is simple class that neither extends ant class not implements any interface. It not requires any other classes from other package. So this class can be compiling without any problem.

  • Hibernate supports lazy initialization, many fetching strategies, and optimistic locking with automatic versioning and time stamping. Hibernate requires no special database tables or fields and generates much of the SQL at system initialization time instead of runtime. Hibernate consistently offers superior performance over straight JDBC coding.

  • Hibernate was designed to work in an application server cluster and deliver a highly scalable architecture. Hibernate scales well in any environment: Use it to drive your in-house Intranet that serves hundreds of users or for mission-critical applications that serve hundreds of thousands.

  • This framework comes with bundled jar files from which you can remove jar files those are not required to your application according to your needs as well as you can add them later. You no need to place all jar file library on classpath. Hibernate is highly customizable and extensible. 

  • Including support for Hibernate Query Language (HQL), Java Persistence Query Language (JPAQL), Criteria queries, and "native SQL" queries; all of which can be scrolled and paginated to suit your exact performance needs.


Before start anything you have to configure HSQL Database. Click Here to configure

Example
Contact.java


package pack;
public class Contact{
    private int id;
    private String name;
    private int phone;
    private String email;
    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 getPhone(){return phone;}
    public void setPhone(int phone){this.phone=phone;}
    public String getEmail(){return email;}
    public void setEmail(String email){this.email=email;}
    public String toString(){
        return "Contact[id="+id+", name="+name+", phone="+phone+", email="+email+"]";
    }
}


ContactDataOperation1.java


import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class ContactDataOperation1{
    public static void main(String ar[]){
        Configuration c=new Configuration();
        c.setProperty("hibernate.dialect","org.hibernate.dialect.HSQLDialect");
        c.setProperty("hibernate.connection.driver_class","org.hsqldb.jdbcDriver");
        c.setProperty("hibernate.connection.url","jdbc:hsqldb:hsql://localhost/testdb");
        c.setProperty("hibernate.connection.username","sa");
        c.setProperty("hibernate.connection.password","");
        c.addClass(pack.Contact.class);
        SessionFactory factory=c.buildSessionFactory();
        Session session=factory.openSession();
        Transaction tx=session.beginTransaction();
        pack.Contact contact=new pack.Contact();
        contact.setId(3);
        contact.setName("abc");
        contact.setPhone(33333333);
        contact.setEmail("abc@gmail.com");
        session.save(contact);
        tx.commit();
        session.close();
    }
}


Contact.hbm.xml


 version="1.0"?>
 hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="pack.Contact" table="contact">
        <id name="id" type="int" column="id">
        id>
        <property name="name" column="fullname" type="string"/>
        <property name="phone" column="mobilenumber" type="int"/>
        <property name="email" column="emailid" type="string"/>
    class>
>





Compile and arrange directory hierarchy as following

HIBERNATE2
│   Contact.java
│   ContactDataOperation1.class
│   ContactDataOperation1.java
├───lib
│     antlr-2.7.6.jar
│     commons-collections-3.1.jar
│     dom4j-1.6.1.jar
│     hibernate3.jar
│     hsqldb.jar
│     javassist-3.9.0.GA.jar
│     jta-1.1.jar
│     slf4j-api-1.5.8.jar
│     slf4j-simple-1.6.0.jar
└───pack
      Contact.class
      Contact.hbm.xml




Now start database server and create tables named contact. Database to be used is HSQLDB and you can read more how to deal with HSQLDB.

Open command prompt and go to hibernate2 directory , and execute following commands.
To set all jar files into classpath;
set CLASSPATH=%CLASSPATH%;lib/antlr-2.7.6.jar;lib/commons-collections-3.1.jar;lib/dom4j-1.6.1.jar;lib/hibernate3.jar;lib/hsqldb.jar;lib/javassist-3.9.0.GA.jar;lib/jta-1.1.jar;lib/slf4j-api-1.5.8.jar;lib/slf4j-simple-1.6.0.jar
To set java into path
set path=%path%;D:\Program Files\Java\jdk1.6.0_13\bin

Compile

…hibernate2>javac *.java

Run
…hibernate2>java ContactDataOperation1

OUTPUT


In database manager, execute “select * from contact” SQL query and you will get something like





Comments

Popular posts from this blog

Using HyperSQL (HSQLDB)

HSQLDB is a portable RDBMS implemented in pure java. It can be embedded with your application as well as can be used separately. It is very a small database that supports almost all features of the standard database system. It comes with small jar file that can be found in lib folder. The HSQLDB jar package is located in the /lib directory of the ZIP package and contains several components and programs. Core components of jar file are : HyperSQL RDBMS Engine (HSQLDB), HyperSQL JDBC Driver, Database Manager, and Sql Tool. Installing and Using Download: download latest release of HyperSQL database from http://hsqldb.org website and extract it. You will see following contents. Here "bin" directory contains some batch files those can be used to run a swing based GUI tool. You can use runManagerSwing.bat to connect to database, but database must be on before running it. Directory lib contains File hsqldb.jar . It is the database to be used by you. Running database First

How to handle values from dynamically generated elements in web page using struts2

Some time you will see the form containing the button " Add More " . This facility is provided for the user to get the values for unknown number of repeating for some information. for example when you are asking to get the projects details from user, you need to put the option to add the more project for the user since you don't known how many projects user have. In the HTML form, you repeat the particular section to get the multiple values for those elements. In Html page , you can put the option to add new row of elements or text fields by writing the java script or using JQuery API. Now, the question is that how to capture the values of dynamically generated text fields on the server. Using the servlet programming you can get the values by using getParameters() method that resultants the array of the parameter having the same name. But this limit you to naming the text fields in the HTML form. To ally this approach, you have to take the same name for t

In Process Mode of HSQLDB in web application.

If you want to use the database into your web application, you can use the HSQLDB in In_Process mode. In this mode, you can embed the HSQLDB into your web application and it runs as a part of your web application programm in the same JVM. In this mode, the database does not open any port to connect to the application on the hosing machine and you don't need to configure anything to access it. Database is not expposed to other application and can not be accessed from any dabase tools like dbVisualizer etc. In this mode ,database will be unknown from any other person except you. But in the 1.8.0 version, you can use Server intance for external as well as in process access.  To close the databse, you can issue SHUTDOWN command as an SQL query.   In the in-process mode, database starts from JDBC with the associated databse file provided through  connection URL. for example   DriverManager.getConnection("jdbc:hsqldb:mydatabase","SA","");   Here myd