Advertisement



< Prev
Next >



Hibernate - The first program in Eclipse



Today we are going to understand how to put Hibernate into an execution using the Eclipse Integrated Development Environment(IDE) application.

As you know that Hibernate is a middleware used for object-relational mapping(ORM) and for performing efficient object persistence. So, in the next section, we are going to create a Java class which will be mapped to a table in database(Oracle Express Edition 10g) and its objects will be persisted, using the Hibernate.



Creating a Java Project in Eclipse







Advertisement




Adding a POJO/Entity class








This is a simple Java class whose objects needs to be persisted/saved, these objects are also known as Plain Old Java Objects(POJO) or Entity class. Some may even refer to such class whose objects needs to be persisted as the Model class.

UserData.java
package decodejava;

public class UserData 
{

//public no-arg constructor
public UserData()
{
}

private int id;
private String name;
	
	
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;
}

}





Adding the class that calls the Hibernate API








The Hiber class creates a Configuration object, used to configure the Hibernate. This is the first object we use when using the Hibernate. This object is used to specify the location of a configuration file and mapping document used by Hibernate. Using Configuration object we can create a SessionFactory object, which is eventually used to create a Session object to perform the object persistence operations.

Hiber.java
package decodejava;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Hiber 
{

public static void main(String[] args) 
{

//Creating the Configuration object.
Configuration cfg = new Configuration().configure("hibernate.cfg.xml").addResource("userdata.hbm.xml");

//Using the Configuration object to creagte a SessionFactory object.
SessionFactory sf = cfg.buildSessionFactory();  

//Using the SessionFactory object to create a Session object.
Session session = sf.openSession();
	
//Creating the first object
UserData ob1 = new UserData();
ob1.setId(1);
ob1.setName("Adam");
	
//Creating the second object
UserData ob2 = new UserData();
ob2.setId(2);
ob2.setName("Ahmad");
	
//Creating the third object
UserData ob3 = new UserData();
ob3.setId(3);
ob3.setName("Amit");
	

session.beginTransaction();
session.save(ob1); //Saving the first object.
session.save(ob2); //Saving the second object
session.save(ob3); //Saving the third object
session.getTransaction().commit();
session.close();

	
ob1 = null;
	 
//Creating a new Session to retrieve and modify the object.
session= sf.openSession();
	
session.beginTransaction();
	
ob1 =(UserData)session.get(UserData.class, 1);
ob2 =(UserData)session.get(UserData.class, 3);
	
//Modifying the username of Id=3
ob1.setName("Mitch");
	
//Saving the modified object in database
session.saveOrUpdate(ob1);

//Deleting the user with id=3
session.delete(ob2);

//Committing the transaction
session.getTransaction().commit();

//Closing the session
session.close();
	
	
ob1 = null;
ob2 = null;
ob3 = null;

	
//Creating a new Session to retrieve the objects.
session= sf.openSession();
session.beginTransaction();
ob1 = (UserData)session.get(UserData.class,1);
ob2 = (UserData)session.get(UserData.class,2);
ob3 = (UserData)session.get(UserData.class,3);
System.out.println("Retrieving the saved objects");
	
	
//Retrieving details of the first user.
System.out.println("First User");
System.out.println("Id : " + ob1.getId() + "  Name : " + ob1.getName());
	
	
//Retrieving details of the second user.
System.out.println("Second User");
System.out.println("Id : " + ob2.getId() + "  Name : " + ob2.getName());
	
	
session.getTransaction().commit();

//closing the session
session.close();
	
//closing the heavyweight SessionFactory object
sf.close();
	
}
}





Adding JARs


  • We are going to add some JARs files to our Java project. These JARs make the Hibernate work with our database using a specific JDBC Driver for our particular database.

    In order to do this, let's right click on our project HibernateProgam and click on Properties.






  • In the next window, we need to click on Java Build Path on the left and click on the Libraries tab on the right side of window. In this window, we need to click on the Add External JARs, as shown in the picture below.






  • Next, we are going to go to a folder named required(within our Hibernate installation folder) and select all the JARs in it and click on Open button.






  • Next, you will be shown the added multiple JARs to your project, to finalize it, click the OK button.






  • Finally, we are going to add one more JAR file by performing the same steps in our previous step. This is a specific JDBC JAR file(ojdbc14.jar) required by Hibernate to connect to our database(Oracle Express Edition 10g) and perform object-relational mapping and object persistence.






Adding a configuration file







This configuration document ends with an extension .cfg.xml, and it is named as hibernate.cfg.xml.


This configuration file is an xml file and it allows us to specify the following features -


hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">



<hibernate-configuration>

<session-factory>


<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">promila21</property>


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


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


<!-- Disable the second-level cache  -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</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>


<!-- Names the mapping entity class -->
<mapping class ="decodejava.UserData"/>

</session-factory>

</hibernate-configuration>





Adding the mapping-resource file






This mapping document ends with an extension .hbm.xml, hence, we have named it userdata.hbm.xml.

This mapping document tells Hibernate -


userdata.hbm.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">


<hibernate-mapping>

   <class name = "decodejava.UserData" table = "userdata">
      
      <id name = "id"  column = "id" type = "int">
         <generator class="native"/>
      </id>
    
      <property name = "name" column = "Name" type = "string"/>
	  
   </class>

</hibernate-mapping>


This mapping document has <hibernate-mapping> as the root element and its child element <class>, containing all the class elements.









Execution


Finally, after executing Hiber class, you will get the following output within the Console window. This output shows you all the SQL commands executed by the Hibernate within the database to map the Java class to a database table and perform all the activities of saving, modifying and retrieving and displaying the objects of UserData, as specified in the Hiber class, as shown below.

Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: create table userdata (id number(10,0) not null, Name varchar2(255 char), primary key (id))
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into userdata (Name, id) values (?, ?)
Hibernate: insert into userdata (Name, id) values (?, ?)
Hibernate: insert into userdata (Name, id) values (?, ?)
Hibernate: select userdata0_.id as id1_0_0_, userdata0_.Name as Name2_0_0_ from userdata userdata0_ where userdata0_.id=?
Hibernate: select userdata0_.id as id1_0_0_, userdata0_.Name as Name2_0_0_ from userdata userdata0_ where userdata0_.id=?
Hibernate: update userdata set Name=? where id=?
Hibernate: delete from userdata where id=?
Hibernate: select userdata0_.id as id1_0_0_, userdata0_.Name as Name2_0_0_ from userdata userdata0_ where userdata0_.id=?
Hibernate: select userdata0_.id as id1_0_0_, userdata0_.Name as Name2_0_0_ from userdata userdata0_ where userdata0_.id=?
Hibernate: select userdata0_.id as id1_0_0_, userdata0_.Name as Name2_0_0_ from userdata userdata0_ where userdata0_.id=?
Retrieving the saved objects
First User
Id : 1  Name : Mitch
Second User
Id : 2  Name : Ahmad


Additionally you can see the updated contents of the table as shown below.






Please share this article -




< Prev
Next >
< Hibernate program without IDE
Hibernate with Annotations >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement