0% found this document useful (0 votes)
68 views22 pages

Hibernate

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views22 pages

Hibernate

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Unit 4 Hibernate

This hibernate provides in-depth concepts of Hibernate Framework with simplified


examples. It was started in 2001 by Gavin King as an alternative to EJB2 style entity bean.

Hibernate Framework
Hibernate is a Java framework that simplifies the development of Java application to
interact with the database. It is an open source, lightweight, ORM (Object Relational
Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API) for
data persistence.

ORM Tool
An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.

The ORM tool internally uses the JDBC API to interact with the database.

What is JPA?
Java Persistence API (JPA) is a Java specification that provides certain functionality and
standard to ORM tools. The javax.persistence package contains the JPA classes and
interfaces.

Advantages of Hibernate Framework


Following are the advantages of hibernate framework:

1) Open Source and Lightweight

Hibernate framework is open source under the LGPL license and lightweight.

2) Fast Performance

The performance of hibernate framework is fast because cache is internally used in


hibernate framework. There are two types of cache in hibernate framework first level
cache and second level cache. First level cache is enabled by default.

3) Database Independent Query

HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the
database independent queries. So you don't need to write database specific queries.
Before Hibernate, if database is changed for the project, we need to change the SQL query
as well that leads to the maintenance problem.

4) Automatic Table Creation

Hibernate framework provides the facility to create the tables of the database
automatically. So there is no need to create tables in the database manually.

5) Simplifies Complex Join

Fetching data from multiple tables is easy in hibernate framework.

6) Provides Query Statistics and Database Status

Hibernate supports Query cache and provide statistics about query and database status.

Hibernate Architecture
1. Hibernate Architecture
2. Elements of Hibernate Architecture
1. SessionFactory
2. Session
3. Transaction
4. ConnectionProvider
5. TransactionFactory

The Hibernate architecture includes many objects such as persistent object, session
factory, transaction factory, connection factory, session, transaction etc.

The Hibernate architecture is categorized in four layers.

o Java application layer


o Hibernate framework layer
o Backhand api layer
o Database layer

Let's see the diagram of hibernate architecture:


This is the high level architecture of Hibernate with mapping file and configuration file.Play
Video

Hibernate framework uses many objects such as session factory, session, transaction etc.
alongwith existing Java API such as JDBC (Java Database Connectivity), JTA (Java
Transaction API) and JNDI (Java Naming Directory Interface).

Elements of Hibernate Architecture


For creating the first hibernate application, we must know the elements of Hibernate architecture. They are
follows:
SessionFactory

The SessionFactory is a factory of session and client of ConnectionProvider. It holds


second level cache (optional) of data. The org.hibernate.SessionFactory interface provides
factory method to get the object of Session.

Session

The session object provides an interface between the application and data stored in the
database. It is a short-lived object and wraps the JDBC connection. It is factory of
Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The
org.hibernate.Session interface provides methods to insert, update and delete the object.
It also provides factory methods for Transaction, Query and Criteria.

Transaction

The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.

ConnectionProvider

It is a factory of JDBC connections. It abstracts the application from DriverManager or


DataSource. It is optional.

TransactionFactory

It is a factory of Transaction. It is optional.

First Hibernate Example without IDE


1. Steps to create first Hibernate Application
1. Create the Persistent class
2. Create the mapping file for Persistent class
3. Create the Configuration file
4. Create the class that retrieves or stores the persistent object
5. Load the jar file
6. Run the first hibernate application without IDE
Here, we are going to create the first hibernate application without IDE. For creating the
first hibernate application, we need to follow the following steps:

1. Create the Persistent class


2. Create the mapping file for Persistent class
3. Create the Configuration file
4. Create the class that retrieves or stores the persistent object
5. Load the jar file
6. Run the first hibernate application by using command prompt

1) Create the Persistent class


A simple Persistent class should follow some rules:

o A no-arg constructor: It is recommended that you have a default constructor at least


package visibility so that hibernate can create the instance of the Persistent class by
newInstance() method.
o Provide an identifier property: It is better to assign an attribute as id. This attribute
behaves as a primary key in database.
o Declare getter and setter methods: The Hibernate recognizes the method by getter and
setter method names by default.
o Prefer non-final class: Hibernate uses the concept of proxies, that depends on the
persistent class. The application programmer will not be able to use proxies for lazy
association fetching.

Let's create the simple Persistent class:

Employee.java
package com.javatpoint.mypackage;

public class Employee {


private int id;
private String firstName,lastName;

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}

2) Create the mapping file for Persistent class


