This is 2 of 8 parts of tutorial series

Tutorial Content:

    Introduction to hibernate framework Hibernate hello world example in eclipse Difference between openSession and getCurrentSession Hibernate one to one mapping example Hibernate one to many mapping example Hibernate many to many mapping example Hibernate inheritance:Table per class hierarchy Hibernate inheritance:table per subclass Hibernate inheritance:Table per concrete class Difference between openSession and getCurrentSession Difference between get and load Spring MVC Hibernate MySQL CRUD example Spring Rest hibernate example
After basic understanding of hibernate framework.We are ready to start working on hibernate In this post,we will configure hibernate in eclipse and write our first hibernate program.For configuring hibernate,there are some prerequisites which you need to have on your system.
  1. Download hibernate framework.(I am using here latest hibernate version 4.1.9)
  2. Download any database.(I am using here sql server 2005)
  3. Download JDBC driver for database(I have downloaded jdbc driver for sql server 2005)
  4. Eclipse ide
  5. JDK 1.5 or above
Now,In eclipse IDE,click on File->new
 Click on other and then select java project



Click on next and  Write project name.I have writtern here "Hibernate4HelloWorldProject"


Click on finish and now our project is created
Create new folder "jars" under src folder so for that right click on project->new->folder
 Write folder name as "jars"
click on finish and empy jar folder will be created in src folder.
Now we will add the hibernate 4 libraries to the project. Extract the "hibernate-release-4.1.9.Final" file if you have not extracted. Now go to the "hibernate-release-4.1.9.Final->lib->required" directory and then copy all the jar files (Ctrl+C) and paste on the jars directory (of our project) in the Eclipse IDE.
Also download jdbc driver for your database and copy that jar to jars
Note- location of above jar files may vary from versions to versions. So if you are using other versions than 4.1.9 then you need to find jars in that version.

Now add all the jars to "Java Build Path". Right click on the "Hibernate4HelloWorldProject" in project explorer and then select properties. Then select "Java Build Path" --> Libraries and then click on the "Add JARs" button. And add all the libraries to Java Build Path.

Click on OK.
you are done with configuring hibernate in eclipse.

Now we will write our first hibernate application.For configuring hibernate in eclipse,please refer previous post.I am using SQL server 2005 as database.
We will make User_table table in database using hibernate.
  
We will create User.java for creating above table in database.

1.User.java(Entity)

An entity can be considered as a lightweight persistence domain object. An entity defines a table in a relational database and each instance of an entity corresponds to a row in that table. An entity refers to a logical collection of data that can be stored or retrieved as a whole.

Create a new package org.arpit.javapostsforlearning to hold the java files. Right click on the "src" folder and then select New --> Package. Then provide the package name as org.arpit.javapostsforlearning and click on the "Finish" button. 

Create a new Java file User.java under the package org.arpit.javapostsforlearning and add the following code:

package org.arpit.javapostsforlearning;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity(name="User_table")
public class User {
 @Id
 int userId;
 @Column(name="User_Name")
 String userName;
 
 String userMessage;
 public int getUserId() {
  return userId;
 }
 public void setUserId(int userId) {
  this.userId = userId;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public String getUserMessage() {
  return userMessage;
 }
 public void setUserMessage(String userMessage) {
  this.userMessage = userMessage;
 }
  
}

@Entity is used for making a persistent pojo class.For this java class,you want to create a table in database.
@Entity(name="User_table") specify that create a table named "User_table" in database

2.Hibernate configuration XML:

After configuring hibernate in eclipse,we need to configure "hibernate.cfg.xml" for database configuration and other related parameters.By default,hibernate searches for a configuration file in a project's root directory.Create a file named "hibernate.cfg.xml" in src folder.
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="connection.url">jdbc:sqlserver://localhost:1433;database=UserInfo</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

        <mapping class="org.arpit.javapostsforlearning.User"></mapping>

    </session-factory>

</hibernate-configuration>
<property name="connection.driver_class">: Need to specify  JDBC driver class.
<property name="hibernate.connection.url "> :specify JDBC URL to the database instance.
<property name="hibernate.connection.username " >:Specify database username
<property name="hibernate.connection.password" >:Specify database password
<property name="hibernate.connection.dialect" >:This property makes Hibernate generate the appropriate SQL for the chosen database.
 <property name="hibernate.connection.pool_size " >:This property limits the number of connections waiting in the Hibernate database connection pool.
 <property name="show_sql" >:If you specify this property to be true then all sql statement will be printed to console.
<property name="hbm2ddl.auto" >:It specify operation on your database schema.Whether to drop and recreate your database schema or update current schema.
<mapping class="org.arpit.javapostsforlearning.User" >:Here you need to specify all java classes for which you want to create a table in database.You need to specify all entity classes here.

3.Main class:

Create a class named "HibernateMain.java" in src->org.arpit.javapostsforlearning

package org.arpit.javapostsforlearning;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateMain {

 public static void main(String[] args) {
    
  Configuration configuration=new Configuration();
  configuration.configure();
  ServiceRegistry sr= new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
  SessionFactory sf=configuration.buildSessionFactory(sr);
  
  User user1=new User();
  user1.setUserName("Arpit");
  user1.setUserMessage("Hello world from arpit");
  
  User user2=new User();
  user2.setUserName("Ankita");
  user2.setUserMessage("Hello world from ankita");
  Session ss=sf.openSession();
  ss.beginTransaction();
 //saving objects to session
  ss.save(user1);
  ss.save(user2);
  ss.getTransaction().commit();
  ss.close();
  
 }

}
As we have discussed in our previous post,we have to create SessionFactory instance in order to communicate with Database in Hibernate

Project structure:

