0% found this document useful (0 votes)
11 views65 pages

WT 5

The document provides an introduction to Hibernate, a Java framework for Object-Relational Mapping (ORM) that simplifies database interactions by mapping Java objects to database tables. It explains the advantages of using Hibernate over traditional database methods, including automatic transaction management and reduced SQL complexity. Additionally, it covers Hibernate's architecture, API components, environment setup, and configuration methods for effective database management in Java applications.

Uploaded by

SANJAY N
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)
11 views65 pages

WT 5

The document provides an introduction to Hibernate, a Java framework for Object-Relational Mapping (ORM) that simplifies database interactions by mapping Java objects to database tables. It explains the advantages of using Hibernate over traditional database methods, including automatic transaction management and reduced SQL complexity. Additionally, it covers Hibernate's architecture, API components, environment setup, and configuration methods for effective database management in Java applications.

Uploaded by

SANJAY N
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/ 65

Introduction

to Hibernate
Mr.Sudheer Benarji P
Assistant Professor
Department of CSE
VNR VJIET
SYLLABUS

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


Object-Relational Mapping (ORM)
• Object-relational mapping (ORM) is a programming technique that allows
data to be exchanged between an object-oriented programming language
and a relational database.
• It creates a virtual object database that can be used within the
programming language.
• ORM (Object Relational Mapping) is needed because it simplifies database
interactions in object-oriented programming by bridging the gap between
object-oriented languages (like Java, Python, or C#) and relational
databases (like MySQL, PostgreSQL, or Oracle).

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


TRADITIONAL DATABASES

• 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.

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");


Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE id = 1");
while(rs.next()) {
System.out.println(rs.getString("name"));
}

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


Object-Relational Mapping

• ORM automates this by generating SQL queries based on object-oriented


class definitions, reducing errors and improving maintainability.
• ORM helps by mapping class attributes to table columns, making database
interaction more intuitive.
• ORM frameworks handle these operations internally, allowing developers to
focus on business logic.
• ORM frameworks support multiple database engines, so switching databases
(e.g., from MySQL to PostgreSQL) often requires minimal changes in the code.
• Since ORM frameworks generate SQL queries internally and use prepared
statements, they reduce the risk of SQL injection attacks.

User user = session.get(User.class, 1);


System.out.println(user.getName());

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE
• Hibernate is a Java framework, licensed under the open-source GNU Lesser General
Public License (LGPL), and is available for free download.
• Developed in 2001 by Gavin King, Hibernate was introduced as a groundbreaking
alternative to the EJB2-style entity bean approach.
• By mapping Java objects to database tables, it streamlines data persistence and
retrieval without the need for complex SQL queries.
• With features like automatic transaction management and caching, Hibernate simplifies
and optimizes database interactions, making it an indispensable framework for efficient
data management in Java applications.

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.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE ADVANTAGES
• Hibernate takes care of mapping Java classes to database tables using XML
files and without writing any line of code.
• Provides simple APIs for storing and retrieving Java objects directly to and
from the database.
• If there is change in the database or in any table, then you need to change
the XML file properties only.
• Abstracts away the unfamiliar SQL types and provides a way to work around
familiar Java Objects.
• Hibernate does not require an application server to operate.
• Manipulates Complex associations of objects of your database.
• Minimizes database access with smart fetching strategies.
• Provides simple querying of data.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE ARCHITECTURE

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE ARCHITECTURE

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.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE ARCHITECTURE
2. Hibernate Layer
This is the core of Hibernate and consists of multiple components:
a) Hibernate Configuration
Configuration files contain database connection settings and Hibernate properties.
Two types of configuration files:
hibernate.properties (Properties file format)
hibernate.cfg.xml (XML format)
b) SessionFactory
It is a factory for Session objects.
Reads the configuration file and establishes a connection with the database.
It is a heavyweight object, so typically, only one instance is created per database in an application
c) Hibernate Session
• It is a lightweight object created from SessionFactory.
• Acts as an interface between the Java application and the database.
• Provides methods to perform CRUD (Create, Read, Update, Delete) operations.
d) Transaction
• Manages database transactions.
• Ensures that operations are executed in a reliable and consistent manner.
• Transactions can be committed (commit()) or rolled back (rollback()).
e) Query
• Used to fetch and manipulate data from the database.
• Hibernate supports:
⚬ HQL (Hibernate Query Language): Object-oriented query language.
⚬ Criteria API: Programmatic way to create queries dynamically..

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE ARCHITECTURE

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.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE API
Hibernate provides a set of APIs that facilitate interaction with
databases in an object-oriented manner. These APIs allow developers to
manage sessions, transactions, queries, and configurations without
writing complex SQL queries.
1. Configuration (org.hibernate.cfg.Configuration)
• The Configuration object is the first Hibernate object you create in
any Hibernate application. It is usually created only once during
application initialization. It represents a configuration or properties
file required by the Hibernate.
• The Configuration object provides two keys components −
• Database Connection − This is handled through one or more
configuration files supported by Hibernate. These files are
hibernate.properties and hibernate.cfg.xml.
• Class Mapping Setup − This component creates the connection
between the Java classes and database 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();

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE API
4. Transaction (org.hibernate.Transaction)
• Manages transactions in Hibernate.
• Ensures atomicity (all operations succeed or none).
• Transactions must be committed or rolled back explicitly.

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;
}

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE Environment Setup