The mapping file name conventionally, should be class_name.hbm.xml. There are many
elements of the mapping file.

o hibernate-mapping : It is the root element in the mapping file that contains all the
mapping elements.
o class : It is the sub-element of the hibernate-mapping element. It specifies the Persistent
class.
o id : It is the subelement of class. It specifies the primary key attribute in the class.
o generator : It is the sub-element of id. It is used to generate the primary key. There are
many generator classes such as assigned, increment, hilo, sequence, native etc. We will
learn all the generator classes later.
o property : It is the sub-element of class that specifies the property name of the Persistent
class.

Let's see the mapping file for the Employee class:

employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">

<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>

<property name="firstName"></property>
<property name="lastName"></property>

</class>

</hibernate-mapping>

3) Create the Configuration file


The configuration file contains information about the database and mapping file.
Conventionally, its name should be hibernate.cfg.xml .

hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>

<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>

</hibernate-configuration>

4) Create the class that retrieves or stores the object


In this class, we are simply storing the employee object to the database.

package com.javatpoint.mypackage;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class StoreData {


public static void main(String[] args) {

//Create typesafe ServiceRegistry object


StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml"
).build();

Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();

SessionFactory factory = meta.getSessionFactoryBuilder().build();


Session session = factory.openSession();
Transaction t = session.beginTransaction();

Employee e1=new Employee();


e1.setId(101);
e1.setFirstName("Gaurav");
e1.setLastName("Chawla");

session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();

}
}

O/R Mapping with Hibernate.


there are three most important mapping topics, which we have to learn
in detail.

These are −

 Mapping of collections,
 Mapping of associations between entity classes, and
 Component Mappings.

Collections Mappings
If an entity or class has collection of values for a particular variable,
then we can map those values using any one of the collection
interfaces available in java. Hibernate can persist instances
of java.util.Map, java.util.Set, java.util.SortedMap, java.util.SortedSet,
java.util.List, and any array of persistent entities or values.

Sr.No. Collection type & Mapping Description

java.util.Set
1
This is mapped with a <set> element and initialized with java.util.HashSet

java.util.SortedSet
2
This is mapped with a <set> element and initialized with java.util.TreeSet.
The sort attribute can be set to either a comparator or natural ordering.

java.util.List
3
This is mapped with a <list> element and initialized with java.util.ArrayList

java.util.Collection
4
This is mapped with a <bag> or <ibag> element and initialized with
java.util.ArrayList

java.util.Map
5
This is mapped with a <map> element and initialized with
java.util.HashMap

java.util.SortedMap
6 This is mapped with a <map> element and initialized with
java.util.TreeMap. The sort attribute can be set to either a comparator or
natural ordering.

Arrays are supported by Hibernate with <primitive-array> for Java


primitive value types and <array> for everything else. However,
they are rarely used, so I am not going to discuss them in this
tutorial.

If you want to map a user defined collection interfaces, which is not


directly supported by Hibernate, you need to tell Hibernate about
the semantics of your custom collections, which is not very easy and
not recommend to be used.
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.

Sr.No. Mapping type & Description

Many-to-One
1
Mapping many-to-one relationship using Hibernate

One-to-One
2
Mapping one-to-one relationship using Hibernate

One-to-Many
3
Mapping one-to-many relationship using Hibernate

Many-to-Many
4
Mapping many-to-many relationship using Hibernate

Component Mappings
It is very much possible that an Entity class can have a reference to
another class as a member variable. If the referred class does not
have its own life cycle and completely depends on the life cycle of
the owning entity class, then the referred class hence therefore is
called as the Component class.

The mapping of Collection of Components is also possible in a


similar way just as the mapping of regular Collections with minor
configuration differences. We will see these two mappings in detail
with examples.

Sr.No. Mapping type & Description

1 Component Mappings
Mapping for a class having a reference to another class as a member
variable.

Hibernate Annotation
Following section will explain the annotations class.

@Entity Annotation
The EJB 3 standard annotations are contained in
the javax.persistence package, so we import this package as the first
step. Second, we used the @Entity annotation to the Employee
class, which marks this class as an entity bean, so it must have a
no-argument constructor that is visible with at least protected
scope.

@Table Annotation
The @Table annotation allows you to specify the details of the table
that will be used to persist the entity in the database.

The @Table annotation provides four attributes, allowing you to


override the name of the table, its catalogue, and its schema, and
enforce unique constraints on columns in the table. For now, we are
using just table name, which is EMPLOYEE.

@Id and @GeneratedValue Annotations


