Hibernate Example Step by Step
For Developing any hibernate application we need create below 4 files always
-
Choose Database Table
-
POJO class
-
Mapping XML
-
Configuration XML
-
Application class for main logic
Above are the minimum requirement to run any hibernate application, but we may create any number of POJO classes and any number of mapping xml files (Number of POJO classes = that many number of mapping xmls), and only one configuration xml and finally one java file to write our logic.
1.Choose Database Table
In this Example we are taking employee
table of mydb
database.
CREATE TABLE `employee` (
`eid` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL DEFAULT '0',
`address` VARCHAR(50) NOT NULL DEFAULT '0',
PRIMARY KEY (`eid`)
)
COLLATE='latin1_swedish_ci' ENGINE=InnoDB AUTO_INCREMENT=5;
mysql> select * from employee;
+-----+-------+------------+
| eid | name | address |
+-----+-------+------------+
| 1 | SATYA | VIJAYAWADA |
| 2 | SURYA | HYDERABAD |
| 3 | RAVI | PUNE |
+-----+-------+------------+
2.POJO class / Persistence class
-
POJO is a simple java file, no need to extend any class or implement any interface.
-
Pojo class contains table column names as data members,
-
In above table eid, name, address are columns
-
It contains column names as private data members with setters and getters
public class EmployeeBo {
private int eid;
private String name;
private String address;
//setters / getters
}
3.Mapping File
-
Mapping file contains mapping from a pojo class name to a table name and pojo class variable names to table column names.
-
We can create any no. of mapping files
-
Mapping can be done using 2 ways, using XML & using Annotations.
Syntax of mapping xml (Pojaclassname.hbm.xml)
<hibernate-mapping>
<class name="POJO class name" table="table name in database">
<id name="variable name" column="column name in db" type="java/hib type" />
<property name="var1 name" column="column name in db" type="java/hib type" />
<property name="var2 name" column="column name in db" type="java/hib type" />
</class>
</hibernate-mapping>
Example: EmployeeBo.hbm.xml
<hibernate-mapping>
<class name="bo.EmployeeBo" table="employee">
<id name="eid" column="eid">
<generator class="assigned" />
</id>
<property name="name" column="name" />
<property name="address" column="address" />
</class>
</hibernate-mapping>
Explanation
-
<hibernate-mapping>
is the root element in the mapping file. -
<class>
specifies the Persistent/POJO class. -
<id>
specifies the primary key attribute in the class. -
<generator>
is the sub element of id. It is used to generate the primary key. There are many generator classes such asassigned
,increment
,hilo
,sequence
,native
etc. We will learn all the generator classes later. -
property
It is the sub-element of class that specifies the property name of the Persistent class.
4.Configuration File
-
Configuration file contains 3 types of information.
-
Connection Properties
-
Hibernate Properties
-
Mapping file name(s)
-
-
We must create configuration file for each database we are going to use.
No. of databases we are using = That many number of configuration files
Syntax of Configuration file
<hibernate-configuration>
<session-factory>
<!-- Related to the connection START -->
<property name="connection.driver_class">Driver Class Name </property>
<property name="connection.url">URL </property>
<property name="connection.user">user </property>
<property name="connection.password">password</property>
<!-- Related to the connection END -->
<!-- Related to hibernate properties START -->
<property name="show_sql">true/false</property>
<property name="dialet">Database dialet class</property>
<property name="hbm2ddl.auto">create/update or what ever</property>
<!-- Related to hibernate properties END-->
<!-- Related to mapping START-->
<mapping resource="hbm file 1 name .xml" / >
<mapping resource="hbm file 2 name .xml" / >
<!-- Related to the mapping END -->
</session-factory>
</hibernate-configuration>
Example: hibernate.cfg.xml
<?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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/smlcodes</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="EmployeeBo.hbm.xml" />
</session-factory>
</hibernate-configuration>
5.Application class for main logic
We will create our application class with the main() method to run the application. We will use this application to save Employee data. Please follow the steps to write Application class
1.Load Hibernate API into Our Application
Load hibernate API by writing these two lines on the top of the application.
import org.hibernate.*;
import org.hibernate.cfg.*;
2.Load Configurations
Among Configuration(hibernate.cfg.xml), Mapping xml files, first we need to load configuration xml, because once we load the configuration file, automatically mapping xml file will also load, because it is defined it Configuration(hibernate.cfg.xml) file
We can load the configuration file by using Configuration class Object. cfg.configure(-xml”) loads the all the configurations from config file and save in config object, now config object contains all configuration details.
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
3.Open Session
SessionFactory will produces the Session objects based on the requests. To get
Session Object we have to call openSession()
method on SessionFactory Object.
Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.
Whenever session is opened then internally a database connection will be opened
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
4. Create Transaction Object
While working with insert, update, delete, operations from a hibernate application onto the database then hibernate needs a logical Transaction, if we are selecting an object from the database then we do not require any logical transaction in hibernate.
To begin a logical transaction in hibernate then we need to call a method beginTransaction() given by Session Interface
Transaction tx = session.beginTransaction();
session.save(bo);
System.out.println("Employee Data saved successfully.....!!");
tx.commit();
We have following methods for performing CURD operations
session.save(bo)
- Inserting object “bo”into databasesession.update(bo)
- Updating object “bo” in the databasesession.load(bo)
- Selecting object “bo” objectsession.delete(bo)
- Deleting object “bo”from database
Finally we need to call commit() in Transaction, like tx.commit();
5.Close the Connections
Finally we need to close the all opend connections
session.close();
factory.close();
Example : EmployeeSave.java
package app;
import org.hibernate.*;
import org.hibernate.cfg.*;
import bo.EmployeeBo;
public class EmployeeSave {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
EmployeeBo bo = new EmployeeBo();
bo.setEid(5);
bo.setName("DILEEP");
bo.setAddress("BANGLORE");
Transaction tx = session.beginTransaction();
session.save(bo);
System.out.println("Employee Data saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}
----------------------------------------------------------
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Employee Data saved successfully.....!!
Hibernate: insert into employee (name, address, eid) values (?, ?, ?)
Summarized Steps for creating Application class
Configuration
SessionFactory
Session
Transaction
Close Statements