• Install Java JDK, IDE, and database like MySQL or H2.


• Create a new Java or Maven project in your preferred IDE.
• Add Hibernate and database dependencies to pom.xml (for Maven).
• Create hibernate.cfg.xml in src/main/resources with DB and Hibernate settings.
• Define your entity class using @Entity, @Table, and JPA annotations.
• Add the entity class mapping in hibernate.cfg.xml.
• Create a Hibernate utility class to configure and provide the SessionFactory.
• Open a Hibernate session and begin a transaction.
• Use the session to perform CRUD operations like save(), update(), etc.
• Commit the transaction and close the session to complete the operation.
• Run your application and verify data insertion in the database.
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
HIBERNATE Environment Setup (2nd way)

• Download the latest version of Hibernate from http://www.hibernate.org/downloads.


• Now, copy all the library files from /lib into your CLASSPATH, and change your classpath
variable to include all the JARs −
• Finally, copy hibernate3.jar file into your CLASSPATH. This file lies in the root directory of
the installation and is the primary JAR that Hibernate needs to do its work.
• To install any packages, you will have to copy library files from /lib into your
CLASSPATH, and change your CLASSPATH variable accordingly.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE CONFIGURATION

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.

Hibernate configuration involves setting up Hibernate to interact with a database. This is


typically done using either an XML-based configuration (hibernate.cfg.xml) or Java-
based configuration (HibernateUtil with StandardServiceRegistry).

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE CONFIGURATION
Hibernate Properties

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE CONFIGURATION
1. Hibernate Configuration via hibernate.cfg.xml (XML-based)

This file is placed in the src/main/resources directory.

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>

<!-- Hibernate dialect -->


<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>

<!-- Show SQL output -->


<property name="hibernate.show_sql">true</property>

<!-- Auto update the database schema -->


<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Mapping files -->


Mr. Sudheer Benarji P,class="com.example.model.YourEntity"
<mapping Assistant Professor, Department /> of CSE, VNRVJIET
</session-factory>
HIBERNATE CONFIGURATION
2. Java-based Hibernate Configuration (Without
XML)
Instead of using an XML file, you can configure Hibernate in Java using StandardServiceRegistry.

Example: Java-based Configuration java CopyEdit