Each entity bean will have a primary key, which you annotate on
the class with the @Id annotation. The primary key can be a single
field or a combination of multiple fields depending on your table
structure.

By default, the @Id annotation will automatically determine the


most appropriate primary key generation strategy to be used but
you can override this by applying the @GeneratedValue annotation,
which takes two parameters strategy and generator that I'm not going
to discuss here, so let us use only the default key generation
strategy. Letting Hibernate determine which generator type to use
makes your code portable between different databases.

@Column Annotation
The @Column annotation is used to specify the details of the
column to which a field or property will be mapped. You can use
column annotation with the following most commonly used
attributes −

 name attribute permits the name of the column to be explicitly


specified.
 length attribute permits the size of the column used to map a
value particularly for a String value.
 nullable attribute permits the column to be marked NOT NULL
when the schema is generated.
 unique attribute permits the column to be marked as containing
only unique values.

Hibernate Query Language (HQL)


Hibernate Query Language (HQL) is an object-oriented query
language, similar to SQL, but instead of operating on tables and
columns, HQL works with persistent objects and their properties.
HQL queries are translated by Hibernate into conventional SQL
queries, which in turns perform action on database.

Although you can use SQL statements directly with Hibernate using
Native SQL, but I would recommend to use HQL whenever possible
to avoid database portability hassles, and to take advantage of
Hibernate's SQL generation and caching strategies.

Keywords like SELECT, FROM, and WHERE, etc., are not case
sensitive, but properties like table and column names are case
sensitive in HQL.
Query Interface
It is an object oriented representation of Hibernate Query. The object of Query can be
obtained by calling the createQuery() method Session interface.

The query interface provides many methods. There is given commonly used methods:

1. public int executeUpdate() is used to execute the update or delete query.


2. public List list() returns the result of the ralation as a list.
3. public Query setFirstResult(int rowno) specifies the row number from where record will
be retrieved.
4. public Query setMaxResult(int rowno) specifies the no. of records to be retrieved from
the relation (table).
5. public Query setParameter(int position, Object value) it sets the value to the JDBC style
query parameter.
6. public Query setParameter(String name, Object value) it sets the value to a named
query parameter.

Example of HQL to get all the records

1. Query query=session.createQuery("from Emp");//here persistent class name is Emp


2. List list=query.list();

Example of HQL to get records with pagination

1. Query query=session.createQuery("from Emp");


2. query.setFirstResult(5);
3. query.setMaxResult(10);
4. List list=query.list();//will return the records from 5 to 10th number
Example of HQL update query

1. Transaction tx=session.beginTransaction();
2. Query q=session.createQuery("update User set name=:n where id=:i");
3. q.setParameter("n","Udit Kumar");
4. q.setParameter("i",111);
5.
6. int status=q.executeUpdate();
7. System.out.println(status);
8. tx.commit();

Example of HQL delete query

1. Query query=session.createQuery("delete from Emp where id=100");


2. //specifying class name (Emp) not tablename
3. query.executeUpdate();

HQL with Aggregate functions


You may call avg(), min(), max() etc. aggregate functions by HQL. Let's see some common
examples:

Example to get total salary of all the employees


1. Query q=session.createQuery("select sum(salary) from Emp");
2. List<Integer> list=q.list();
3. System.out.println(list.get(0));

Example to get maximum salary of employee

1. Query q=session.createQuery("select max(salary) from Emp");

Example to get minimum salary of employee

1. Query q=session.createQuery("select min(salary) from Emp");


Example to count total number of employee ID

1. Query q=session.createQuery("select count(id) from Emp");

Example to get average salary of each employees

1. Query q=session.createQuery("select avg(salary) from Emp");

FROM Clause
You will use FROM clause if you want to load a complete persistent
objects into memory. Following is the simple syntax of using FROM
clause −

String hql = "FROM Employee";


Query query = session.createQuery(hql);
List results = query.list();

If you need to fully qualify a class name in HQL, just specify the
package and class name as follows −

String hql = "FROM com.hibernatebook.criteria.Employee";


Query query = session.createQuery(hql);
List results = query.list();

AS Clause
The AS clause can be used to assign aliases to the classes in your
HQL queries, especially when you have the long queries. For
instance, our previous simple example would be the following −

String hql = "FROM Employee AS E";


Query query = session.createQuery(hql);
List results = query.list();
The AS keyword is optional and you can also specify the alias
directly after the class name, as follows −

String hql = "FROM Employee E";


Query query = session.createQuery(hql);
List results = query.list();

