Hibernate - Eclipse - 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:

  1. package org.arpit.javapostsforlearning;  
  2.   
  3. import javax.persistence.Column;  
  4. import javax.persistence.Entity;  
  5. import javax.persistence.GeneratedValue;  
  6. import javax.persistence.Id;  
  7.   
  8. @Entity(name="User_table")  
  9. public class User {  
  10.  @Id  
  11.  int userId;  
  12.  @Column(name="User_Name")  
  13.  String userName;  
  14.    
  15.  String userMessage;  
  16.  public int getUserId() {  
  17.   return userId;  
  18.  }  
  19.  public void setUserId(int userId) {  
  20.   this.userId = userId;  
  21.  }  
  22.  public String getUserName() {  
  23.   return userName;  
  24.  }  
  25.  public void setUserName(String userName) {  
  26.   this.userName = userName;  
  27.  }  
  28.  public String getUserMessage() {  
  29.   return userMessage;  
  30.  }  
  31.  public void setUserMessage(String userMessage) {  
  32.   this.userMessage = userMessage;  
  33.  }  
  34.     
  35. }  

@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"> 
  1. <hibernate-configuration>  
  2.   
  3.     <session-factory>  
  4.   
  5.         <!-- Database connection settings -->  
  6.         <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>  
  7.         <property name="connection.url">jdbc:sqlserver://localhost:1433;database=UserInfo</property>  
  8.         <property name="connection.username">sa</property>  
  9.         <property name="connection.password"></property>  
  10.   
  11.         <!-- JDBC connection pool (use the built-in) -->  
  12.         <property name="connection.pool_size">1</property>  
  13.   
  14.         <!-- SQL dialect -->  
  15.         <property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</property>  
  16.   
  17.         <!-- Echo all executed SQL to stdout -->  
  18.         <property name="show_sql">true</property>  
  19.   
  20.         <!-- Drop and re-create the database schema on startup -->  
  21.         <property name="hbm2ddl.auto">create</property>  
  22.   
  23.         <mapping class="org.arpit.javapostsforlearning.User"></mapping>  
  24.   
  25.     </session-factory>  
  26.   
  27. </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

  1. package org.arpit.javapostsforlearning;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.cfg.Configuration;  
  6. import org.hibernate.service.ServiceRegistry;  
  7. import org.hibernate.service.ServiceRegistryBuilder;  
  8.   
  9. public class HibernateMain {  
  10.   
  11.  public static void main(String[] args) {  
  12.       
  13.   Configuration configuration=new Configuration();  
  14.   configuration.configure();  
  15.   ServiceRegistry sr= new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();  
  16.   SessionFactory sf=configuration.buildSessionFactory(sr);  
  17.     
  18.   User user1=new User();  
  19.   user1.setUserName("Arpit");  
  20.   user1.setUserMessage("Hello world from arpit");  
  21.     
  22.   User user2=new User();  
  23.   user2.setUserName("Ankita");  
  24.   user2.setUserMessage("Hello world from ankita");  
  25.   Session ss=sf.openSession();  
  26.   ss.beginTransaction();  
  27.  //saving objects to session  
  28.   ss.save(user1);  
  29.   ss.save(user2);  
  30.   ss.getTransaction().commit();  
  31.   ss.close();  
  32.     
  33.  }  
  34.   
  35. }  
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.

  1. Hibernate: drop table User_table  
  2. Hibernate: create table User_table (userId int identity not null, userMessage varchar(255), User_Name varchar(255), primary key (userId))  
  3. Jan 292013 9:38:32 PM org.hibernate.tool.hbm2ddl.SchemaExport execute  
  4. INFO: HHH000230: Schema export complete  
  5. Hibernate: insert into User_table (userMessage, User_Name) values (?, ?)  
  6. 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:


Read more at http://javapostsforlearning.blogspot.com/2013/01/hibernate-hello-world-example-in-eclipse.html#7u62HPFgPsZHux3p.99

Post a Comment

Thank You

Previous Post Next Post