Hibernate Database Operations:
Hibernate is a framework which provides some abstraction
layer, meaning that the programmer does not have to worry
about the implementations, hibernate does the
implementations for you internally like Establishing a
connection with the database, writing query to perform
CRUD operations etc.
It is a java framework which is used to develop persistence
logic. Persistence logic means to store and process the data
for long use. More precisely Hibernate is an open-source,
non-invasive, light-weight java ORM (Object-relational
mapping) framework to develop objects which are
independent of the database software and make independent
persistence logic in all JAVA, JEE.
Open-Source means:
• Hibernate framework is available for everyone without
any cost.
• The source code of Hibernate is also available on the
Internet and we can also modify the code.
Light-weight means:
• Hibernate is less in size means the installation
package is not big is size.
• Hibernate does not require any heavy container for
execution.
• Hibernate can be used alone or we can use Hibernate
with other java technology and framework.
Non-invasive means:
• The classes of Hibernate application development are
loosely coupled classes with respect to Hibernate API
i.e. Hibernate class need not implement hibernate API
interfaces and need not extend from Hibernate API
classes.
Hibernate Architecture
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
Elements of Hibernate Architecture
For creating the first hibernate application, we must know the elements of Hibernate
architecture. They are as 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.
Hibernate Operations:
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 turn perform an action on a
database.
HQL is extremely simple to learn and use, and the code is
always self-explanatory.
Let's briefly look at the snippets of HQL INSERT, UPDATE,
SELECT, and DELETE Examples then we will develop a
complete example to demonstrate the HQL CRUD example.
1. HQL Insert Query Example
The below snippet demonstrates the usage of HQL to insert a
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();
}
}
2. HQL Select Query Example
The below snippet demonstrates the usage of HQL for getting a
student by id:
public Student getStudent(int id) {
Transaction transaction = null;
Student student = null;
try (Session session =
HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
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();
}
return student;
}
The below snippet demonstrates the usage of HQL for getting
all students:
public List < Student > getStudents() {
try (Session session =
HibernateUtil.getSessionFactory().openSession()) {
return session.createQuery("from Student",
Student.class).list();
}
}
3. HQL Update Query Example
The below snippet demonstrates the usage of HQL to update a
student's firstName where id = 1:
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();
}
}
4. HQL Delete Query Example
The below snippet demonstrates the usage of HQL to delete a
student where id = 1:
public void deleteStudent(int id) {
Transaction transaction = null;
try (Session session =
HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
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();
}
}