Hibernate Tutorial
Hibernate Tutorial
Hibernate Tutorial
Audience:
This class is designed for Java programmers with a need to understand the Hibernate framework and API. This tutorial will bring you at intermediate level of experties.
Prerequisites:
Before proceeding with this tutorial you should have a good understanding of the Java programming language. A basic understanding of relational databases, JDBC and SQL is very helpful.
Hibernate Overview:
Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks. Hibernate sits between traditional Java objects and database server to handle all the work in persisting those objects based on the appropriate O/R mechanisms and patterns.
Hibernate Advantages:
Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code. Provides simple APIs for storing and retrieving Java objects directly to and from the database. If there is change in Database or in any table then the only need to change XML file properties.
1|Page
Supported Databases:
Hibernate supports almost all the major RDBMS. Following is list of few of the database engines supported by Hibernate.
HSQL Database Engine DB2/NT MySQL PostgreSQL FrontBase Oracle Microsoft SQL Server Database Sybase SQL Server Informix Dynamic Server
Hibernate Architecture:
The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs. Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application. Following is a very high level view of the Hibernate Application Architecture.
2|Page
Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers. Following section gives brief description of each of the class objects involved in Hibernate Application Architecture.
Configuration Object:
The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate. The Configuration object provides two keys components: 1. 2. Database Connection: This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml. Class Mapping Setup This component creates the connection between the Java classes and database tables..
SessionFactory Object:
Configuration object is used to create a SessionFactory object which inturn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be
3|Page
Session Object:
A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object. The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.
Transaction Object:
A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA). This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.
Query Object:
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.
Criteria Object:
Criteria object are used to create and execute object oriented criteria queries to retrieve objects.
Downloading Hibernate:
It is assumed that you already have latest version of Java is installed on your machine. Following are the simple steps to download and install Hibernate on your machine.
Make a choice whether you want to install Hibernate on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix. Download the latest version of Hibernate from http://www.hibernate.org/downloads. At the time of writing this tutorial I downloaded hibernate-distribution-3.6.4.Final and when you unzip the downloaded file it will give you directory structure as follows.
4|Page
Installing Hibernate:
Once you downloaded and unzipped the latest version of the Hibernate Installation file, you need to perform following two simple steps. Make sure you are setting your CLASSPATH variable properly otherwise you will face problem while compiling your application.
Now copy all the library files from /lib into your CLASSPATH, and change your classpath variable to include all the JARs: Finally copy hibernate3.jar file into your CLASSPATH. This file lies in the root directory of the installation and is the primary JAR that Hibernate needs to do its work.
Hibernate Prerequisites:
Following is the list of the packages/libraries required by Hibernate and you should install them before starting with Hibernate. To install these packages you would have to copy library files from /lib into your CLASSPATH, and change your CLASSPATH variable accordingly. S.N. 1 2 3 4 5 6 7 Packages/Libraries dom4j - XML parsing www.dom4j.org/ Xalan - XSLT Processor http://xml.apache.org/xalan-j/ Xerces - The Xerces Java Parser http://xml.apache.org/xerces-j/ cglib - Appropriate changes to Java classes at runtime http://cglib.sourceforge.net/ log4j - Logging Faremwork http://logging.apache.org/log4j Commons - Logging, Email etc. http://jakarta.apache.org/commons SLF4J - Logging Facade for Java http://www.slf4j.org
Hibernate Configuration
Hibernate requires to know in advance where to find the mapping information that defines how your Java classes relate to the database tables. Hibernate also requires a set of configuration
5|Page
Hibernate Properties:
Following is the list of important properties you would require to configure for a databases in a standalone situation: S.N. 1 Properties and Description hibernate.dialect This property makes Hibernate generate the appropriate SQL for the chosen database. hibernate.connection.driver_class The JDBC driver class. hibernate.connection.url The JDBC URL to the database instance. hibernate.connection.username The database username. hibernate.connection.password The database password. hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool. hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.
If you are using a database along with an application server and JNDI then you would have to configure the following properties: S.N. 1 Properties and Description hibernate.connection.datasource The JNDI name defined in the application server context youre using for the application. hibernate.jndi.class The InitialContext class for JNDI.
6|Page
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property> <!-- Assume test is the database name --> <property name="hibernate.connection.url"> jdbc:mysql://localhost/test </property> <property name="hibernate.connection.username"> root </property> <property name="hibernate.connection.password"> root123 </property> <!-- List of XML mapping files --> <mapping resource="Employee.hbm.xml"/> </session-factory> </hibernate-configuration>
The above configuration file includes <mapping> tags which are related to hibernate-mapping file and we will see in next chapter what exactly is a hibernate mapping file and how and why do we use it. Following is the list of various important databases dialect property type:
7|Page
Hibernate Examples
8|Page
public class Employee { private int id; private String firstName; private String lastName; private int salary; public Employee() {} public Employee(String fname, String lname, int salary) { this.firstName = fname; this.lastName = lname; this.salary = salary; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String first_name ) { this.firstName = first_name; } public String getLastName() { return lastName; } public void setLastName( String last_name ) { this.lastName = last_name; } public int getSalary() { return salary; } public void setSalary( int salary ) { this.salary = salary; } }
9|Page
create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) );
<?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="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> </hibernate-mapping>
You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. Let us see little detail about the mapping document:
The mapping document is an XML document having <hibernate-mapping> as the root element which contains all the <class> elements. The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. The <meta> element is optional element and can be used to create the class description. The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <generator> element within the id element is used to automatically generate the primary key values. Set the class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute
10 | P a g e
import java.util.List; import java.util.Date; import java.util.Iterator; import import import import import org.hibernate.HibernateException; org.hibernate.Session; org.hibernate.Transaction; org.hibernate.SessionFactory; org.hibernate.cfg.Configuration;
public class ManageEmployee { private static SessionFactory factory; public static void main(String[] args) { try{ factory = new Configuration().configure().buildSessionFactory(); }catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } ManageEmployee ME = new ManageEmployee(); /* Add few employee records in database */ Integer empID1 = ME.addEmployee("Zara", "Ali", 1000); Integer empID2 = ME.addEmployee("Daisy", "Das", 5000); Integer empID3 = ME.addEmployee("John", "Paul", 10000); /* List down all the employees */ ME.listEmployees(); /* Update employee's records */ ME.updateEmployee(empID1, 5000); /* Delete an employee from the database */ ME.deleteEmployee(empID2); /* List down new list of the employees */ ME.listEmployees(); } /* Method to CREATE an employee in the database */ public Integer addEmployee(String fname, String lname, int salary){ Session session = factory.openSession(); Transaction tx = null; Integer employeeID = null; try{ tx = session.beginTransaction(); Employee employee = new Employee(fname, lname, salary);
11 | P a g e
12 | P a g e
You would get following result, and records would be created in EMPLOYEE table.
$java ManageEmployee .......VARIOUS LOG MESSAGES WILL DISPLAY HERE........ First First First First First Name: Name: Name: Name: Name: Zara Daisy John Zara John Last Name: Ali Salary: 1000 Last Name: Das Salary: 5000 Last Name: Paul Salary: 10000 Last Name: Ali Salary: 5000 Last Name: Paul Salary: 10000
mysql> select * from EMPLOYEE; +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 29 | Zara | Ali | 5000 | | 31 | John | Paul | 10000 | +----+------------+-----------+--------+ 2 rows in set (0.00 sec mysql>
13 | P a g e
Learn Java Learn JDBC Java Examples Learn Best Practices Learn Python Learn Ruby Learn Ruby on Rails Learn SQL Learn MySQL Learn AJAX Learn C Programming Learn C++ Programming Learn CGI with PERL Learn DLL Learn ebXML Learn Euphoria Learn GDB Debugger Learn Makefile Learn Parrot Learn Perl Script Learn PHP Script Learn Six Sigma Learn SEI CMMI Learn WiMAX Learn Telecom Billing
Learn CSS Learn HTTP Learn JavaScript Learn jQuery Learn Prototype Learn script.aculo.us Web Developer's Guide Learn RADIUS Learn RSS Learn SEO Techniques Learn SOAP Learn UDDI Learn Unix Sockets Learn Web Services Learn XML-RPC Learn UML Learn UNIX Learn WSDL Learn i-Mode Learn GPRS Learn GSM Learn WAP Learn WML Learn Wi-Fi
14 | P a g e