Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

CSI3018- Advanced Java

Module – 5
Hibernate

1
SCOPE
CSI3018- Advanced Java
Outline

• Introduction
• Hibernate architecture
• Object Relation Mapping (ORM)
• Hibernate annotations
• Hibernate Query Language
• CURD application using Hibernate

2
SCOPE
CSI3018- Advanced Java
Introduction
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.
What is ORM tool?
It is a technique that maps the object stored in the database.
An ORM tool simplifies data creation, manipulation, and access.
It internally uses the Java API to interact with the databases.

3
SCOPE
CSI3018- Advanced Java
Introduction
What is JPA?

JPA defines a set of functionalities, standards, and concepts to the


ORM tool. It is available in the javax.persistence package.

To decrease the line of codes for relational object management, a


coder must follow the "JPA Framework," which easily allows
interaction with the database.

Why Hibernate?

Hibernate overcomes the database dependency faced in the JDBC.

Hibernate strengthens the object level relationship – eliminates


the impedance mismatch problem
4
SCOPE
CSI3018- Advanced Java
Hibernate Features

5
SCOPE
CSI3018- Advanced Java
Hibernate Features
Lightweight
Hibernate is a lightweight framework as it does not contains additional
functionalities; it uses only those functionalities required for object-relational
mapping.
It is a lightweight framework because it uses persistent classes for data transfer
between java application and databases.

ORM (Object Relation Mapping)


Hibernate is an ORM tool which helps in the interaction between the java classes
and relational database.
It also solves the problem of data mismatch found in Java application and RDBMS.

HQL (Hibernate Query Language)


Hibernate has its query language, i.e., HQL (Hibernate Query Language) which is
independent of the database.
HQL is an object-oriented language similar to SQL, but it works with the persistent
object and its properties.

6
SCOPE
CSI3018- Advanced Java
Hibernate Features
Auto-Generation
Hibernate provides a feature of automatic table generation. It means a
programmer need not worry about the query implementation, i.e., Hibernate
does on its own.

Lazy Loading
Hibernate supports a new concept called lazy loading. Lazy loading concept
retrieves the only necessary object for execution.
It also improves the performance of an application.

Database Independent
Hibernate is database-independent as it provides ‘Database Dialect’ so we need
not write SQL queries.
It supports many databases such as Oracle, MySql, Sybase, etc.

7
SCOPE
CSI3018- Advanced Java Hibernate Architecture
Hibernate is an ORM framework
with a layered architecture.

There are mainly three layers in


Hibernate architecture:-

Application Layer
Hibernate Core Layer
Database Layer

8
SCOPE
CSI3018- Advanced Java
Hibernate Framework

9
SCOPE
CSI3018- Advanced Java Core Objects of the Hibernate Framework
1. Configuration
The org.hibernate.cfg package contains the Configuration class, which
consists of the properties and function files of Hibernate.
The configuration object is created only once during the application
initialization.
To activate the Hibernate Framework, we use the following code:
Configuration cfg=new Configuration();

It reads both mapping and configuration file.


cfg.configure();

2. SessionFactory
The org.hibernate.sessionFactory package contains the SessionFactory
interface whose object can be obtained by the object of Configuration class.
It is a threadsafe object and used by all the threads in the application.

The below code shows the creation of SessionFactory object:


SessionFactory factory=cfg.buildSessionFactory();
It takes the JDBC information from cfg object and creates a JDBC
connection. 10
SCOPE
CSI3018- Advanced Java

Core Objects of the Hibernate Framework


3. Session
The org.hibernate.session package contains the Session interface. A
SessionFactory object is used to create a Session object, which is lightweight
object.
It is used to execute CRUD operations (insert, delete, update, edit). It also holds
the first-level cache data in Hibernate.
The below code shows the creation of Session object:
Session session=factory.buildSession();

4. Transaction
The org.hibernate.transaction package contains a Transaction interface.
The object of the session creates a Transaction object. It provides the instruction
to the database for transaction management.

The below code shows the creation of Transaction object:


Transaction t=session.beginTransaction();
t.commit();
The commit() function is used to close the transaction.
11
SCOPE
CSI3018- Advanced Java

Core Objects of the Hibernate Framework


5. Query
The org.hibernate.query package contains Query and Criteria interface,
respectively. Query objects use Hibernate Query Language (HQL) to get data
from the database.
Session objects are used to create query objects.
The below code shows the initialization of Query object:
Query query= session.createQuery();

12
SCOPE
CSI3018- Advanced Java
First Hibernate Example

To create the first hibernate application without IDE


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