 4.Run it:

When you will run this application.You will get following output.

Hibernate: drop table User_table
Hibernate: create table User_table (userId int identity not null, userMessage varchar(255), User_Name varchar(255), primary key (userId))
Jan 29, 2013 9:38:32 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into User_table (userMessage, User_Name) values (?, ?)
Hibernate: insert into User_table (userMessage, User_Name) values (?, ?)
After execution of above program,you can check User_table table in your database.

5.SQL output:

Source code:

click to begin
6.1 MB .zip

Tutorial Content:

    Introduction to hibernate framework Hibernate hello world example in eclipse Difference between openSession and getCurrentSession Hibernate one to one mapping example Hibernate one to many mapping example Hibernate many to many mapping example Hibernate inheritance:Table per class hierarchy Hibernate inheritance:table per subclass Hibernate inheritance:Table per concrete class Difference between openSession and getCurrentSession Difference between get and load Spring MVC Hibernate MySQL CRUD example Spring Rest hibernate example
After basic understanding of hibernate framework.We are ready to start working on hibernate In this post,we will configure hibernate in eclipse.For configuring hibernate,there are some prerequisites which you need to have on your system.
  1. Download hibernate framework.(I am using here latest hibernate version 4.1.9)
  2. Download any database.(I am using here sql server 2005)
  3. Download JDBC driver for database(I have downloaded jdbc driver for sql server 2005)
  4. Eclipse ide
  5. JDK 1.5 or above
Now,In eclipse IDE,click on File->new
 Click on other and then select java project



Click on next and  Write project name.I have writtern here "Hibernate4HelloWorldProject"


Click on finish and now our project is created
Create new folder "jars" under src folder so for that right click on project->new->folder
 Write folder name as "jars"
click on finish and empy jar folder will be created in src folder.
Now we will add the hibernate 4 libraries to the project. Extract the "hibernate-release-4.1.9.Final" file if you have not extracted. Now go to the "hibernate-release-4.1.9.Final->lib->required" directory and then copy all the jar files (Ctrl+C) and paste on the jars directory (of our project) in the Eclipse IDE.
Also download jdbc driver for your database and copy that jar to jars
Note- location of above jar files may vary from versions to versions. So if you are using other versions than 4.1.9 then you need to find jars in that version.

Now add all the jars to "Java Build Path". Right click on the "Hibernate4HelloWorldProject" in project explorer and then select properties. Then select "Java Build Path" --> Libraries and then click on the "Add JARs" button. And add all the libraries to Java Build Path.

Click on OK.

Now you are done with configuring hibernate in eclipse.You can create your first hibernate project.
In next post we will write 


Target Audience

This tutorial is designed for Java programmers who need to understand the Hibernate framework and its application.

Prerequisites:

Before proceeding with this tutorial you should have a good understanding of the Java programming language and also good understanding of SQL.
This is 1 of 8 parts of tutorial series

Tutorial Content:

    Introduction to hibernate framework Hibernate hello world example in eclipse Difference between openSession and getCurrentSession Hibernate one to one mapping example Hibernate one to many mapping example Hibernate many to many mapping example Hibernate inheritance:Table per class hierarchy Hibernate inheritance:table per subclass Hibernate inheritance:Table per concrete class Difference between openSession and getCurrentSession Difference between get and load Spring MVC Hibernate MySQL CRUD example Spring Rest hibernate example
Before understanding hibernate framework,we need to understand Object Relational Mapping(ORM).

What is ORM?

ORM is a programming method to map the objects in java with the relational entities in the database.In this,entities/classes refers to table in database,instance of classes refers to rows and attributes of instances of classes refers to column of table in database.This provides solutions to the problems arise while developing persistence applications using traditional JDBC method. This also reduces the code that needs to be written.

Need for tools like hibernate:

The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
Improved productivity:
  • High-level object-oriented API 
  • Less Java code to write 
  • No SQL to write 
Improved performance:
  • Sophisticated caching 
  • Lazy loading 
  • Eager loading 
Improved maintainability:
  • A lot less code to write 
Improved portability:
  • ORM framework generates database-specific SQL for you 

What is hibernate?

Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables.The main goal of hibernate is to relieve the developer from the common data persistence related tasks.It maps the objects in the java with the tables in the database very efficiently and also you can get maximum using its data query and retrieval facilities.Mainly by using Hibernate in your projects you can save incredible time and effort.

Architecture of hibernate :

Following is a detailed view of the Hibernate Application Architecture with few important core classes.

The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs.Hibernate is like a bridge between java application and relational database.

Core classes of hibernate are:

Session Interface: 

This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.It allows you to create query objects to retrieve persistent objects.It wraps JDBC connection Factory for Transaction.It holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier .
Session session=SessionFactory.openConnection();
SessionFactory Interface :
This is a factory that delivers the session objects to hibernate application.It is a heavy weighted object so generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work.
Configuration configuration=new Configuration();
  configuration.configure();
  ServiceRegistry sr= new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
  SessionFactory sf=configuration.buildSessionFactory(sr);
SessionFactory object is created with the help of configuration object.

Configuration Interface :

This is used to configure hibernate. It’s also used to bootstrap hibernate. Mapping documents of hibernate are located using this interface.

Transaction Interface :

This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.

Query and Criteria Interface :

This interface allows the user to perform queries and also control the flow of the query execution.
 

Java tutorial for beginners Copyright © 2012