2. Introduction to Hibernate.
Hibernate was started in 2001 by Gavin King as an alternative
to EJB2
Hibernate simplifies the development of java application.
C,C++,Java,etc.. Are programming languages.
JDBC,SERVLET,JSP,etc…are technologies.
Hibernate,Spring,etc..are framework.
3. ORM-Object Relational Mapping
ORM is a programming technique which is used to convert
object into a relational database.
Java Objects Directly Mapping
Relational
DB
Object Mapping Relational
4. Continues….
ORM framework is Hibernate.
Hibernate is an ORM tool which means it is used to map plain
java objects to tables of a relational database and vice-versa.
Your
Application ORM-Middleware acting as
a bridge between
application and DB
DB
5. The “CRUD” Operations handover the object to Hibernate.
Hibernate use JDBC internally to talk to the relational database
for persisting.
For ex: Student Class
Name
RollNo
Address
Mobile
7. In the above example if we are using JDBC,the programmer
need to write a lengthy code.
Instead, if we are using Hibernate, programmer want just to
pass the java object which you want to store and persist
implicitly and will generate optimized query and are stored data
into table.
If we are using hibernate the code will be like this:
9. In JDBC retrieval of data is performed by using result set.It
will be little bit difficult for the programmer to write the code.
In Hibernate,the code will be like this:
List Student_InfoList=Session.createQuery(“FROM Student_Info”).list();
10. Advantages of using Hibernate:
Faster retrieval of data.
• Can retrieve data only in a single line of code in hibernate.
Opening and closing of DB connection would no longer be a
problem.
• Some times the programmer forget to close the connection, they will lead to memory
leak problems. But Hibernate will do it implicitly.
Do not bother about change in a column of a table need only to
change in one place in XML file or java annotation in java model
object.
• Changing Mobile to Phone No:
11. Hibernate Architecture
Hibernate is a ORM framework that is built on the top of
multiple technologies like JDBC,JNDI(Java Naming Directory
Interface),JTA(Java Transaction API) etc…to develop object
based ORM mapping persistence logic as a db software
independent persistence logic.
Hibernate is a framework, it does not interact directly with db.
12. •JAVA uses i/p in the form of objects.
•Hibernate give o/p to application in the form of objects.
•Hibernate take support of one or more technologies to interact
with db through JDBC driver.
•Once persistence operations is done in db s/w results goes to
hibernate framework through JDBC driver and JTA.
13.
14. 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.
•It is usually created only once during application initialization.
It represents a configuration or properties file required by the
Hibernate.
15. The Configuration object provides two keys components −
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.
16. Class objects in hibernate Continues….
SessionFactory Object
• The SessionFactory is a heavyweight object; it is usually created during
application start up and kept for later use.
• You would need one SessionFactory object per database using a separate
configuration file. So, if you are using multiple databases, then you
would have to create multiple SessionFactory objects.
17. Class objects in hibernate Continues….
Session Object
•The Session object is lightweight and designed to be instantiated
each time an interaction is needed with the database.
•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.
18. Class objects in hibernate Continues….
Transaction Object
•This is an optional object and Hibernate applications may
choose not to use this interface
•Transactions in Hibernate are handled by an underlying
transaction manager and transaction (from JDBC or JTA).
19. Class objects in hibernate Continues….
Query Object
•Query objects use SQL or Hibernate Query Language (HQL)
string to retrieve data from the database and create objects.
20. Class objects in hibernate Continues….
Criteria Object
•Criteria objects are used to create and execute object
oriented criteria queries to retrieve objects.
21. Hibernate - Mapping Files
An Object/relational mappings are usually defined in an XML document. This
mapping file instructs Hibernate — how to map the defined class or classes to the
database tables?
Consider an ex:
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) );
22. Based on the two above entities, we can define following mapping file,
which instructs Hibernate how to map the defined class or classes to the
database tables.
<?xml version = "1.0" encoding = "utf-8"?>---
<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>
23. You should save the mapping document in a file with the format
<classname>.hbm.xml.
Here,We saved our mapping document in the file
Employee.hbm.xml.
Let us see understand a little detail about the mapping elements
used in the mapping file −
1. The mapping document is an XML document having <hibernate-
mapping> as the root element, which contains all the <class>
elements.
24. 2.The <class> elements are used to define specific mappings from a Java
classes to the database tables.
3. The <meta> element is optional element and can be used to create the
class description.
4. The <id> element maps the unique ID attribute in class to the primary
key of the database table.
5. The <generator> element within the id element is used to generate the
primary key values automatically. The class attribute of the generator
element is set to native
25. 6. 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 holds the
hibernate mapping type, this mapping types will convert from Java
to SQL data type.
26. Hibernate Query Language(HQL)
Hibernate Query Language (HQL) is same as SQL
(Structured Query Language) but it doesn't depends on the
table of the database.
Instead of table name, we use class name in HQL. So it is
database independent query language.
Keywords like SELECT, FROM, and WHERE, etc., are not
case sensitive, but properties like table and column names are
case sensitive in HQL.
27. Advantage of HQL
There are many advantages of HQL. They are as follows:
database independent
supports polymorphic queries
easy to learn for Java Programmer
28. Example of HQL to get all the records
Query query=session.createQuery("from Emp");//here persistent class nam
e is Emp
List list=query.list();
Example of HQL to get records with pagination
Query query=session.createQuery("from Emp");
query.setFirstResult(5);
query.setMaxResult(10);
List list=query.list();//will return the records from 5 to 10th number
29. Example of HQL delete query
Query query=session.createQuery("delete from Emp where id=100");
//specifying class name (Emp) not tablename
query.executeUpdate();
30. Hibernate - O/R Mappings
So far, we have seen very basic O/R mapping using hibernate,
but there are three most important mapping topics, which we
have to learn in detail.
These are −
Mapping of collections and
Mapping of associations between entity classes
31. Association Mappings
The mapping of associations between entity classes and the
relationships between tables is the soul of ORM.
Following are the four ways in which the cardinality of the
relationship between the objects can be expressed.
An association mapping can be unidirectional as well as
bidirectional.
32. Hibernate - Many-to-One Mappings
A many-to-one association is the most common kind of
association where an Object can be associated with multiple
objects. For example, the same address object can be associated
with multiple employee objects.
Define Hibernate Mapping File
The <many-to-one> element will be used to define the rule to
establish a many-to-one relationship between EMPLOYEE and
ADDRESS entities.
33. <?xml version = "1.0" encoding = "utf-8"?>---
<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"/>
<many-to-one name = "address" column = "address" class="Address" not-null="true"/>
</class>
<class name = "Address" table="ADDRESS">
<meta attribute = "class-description"> This class contains the address detail.
</meta>
<id name = "id" type = "int" column = "id">
<generator class="native"/> </id>
<property name = "street" column = "street_name" type = "string"/>
</class>
</hibernate-mapping>
34. The <many-to-one>element is used to set the relationship
between EMPLOYEE and ADDRESS entities.
The name attribute is set to the defined variable in the parent
class, in our case it is address.
The column attribute is used to set the column name in the
parent table EMPLOYEE.
35. Hibernate - One-to-Many Mappings
A one-to-one association is similar to many-to-one association with a
difference that the column will be set as unique. For example, an address
object can be associated with a single employee object.
36. Let’s look at the following entity relationship
diagram to see one-to-many association:
37. For this example, we will implement a Cart system, where we have a table for
Cart and another table for Items.
A Cart can have multiple items, so here we have a one-to-many mapping with
cart_id as a primary key in the Cart table and this association is constrained
by the foreign key in the Items table.
38. Hibernate - One-to-One Mappings
First of all we would need to setup One to One mapping in database tables.
We will create two tables for our example – Transaction and Customer.
Both of these tables will have one to one mapping.
Transaction will be the primary table and we will be using Foreign Key in
Customer table for one-to-one mapping.
Transaction Customer
39. Hibernate - Many-to-Many Mappings
Many-to-Many mapping is usually implemented in database using a Join Table.
For example we can have Cart and Item table and Cart_Items table for many-to-many mapping.
Every cart can have multiple items
and every item can be part of multiple carts, so we have a many to many mapping here.