import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {


private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {


try {
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // Loads hibernate.cfg.xml
.build();
return new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception ex) {
throw new RuntimeException("SessionFactory creation failed: " + ex.getMessage());
}
}

public static SessionFactory getSessionFactory() {


return sessionFactory;
Mr. Sudheer
} Benarji P, Assistant Professor, Department of CSE, VNRVJIET
}
HIBERNATE SESSIONS

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.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


Instances may exist in one of the following three states at a given
point in time −

• transient − A new instance of a persistent class, which is not associated with a


Session and has no representation in the database and no identifier value is
considered transient by Hibernate.
• persistent − You can make a transient instance persistent by associating it with
a Session. A persistent instance has a representation in the database, an
identifier value and is associated with a Session.
• detached − Once we close the Hibernate Session, the persistent instance will
become a detached instance.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


A Session instance is serializable if its persistent classes are
serializable. A typical transaction should use the following idiom

Session session = factory.openSession();


Transaction tx = null;
try {
tx = session.beginTransaction();
// do some work
...
tx.commit();
}catch (Exception e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
} Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
HIBERNATE SESSIONS
Session Interface Methods
There are number of methods provided by the Session interface, these are few important methods

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE - PERSISTENT CLASS

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.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


There are following main rules of persistent classes, however, none
of these rules are hard requirements

• All Java classes that will be persisted need a default constructor.


• All classes should contain an ID in order to allow easy identification of your
objects within Hibernate and the database. This property maps to the primary
key column of a database table.
• All attributes that will be persisted should be declared private and have getXXX
and setXXX methods defined in the JavaBean style.
• A central feature of Hibernate, proxies, depends upon the persistent class being
either non-final, or the implementation of an interface that declares all public
methods.
• All classes that do not extend or implement some specialized classes and
The POJO name is used
interfaces to emphasize
required that
by the EJB a given object is an ordinary Java Object, not a special
framework.
object, and in particular not an Enterprise JavaBean.
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
Simple POJO Example
Based on the few rules mentioned above, we can define a POJO class as
public class Employee { public int getId() {
follows
private int id; return id; public String getLastName() {
private String firstName; } return lastName;
private String lastName; public void setId( int id ) { }
private int salary; this.id = id; public void setLastName( String
} last_name ) {
public Employee() {} public String this.lastName = last_name;
public Employee(String getFirstName() { }
fname, String lname, int return firstName; public int getSalary() {
salary) { } return salary;
this.firstName = fname; public void setFirstName( }
this.lastName = lname; String first_name ) { public void setSalary( int salary ) {
this.salary = salary; this.firstName = this.salary = salary;
} Mr. Sudheer Benarji P, Assistant Professor, Department of} CSE, VNRVJIET
first_name;
HIBERNATE - MAPPING FILES

An Object/relational mappings are usually defined in an XML document. This


mapping file instructs Hibernate — how to map the defined class or classes to the
database tables?
Though many Hibernate users choose to write the XML by hand, but a number of
tools exist to generate the mapping document. These include XDoclet, Middlegen
and AndroMDA for the advanced Hibernate users.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


Let us consider our previously defined POJO class whose objects will persist in the
table defined in next section.
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;

public Employee() {}

public Employee(String fname, String lname, int salary) {


this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}

public int getId() {


return id;
}

public void setId( int id ) {


this.id = id;
}

public String getFirstName() {


return firstName;
}

public void setFirstName( String first_name ) {


this.firstName = first_name;
}

public String getLastName() {


return lastName;
}

public void setLastName( String last_name ) {


this.lastName = last_name;
}

public int getSalary() {


return salary;
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
}
Let us consider our previously defined POJO class whose objects will persist in the
table defined in next section.

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

create table EMPLOYEE (


id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


Based on the two above entities, we can define following mapping file, which
instructs Hibernate how to map the defined class or classes to the database tables.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<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.

Step 1: Setup Hibernate in Your Java Project


Create a Java Project (if using an IDE like IntelliJ or Eclipse).

Add Hibernate Dependencies


Step 2: Configure Hibernate (hibernate.cfg.xml)
Create the Hibernate configuration file inside src/main/resources:

Step 3: Create Entity Class


Define an entity class (User.java) with Hibernate annotations

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


BUILDING HIBERNATE APPLICATION
Step 4: Create Hibernate Utility Class
This utility class sets up the SessionFactory to interact with the database.

Step 5: Perform Database Operations


Create a UserDAO.java class to interact with the database.

Step 6: Main Method to Test


Create a Main.java class to test the Hibernate application.

Step 7: Run the Application


1. Ensure MySQL is running and the database is created (your_database).
2.Compile and run Main.java.
⚬ Hibernate will automatically create the table users.
⚬ A new user will be inserted.
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
⚬ The inserted user will be fetched and displayed.
HIBERNATE - O/R MAPPINGS

There are three most important mapping topics

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

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


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.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


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.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


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.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE ANNOTATIONS

• 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.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE ANNOTATIONS
import javax.persistence.*;

@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() {}

public int getId() {


return id;
}

public void setId( int id ) {


this.id = id;
}

public String getFirstName() {


return firstName;
}

public void setFirstName( String first_name ) {


this.firstName = first_name;
}

public String getLastName() {


return lastName;
}

public void setLastName( String last_name ) {


this.lastName = last_name;
}

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


public int getSalary() {
return salary;
}
HIBERNATE ANNOTATIONS

@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

@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.
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>

<property name = "hibernate.dialect">


org.hibernate.dialect.MySQLDialect
</property>

<property name = "hibernate.connection.driver_class">


com.mysql.jdbc.Driver
</property>

<!-- Assume students is the database name -->

<property name = "hibernate.connection.url">


jdbc:mysql://localhost/test
</property>

<property name = "hibernate.connection.username">


root
</property>

<property name = "hibernate.connection.password">


Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
cohondob
</property>
HIBERNATE QUERY LANGUAGE

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.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE QUERY LANGUAGE

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();

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE QUERY LANGUAGE

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();

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE QUERY LANGUAGE

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.

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE QUERY LANGUAGE

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();

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE QUERY LANGUAGE

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();

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);
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
query.setParameter("employee_id",10);
HIBERNATE QUERY LANGUAGE
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);
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);

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE QUERY LANGUAGE
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);

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE QUERY LANGUAGE
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 −

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE QUERY LANGUAGE
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 −

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();

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE QUERY LANGUAGE
PAGINATION USING QUERY