13
SCOPE
CSI3018- Advanced Java
First Hibernate Example
Create the Persistent class

A simple Persistent class should follow some rules:


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.
Provide an identifier property: It is better to assign an attribute
as id. This attribute behaves as a primary key in database.
Declare getter and setter methods: The Hibernate recognizes the
method by getter and setter method names by default.

14
SCOPE
CSI3018- Advanced Java
First Hibernate Example
Create the Persistent class
Student.java
package com.mypackage; public String getName() {
return name;
public class Student { }
private long id;
public void setName(String name) {
private String name; this.name = name;
private String degree; }

public long getId() { public String getDegree() {


return id; return degree;
} }

public void setId(long id) { public void setDegree(String degree) {


this.degree = degree;
this.id = id;
}
} }

15
SCOPE
CSI3018- Advanced Java

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.

hibernate-mapping : It is the root element in the mapping file that contains all
the mapping elements.
class : It is the sub-element of the hibernate-mapping element. It specifies the
Persistent class.
id : It is the sub-element of class. It specifies the primary key attribute in the
class.
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.
property : It is the sub-element of class that specifies the property name of the
Persistent class.

16
SCOPE
CSI3018- Advanced Java

Create the mapping file for Persistent class


student.hbm.xml
<hibernate-mapping>
<class name="com.mypackage.Student" table=“STUDENT">
<id name="id">
<generator class="assigned"></generator>
</id>

<property name=“name"></property>
<property name=“degree"></property>

</class>

</hibernate-mapping>

<property name="name" column="sname" not-null="true" />

17
SCOPE
CSI3018- Advanced Java

Create the Configuration file


The configuration file contains information about the database and mapping
file. Conventionally, its name should be hibernate.cfg.xml .
<hibernate-configuration> to create the table in the database
automatically
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<mapping resource=“student.hbm.xml"/>
</session-factory>

18
</hibernate-configuration> SCOPE
CSI3018- Advanced Java

Create the class that retrieves or stores the object


package com.mypackage;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class AddStudent {


public static void main(String args[]) throws Exception {
long id=101;
String name = “Arjun";
String degree = "MTech";
Student s1 = new Student();
s1.setId(id);
s1.setDegree(degree);
s1.setName(name);

19
SCOPE
CSI3018- Advanced Java

Create the class that retrieves or stores the object


try {
SessionFactory sessionFactory = new Configuration().configure(
"/hibernate.cfg.xml").buildSessionFactory();
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
s.save(s1);
tx.commit();
s.close();
} catch (Exception e) {
System.out.println(e.getMessage());
System.err.println("Initial SessionFactory creation failed." + e);
}
System.out.println("Added to Database");
}// end of method
}// end of class

20
SCOPE
CSI3018- Advanced Java
Introduction
5. Load the jar file
For successfully running the hibernate application, you should have the
hibernate5.jar file.

6. How to run the first hibernate application without IDE

 Install the oracle10g (Database Server) for this example.


Load the jar files for hibernate. (One of the way to load the jar file is copy all the
jar files under the JRE/lib/ext folder.)
Now, run the AddStudent class by java com.mypackage.AddStudent

21
SCOPE
CSI3018- Advanced Java
Configuration file

For MySQL Database


update
org.hibernate.dialect.MySQL5Dialect
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306
root
root

22
SCOPE
CSI3018- Advanced Java
Hibernate - O/R Mappings
Entity Association Mapping
The mapping of associations between entity classes and the
relationships between tables is the soul of ORM. In other words, it
specifies how the objects are associated with each other.

Hibernate provides four types of association mapping, which are


listed below:
1. One To One
2. One To Many
3. Many To One
4. Many To Many
The types of association mapping can be uni-directional or bi-
directional

23
SCOPE
CSI3018- Advanced Java
O/R Association Mappings
One to One Mapping
only one object of a persistent class is related to only one object of another persistent
class.

Student.hbm.xml
<hibernate-mapping>
<class name="com.hibernate.Student" table="STUD1">
<id name="studentId" type="long" column="ID">
<generator class="increment" />
</id>
<property name="studentName" type="string" length="100"
not-null="true" column="name" />
<one-to-one name="address" class="com.hibernate.Address"
cascade="all" />
</class>
</hibernate-mapping>
24
SCOPE
CSI3018- Advanced Java
O/R Association Mappings
One to Many Mapping

In One-to-Many association mapping, only one object of one persistent class is


related to more than one objects of another persistent class.

It is a relationship in which one (parent) is related to many (children).

