WT 5
WT 5
to Hibernate
Mr.Sudheer Benarji P
Assistant Professor
Department of CSE
VNR VJIET
SYLLABUS
• Traditional database interaction requires writing raw SQL queries for every
CRUD (Create, Read, Update, Delete) operation.
• Without ORM, developers have to write repetitive JDBC (or equivalent) code
for database operations.
• Without ORM, switching databases requires rewriting a lot of SQL queries.
JDBC
JDBC (Java Database Connectivity) provides a set of Java APIs to access the relational
databases from the Java program.
Java APIs enable programs to execute SQL statements and interact with any SQL database.
JDBC gives a flexible architecture to write a database-independent web application that
can execute on different platforms and interact with different DBMS without any change.
1. Application Layer
• This is the topmost layer where the application
interacts with Hibernate.
• Persistence Object: It represents a Java object
(POJO) that is mapped to a database table.
• The application creates and manipulates
persistence objects, and Hibernate takes care of
persisting them into the database.
3. Database Layer
• This is the lowest layer, where the actual data resides.
• Hibernate converts object-oriented operations into SQL queries and
executes them on the database.
• The database stores the records in tables.
Eg.
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
Mr. Sudheer Benarji SessionFactory
P, Assistant sessionFactory =
Professor, Department of CSE, VNRVJIET
cfg.buildSessionFactory();
HIBERNATE API
2. SessionFactory (org.hibernate.SessionFactory)
• A factory for Session objects.
• It is heavyweight, so only one instance per database is recommended.
• Maintains metadata and connection settings.
SessionFactory object configures Hibernate for the application using the supplied
configuration file and allows for a Session object to be instantiated. The SessionFactory is
a thread safe object and used by all the threads of an application.
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.
Eg.
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
HIBERNATE API
3. Session (org.hibernate.Session)
• A lightweight, short-lived object that interacts with the database.
• Used for CRUD operations (Create, Read, Update, Delete).
• Obtained from SessionFactory.
A Session is used to get a physical connection with a database. The Session object is
lightweight and designed to be instantiated each time an interaction is needed with the
database. Persistent objects are saved and retrieved through a Session object.
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
Eg.
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(myObject); // Saving an entity
session.getTransaction().commit();
session.close();
A Transaction represents a unit of work with the database and most of the RDBMS
supports transaction functionality. Transactions in Hibernate are handled by an
underlying transaction manager and transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this
interface, instead managing transactions in their own application code.
Eg.
Transaction tx = session.beginTransaction();
try {
session.save(myObject);
tx.commit(); // Commit if everything is fine
} catch (Exception e) {
tx.rollback(); // Rollback in case of an error
} Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
HIBERNATE API
5. Query (org.hibernate.query.Query)
• Used to execute queries in Hibernate.
• Supports HQL (Hibernate Query Language) and native SQL queries.
• Provides methods like list(), uniqueResult(), and executeUpdate().
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from
the database and create objects. A Query instance is used to bind query parameters,
limit the number of results returned by the query, and finally to execute the query.
Eg.
Query query = session.createQuery("FROM Employee WHERE id = :empId");
6. Criteria API (org.hibernate.Criteria)
query.setParameter("empId", 101); Employee emp = (Employee) query.uniqueResult();
• Provides a programmatic way to create dynamic queries.
• Eliminates the need to write raw SQL or HQL.
• Supports pagination, filtering, and ordering.
Criteria objects are used to create and execute object oriented criteria queries to
retrieve objects.
Eg.
Criteria criteria = session.createCriteria(Employee.class);
criteria.add(Restrictions.eq("department", "IT"));
Mr. Sudheer
List<Employee> Benarji P, Assistant
itEmployees Professor, Department of CSE, VNRVJIET
= criteria.list();
HIBERNATE API
7. Annotations (javax.persistence.*)
• Hibernate supports JPA (Java Persistence API) annotations to define mappings.
Eg.
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name")
private String name;
}
Hibernate requires to know in advance — where to find the mapping information that
defines how your Java classes relate to the database tables. Hibernate also requires a
set of configuration settings related to database and other related parameters. All such
information is usually supplied as a standard Java properties file called
hibernate.properties, or as an XML file named hibernate.cfg.xml.
Example
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate//DTD Configuration 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
A Session is used to get a physical connection with a database. The Session object
is lightweight and designed to be instantiated each time an interaction is needed
with the database. Persistent objects are saved and retrieved through a Session
object.
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.
The main function of the Session is to offer, create, read, and delete operations for
instances of mapped entity classes.
The entire concept of Hibernate is to take the values from Java class attributes and
persist them to a database table. A mapping document helps Hibernate in
determining how to pull the values from the classes and map them with table and
associated fields.
Java classes whose objects or instances will be stored in database tables are
called persistent classes in Hibernate. Hibernate works best if these classes follow
some simple rules, also known as the Plain Old Java Object (POJO) programming
model.
public Employee() {}
There would be one table corresponding to each object you are willing to provide
persistence. Consider above objects need to be stored and retrieved into the
following RDBMS table
<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"/>
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
</class>
You should save the mapping document in a file with the format <classname>.hbm.xml.
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
• The mapping document is an XML document having <hibernate-mapping> as the root element, which
contains all the <class> elements.
• The <class> elements are used to define specific mappings from a Java classes to the database tables. The
Java class name is specified using the name attribute of the class element and the database table name is
specified using the table attribute.
• The <meta> element is optional element and can be used to create the class description.
• The <id> element maps the unique ID attribute in class to the primary key of the database table. The name
attribute of the id 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.
• 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 to let hibernate pick up either identity, sequence, or
hilo algorithm to create primary key depending upon the capabilities of the underlying database.
• 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
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
the database table. The type attribute holds the hibernate mapping type, this mapping types will convert
BUILDING HIBERNATE APPLICATION
Building a Hibernate application involves several key steps, including setting up the
environment, configuring Hibernate, defining entity classes, and interacting with a
database. Below is a structured guide to building a Hibernate application.
• Mapping of collections
• Mapping of associations between entity classes, and
• 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.
• So far you have seen how Hibernate uses XML mapping file for the transformation of data from
POJO to database tables and vice versa.
• Hibernate annotations are the newest way to define mappings without the use of XML file.
• You can use annotations in addition to or as a replacement of XML mapping metadata.
• Hibernate Annotations is the powerful way to provide the metadata for the Object and
Relational Table mapping.
• All the metadata is clubbed into the POJO java file along with the code, this helps the user to
understand the table structure and POJO simultaneously during the development.
• If you going to make your application portable to other EJB 3 compliant ORM applications, you
must use annotations to represent the mapping information, but still if you want greater
flexibility, then you should go with XML-based mappings.
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id @GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "salary")
private int salary;
public Employee() {}
@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.
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
HIBERNATE ANNOTATIONS
@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.
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
HIBERNATE ANNOTATIONS
Now let us create hibernate.cfg.xml configuration file to define database related parameters.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
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 −
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 −
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();
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
HIBERNATE QUERY LANGUAGE
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();
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);
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
HIBERNATE QUERY LANGUAGE
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);
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);
The distinct keyword only counts the unique values in the row set. The following query will
return only unique count −
Following is the example, which you can extend to fetch int pageSize = 10;
10 rows at a time −
Query query = session.createQuery("FROM Employee");
query.setMaxResults(10);
List results = query.list(); List results = query.list();
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
HIBERNATE EXECUTION
1.Download IntelliJ IDE community Edition
2. Follow the installation steps and complete the installation
3. Include Hibernate in your project
Open pom.xml in your project and add the below lines in dependencies
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.5.2.Final</version> <!-- Replace with the desired version -->
</dependency>
</dependencies>
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
HIBERNATE EXECUTION
1.Download IntelliJ IDE community Edition
2. Follow the installation steps and complete the installation
3. Include Hibernate in your project
Open pom.xml in your project and add the below lines in dependencies
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.5.2.Final</version> <!-- Replace with the desired version -->
</dependency>
</dependencies>
<HIBERNATE-CONFIGURATION>
<SESSION-FACTORY>
</SESSION-FACTORY>
</HIBERNATE-CONFIGURATION>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
import org.hibernate.Transaction; }
import org.hibernate.cfg.Configuration; }
// Update
Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Employee.class); session.update(e);
session.save(emp1); if (e != null) {
session.save(emp2); session.delete(e);