Using above two methods together, we can construct a


paging component in our web or Swing application. int pageNumber = 2;

Following is the example, which you can extend to fetch int pageSize = 10;

10 rows at a time −
Query query = session.createQuery("FROM Employee");

String hql = "FROM Employee"; query.setFirstResult((pageNumber - 1) * pageSize); // For page 2: (2-1)*10 =

Query query = session.createQuery(hql); 10

query.setFirstResult(1); query.setMaxResults(pageSize); // Limit to 10 records

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>

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


// this adds hibernate to the maven project
HIBERNATE EXECUTION
4. Create the Employee.java to create the structure and add dependencies
package org.example; @Override
import jakarta.persistence.*; public String toString() {
@Entity return "Employee{" +
@Table(name="employees") "id=" + id +
public class Employee { ", name='" + name + '\'' +
@Id ", salary=" + salary +
@GeneratedValue(strategy= GenerationType.IDENTITY) '}';
private int id; }
@Column(name="username") public String getName() {
private String name; return name;
@Column(name="salary") }
private double salary; public void setName(String name) {
public Employee() {} this.name = name;
public int getId() { }
return id; public double getSalary() {
} return salary;
public void setId(int id) { }
this.id = id; public void setSalary(double salary) {
} this.salary = salary;
public Employee(String name, double salary) { }
this.name = name; }
this.salary = salary;
}
public Employee(int id, String name, double salary) {
Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET
this.id = id;
this.name = name;
HIBERNATE EXECUTION
5. Add the hibernate configuration file in hibernate.cfg.xml

<?XML VERSION='1.0' ENCODING='UTF-8'?>


<!DOCTYPE HIBERNATE-CONFIGURATION PUBLIC
"-//HIBERNATE/HIBERNATE CONFIGURATION DTD 3.0//EN"
"HTTP://HIBERNATE.SOURCEFORGE.NET/HIBERNATE-CONFIGURATION-3.0.DTD">

<HIBERNATE-CONFIGURATION>
<SESSION-FACTORY>

<!-- JDBC CONNECTION SETTINGS -->


<PROPERTY NAME="HIBERNATE.CONNECTION.DRIVER_CLASS">COM.MYSQL.CJ.JDBC.DRIVER</PROPERTY>
<PROPERTY NAME="HIBERNATE.CONNECTION.URL">JDBC:MYSQL://LOCALHOST:3306/YOUR_DATABASE</PROPERTY>
<PROPERTY NAME="HIBERNATE.CONNECTION.USERNAME">YOUR_USERNAME</PROPERTY>
<PROPERTY NAME="HIBERNATE.CONNECTION.PASSWORD">YOUR_PASSWORD</PROPERTY>

<!-- JDBC CONNECTION POOL (OPTIONAL) -->


<PROPERTY NAME="CONNECTION.POOL_SIZE">10</PROPERTY>

<!-- SQL DIALECT -->


<PROPERTY NAME="HIBERNATE.DIALECT">ORG.HIBERNATE.DIALECT.MYSQL8DIALECT</PROPERTY>

<!-- SHOW SQL IN CONSOLE -->


<PROPERTY NAME="SHOW_SQL">TRUE</PROPERTY>

<!-- UPDATE THE SCHEMA IF NECESSARY -->


<PROPERTY NAME="HBM2DDL.AUTO">UPDATE</PROPERTY>

<!-- ENTITY CLASS MAPPING -->


<MAPPING CLASS="COM.YOURPACKAGE.YOURENTITY"/>

</SESSION-FACTORY>
</HIBERNATE-CONFIGURATION>

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE EXECUTION
6. Add MySQL connector dependency to pom.xml

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>

Mr. Sudheer Benarji P, Assistant Professor, Department of CSE, VNRVJIET


HIBERNATE EXECUTION
// Read (SELECT)
7. Write the code to communicate with database with Hibernate
try (Session session = factory.openSession()) {
using Session List<Employee> employees = session.createQuery("from Employee", Employee.class).list();
import org.example.Employee; System.out.println("All Employees:");
import org.hibernate.Session; for (Employee e : employees) {
import org.hibernate.SessionFactory; System.out.println(e);

import org.hibernate.Transaction; }

import org.hibernate.cfg.Configuration; }
// Update

import java.util.List; try (Session session = factory.openSession()) {


Transaction tx = session.beginTransaction();

public class HibernateExample { Employee e = session.get(Employee.class, 1); // update Alice

public static void main(String[] args) { if (e != null) {

Configuration cfg = new e.setSalary(55000);

Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Employee.class); session.update(e);

SessionFactory factory = cfg.buildSessionFactory(); System.out.println("Updated Employee: " + e);


}

// Create (INSERT) with manual IDs tx.commit();

Employee emp1 = new Employee(1, "Alice", 50000); }

Employee emp2 = new Employee(2, "Bob", 60000); // Delete


try (Session session = factory.openSession()) {

try (Session session = factory.openSession()) { Transaction tx = session.beginTransaction();

Transaction tx = session.beginTransaction(); Employee e = session.get(Employee.class, 2); // delete Bob

session.save(emp1); if (e != null) {

session.save(emp2); session.delete(e);

tx.commit(); System.out.println("Deleted Employee: " + e);


Mr. Sudheer Benarji P, Assistant Professor,
System.out.println("Employees inserted"); } Department of CSE, VNRVJIET

You might also like