To achieve a One-to-Many relationship between two objects, we need to take a


collection property such as Set, Map, and List in the parent class.

A Set is a java collection that does not contain any duplicate element. A Set is
mapped with a <set> element in the mapping table and initialized with
java.util.HashSet. You can use Set collection in your class when there is no
duplicate element required in the collection.

25
SCOPE
CSI3018- Advanced Java O/R Association Mappings
One to Many Mapping

<hibernate-mapping>
<class name="com.hibernate.Student" table="student">
<id name="studentId" column="sutid">
<generator class="increment" />
</id>
<property name="studentName" column="stud_name" type="string" />
<set name="studentPhone" cascade="all">
<key column="stud_id" />
<one-to-many class="com.hibernate.Phone" />
</set>
</class>
</hibernate-mapping>
26
SCOPE
CSI3018- Advanced Java O/R Association Mappings
Many to One Mapping
It is one of the most commonly used association mapping.
In Hibernate, Many-to-One association mapping is applied from child class
object to parent class object.

<hibernate-mapping>
<class name="com.hibernate.Student" table="STUD1">
<id name="studentId" type="long" column="ID">
<generator class="increment" />
</id>
<property name="studentName" type="string" length="100"
not-null="true" column="name" />
<many-to-one name="studentAddress" class="com.hibernate.Address"
column="STUDENT_ADDRESS" cascade="all" />
</class>
</hibernate-mapping>

27
SCOPE
CSI3018- Advanced Java O/R Association Mappings
Many to Many Mapping

In Many-to-Many association mapping, many objects of one persistent class are


associated with many objects of another persistent class.
For example, many (students) are related to many (courses) and vice-versa as
many-to-many is a bidirectional association mapping.

To achieve many-to-many mapping, we need to declare collection property in both


persistent classes.

<set name="courses" table="SCOURSE" cascade="all">


<key column="SID" />
<many-to-many column="CID" class="com.hibernate.Course" />
</set>
28
SCOPE
CSI3018- Advanced Java
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.
Advantages of HQL
Database Independent- HQL is a database-independent query language. That means if we
write programs using HQL commands, then the program can be executed in all relational
databases without any modification.
Case- insensitive for keywords- HQL is similar to SQL. Hence, their properties are also
identical. HQL is case-insensitive for keywords like SQL, which means all the keywords can
be written in both upper and lower case. For example, select, SELECT, and Select are all the
same.
Object-oriented- HQL is an object-oriented query language as it supports inheritance,
polymorphism, and association. Instead of real table names and columns, it uses class and
property names.
Easy to Learn- HQL is easy to learn and implement, as its syntax is identical to SQL.

29
SCOPE
CSI3018- Advanced Java
HQL Syntax
SELECT Clause
String hql = "SELECT from Employee";
Query query = session.createQuery(hql);
List results = query.list();

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


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

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);
30
SCOPE
CSI3018- Advanced Java
HQL
INSERT 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);

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);
31
SCOPE
CSI3018- Advanced Java CRUD Application
public class Student{
public void insertStudent() {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction = session.beginTransaction();

String hql = "INSERT INTO Student (firstName, lastName, email) " +


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

// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}
32
SCOPE
CSI3018- Advanced Java CRUD Application
public void updateStudent(Student student) {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction = session.beginTransaction();

// save the student object


String hql = "UPDATE Student set firstName = :firstName " + "WHERE id =
:studentId";
Query query = session.createQuery(hql);
query.setParameter("firstName", student.getFirstName());
query.setParameter("studentId", 1);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace(); 33
} } SCOPE
CSI3018- Advanced Java CRUD Application
public void deleteStudent(int id) {

Transaction transaction = null;


try (Session session = HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
// Delete a student object
Student student = session.get(Student.class, id);
if (student != null) {
String hql = "DELETE FROM Student " + "WHERE id = :studentId";
Query query = session.createQuery(hql);
query.setParameter("studentId", id);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);
}
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} }
34
SCOPE
CSI3018- Advanced Java CRUD Application
public Student getStudent(int id) {
Transaction transaction = null;
Student student = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
// get an student object
String hql = " FROM Student S WHERE S.id = :studentId";
Query query = session.createQuery(hql);
query.setParameter("studentId", id);
List results = query.getResultList();

if (results != null && !results.isEmpty()) {


student = (Student) results.get(0);
}
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} 35
return student; } SCOPE
CSI3018- Advanced Java CRUD Application
public List < Student > getStudents() {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
return session.createQuery("from Student", Student.class).list();
}
}
}

36
SCOPE

You might also like