Hibernate
Hibernate
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.
Hibernate framework is open source under the LGPL license and lightweight.
2) Fast Performance
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.
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.
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.
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).
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
TransactionFactory
Employee.java
package com.javatpoint.mypackage;
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.
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>
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>
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;
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
}
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.
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.
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.
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.
@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 −
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. 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();
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 −
If you need to fully qualify a class name in HQL, just specify the
package and class name as follows −
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 −
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 −
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 −
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 −
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 −
DELETE Clause
The DELETE clause can be used to delete one or more objects.
Following is the simple syntax of using DELETE clause −
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 −
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 −
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 −
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