SELECT Clause
The SELECT clause provides more control over the result set then
the from clause. If you want to obtain few properties of objects
instead of the complete object, use the SELECT clause. Following is
the simple syntax of using SELECT clause to get just first_name
field of the Employee object −

String hql = "SELECT E.firstName FROM Employee E";


Query query = session.createQuery(hql);
List results = query.list();

It is notable here that Employee.firstName is a property of Employee


object rather than a field of the EMPLOYEE table.

WHERE Clause
If you want to narrow the specific objects that are returned from
storage, you use the WHERE clause. Following is the simple syntax
of using WHERE clause −

String hql = "FROM Employee E WHERE E.id = 10";


Query query = session.createQuery(hql);
List results = query.list();

ORDER BY Clause
To sort your HQL query's results, you will need to use the ORDER
BY clause. You can order the results by any property on the objects
in the result set either ascending (ASC) or descending (DESC).
Following is the simple syntax of using ORDER BY clause −
String hql = "FROM Employee E WHERE E.id > 10 ORDER BY
E.salary DESC";
Query query = session.createQuery(hql);
List results = query.list();

If you wanted to sort by more than one property, you would just
add the additional properties to the end of the order by clause,
separated by commas as follows −

String hql = "FROM Employee E WHERE E.id > 10 " +


"ORDER BY E.firstName DESC, E.salary DESC ";
Query query = session.createQuery(hql);
List results = query.list();

GROUP BY Clause
This clause lets Hibernate pull information from the database and
group it based on a value of an attribute and, typically, use the
result to include an aggregate value. Following is the simple syntax
of using GROUP BY clause −

String hql = "SELECT SUM(E.salary), E.firtName FROM


Employee E " +
"GROUP BY E.firstName";
Query query = session.createQuery(hql);
List results = query.list();

Using Named Parameters


Hibernate supports named parameters in its HQL queries. This
makes writing HQL queries that accept input from the user easy and
you do not have to defend against SQL injection attacks. Following
is the simple syntax of using named parameters −

String hql = "FROM Employee E WHERE E.id = :employee_id";


Query query = session.createQuery(hql);
query.setParameter("employee_id",10);
List results = query.list();
UPDATE Clause
Bulk updates are new to HQL with Hibernate 3, and delete work
differently in Hibernate 3 than they did in Hibernate 2. The Query
interface now contains a method called executeUpdate() for
executing HQL UPDATE or DELETE statements.

The UPDATE clause can be used to update one or more properties of


an one or more objects. Following is the simple syntax of using
UPDATE clause −

String hql = "UPDATE Employee set salary = :salary " +


"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("salary", 1000);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

DELETE Clause
The DELETE clause can be used to delete one or more objects.
Following is the simple syntax of using DELETE clause −

String hql = "DELETE FROM Employee " +


"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

INSERT Clause
HQL supports INSERT INTO clause only where records can be
inserted from one object to another object. Following is the simple
syntax of using INSERT INTO clause −

String hql = "INSERT INTO Employee(firstName, lastName,


salary)" +
"SELECT firstName, lastName, salary FROM
old_employee";
Query query = session.createQuery(hql);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

Aggregate Methods
HQL supports a range of aggregate methods, similar to SQL. They
work the same way in HQL as in SQL and following is the list of the
available functions −

Sr.No. Functions & Description

1 avg(property name)
The average of a property's value

2 count(property name or *)
The number of times a property occurs in the results

3 max(property name)
The maximum value of the property values

4 min(property name)
The minimum value of the property values

5 sum(property name)
The sum total of the property values

The distinct keyword only counts the unique values in the row set.
The following query will return only unique count −

String hql = "SELECT count(distinct E.firstName) FROM


Employee E";
Query query = session.createQuery(hql);
List results = query.list();

Pagination using Query


There are two methods of the Query interface for pagination.
Sr.No. Method & Description

Query setFirstResult(int startPosition)


1 This method takes an integer that represents the first row in your result set,
starting with row 0.

Query setMaxResults(int maxResult)


2 This method tells Hibernate to retrieve a fixed number maxResults of
objects.

Using above two methods together, we can construct a paging


component in our web or Swing application. Following is the
example, which you can extend to fetch 10 rows at a time −

String hql = "FROM Employee";


Query query = session.createQuery(hql);
query.setFirstResult(1);
query.setMaxResults(10);
List results = query.list();

Advantage of HQL
There are many advantages of HQL. They are as follows:

o database independent
o supports polymorphic queries
o easy to learn for Java Programmer

You might also like