KEMBAR78
Hibernate 1 | PDF | Databases | Object (Computer Science)
0% found this document useful (0 votes)
11 views46 pages

Hibernate 1

The document provides an overview of Hibernate, an open-source framework for Object-Relational Mapping (ORM) in Java, detailing its advantages over JDBC, which allows for database-independent applications. It explains Hibernate's architecture, including key components like Configuration, SessionFactory, Session, and Transaction objects, as well as the use of annotations for mapping Java classes to database tables. Additionally, it covers Hibernate Query Language (HQL) and provides examples of configuration and usage in Java applications.

Uploaded by

nimarjotk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views46 pages

Hibernate 1

The document provides an overview of Hibernate, an open-source framework for Object-Relational Mapping (ORM) in Java, detailing its advantages over JDBC, which allows for database-independent applications. It explains Hibernate's architecture, including key components like Configuration, SessionFactory, Session, and Transaction objects, as well as the use of annotations for mapping Java classes to database tables. Additionally, it covers Hibernate Query Language (HQL) and provides examples of configuration and usage in Java applications.

Uploaded by

nimarjotk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Hibernate

By – Rakesh Kumar
What is JDBC?
• JDBC stands for Java Database Connectivity. It provides a set of Java API for
accessing the relational databases from Java program, these Java APIs
enables Java programs to execute SQL statements and interact with any SQL
compliant database.
• JDBC provides a flexible architecture to write a database independent
application that can run on different platforms and interact with different
DBMS without any modification.

By – Rakesh Kumar
Pros and Cons of JDBC
Pros Cons

Clean and simple SQL processing Complex if it is used in large


projects.
Good performance with large data. Large programming overhead. No
encapsulation
Very good for small applications. Hard to implement MVC concept.

Simple syntax and easy to learn. Query is DBMS specific.

By – Rakesh Kumar
Object Relational Mapping (ORM)
• ORM is a programming technique for converting data between relational
databases and object oriented programming languages such as Java, C# etc.

By – Rakesh Kumar
Object Relational Mapping

By – Rakesh Kumar
Advantages of ORM over JDBC
• ORM lets business code access objects rather than DB tables.
• Hides details of SQL queries from object oriented logic.
• No need to deal with the database implementation.
• Entities based on business concepts rather than database structure.
• Transaction management and automatic key generation.
• Based on JDBC ‘under the hood’.
• Fast development of application.

By – Rakesh Kumar
Entities in ORM Solution
• API to perform basic CRUD operations on objects of persistent classes.
• A language or API to specify queries that refer to classes and properties of
classes.
• A configurable facility for specifying mapping metadata.
• A technique to interact with transactional objects to perform dirty checking,
lazy association fetching and other optimization functions.

By – Rakesh Kumar
Introduction to Hibernate
• Hibernate is an open source persistent framework created by Gavin King in
2001.
• It is a powerful, high performance Object-Relational persistence and Query
service for any Java application.
• It maps Java classes to database tables and from Java data types to SQL
data types and relieves the developer from 95% of common data persistence
related programming tasks.
• Hibernate sits between traditional Java objects and database server to handle
all the works in persisting those objects based on the appropriate O/R
mechanisms and patterns.

By – Rakesh Kumar
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 a change in the database or in any table, then the developer needs
to change the XML file properties only.
• Abstracts away the unfamiliar SQL types and provides a way to work around
familiar Java objects.
• It manipulates complex associations of objects of the database.
• Minimizes database access with smart fetching strategies.
• Provides simple querying of data.
By – Rakesh Kumar
Hibernate Architecture

By – Rakesh Kumar
Configuration Object
• The configuration object is the first hibernate object, the developer create in a
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 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.

By – Rakesh Kumar
SessionFactory Object
• 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. Developer require one
SessionFactory object per database using a separate configuration file. If a
developer uses multiple databases, then he needs to create multiple
SessionFactory objects.

By – Rakesh Kumar
Session Object
• 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 as needed.

By – Rakesh Kumar
Transaction Object
• 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.

By – Rakesh Kumar
Query Object
• 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.

By – Rakesh Kumar
Criteria Object
• Criteria objects are used to create and execute object oriented criteria queries
to retrieve objects.

By – Rakesh Kumar
Hibernate Configuration
• Hibernate requires to know in advance where to find the mapping information
that defines how Java classes relate to the database tables. Hibernate also
requires a set of configuration settings related to the 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.

By – Rakesh Kumar
Hibernate Properties
Properties Description

hibernate.diaelect It makes hibernate generate the appropriate SQL


for the chosen database.
hibernate.connection.dri JDBC driver class
ver.class

hibernate.connection.url JDBC url to the database.

By – Rakesh Kumar
Hibernate Properties
Properties Description

hibernate.connection.us Database username


ername
hibernate.connection.pa Database password
ssword
hibernate.connection.po Limits the number of connections waiting in the
ol_size hibernate database connection pool.

hibernate.connection.aut Allows autocommit mode to be used for the


ocommit JDBC connection.
By – Rakesh Kumar
hbm2ddl.auto Property
• This property defines how the database schema is handled.
• Possible values are
 create – Creates a new table in the database when the SessionFactory object is
created. In case a table exists in the database with the same name, it deletes the
table along with data and creates a new table.
 update – Hibernate first validates whether the table is present in the database. If
present, it alters that table as per the changes. If not, it creates a new one.
 validate – Hibernate only verifies whether the table is present. If the table does
not exist, then it throws an exception.
 create-drop – Hibernate creates a new table when SessionFactory is created,
performs required operations and deletes the table when SessionFactory is
destroyed. This value is used for testing hibernate code.
By – Rakesh Kumar
Hibernate Dialect
• A database dialect is a configuration option that allows software to translate
general SQL statements into vendor-specific DDL and DML. Different
database products, such as PostgreSQL, MySQL, Oracle and SQL Server,
have their own variant of SQL, which are called SQL dialects.
Database Dialect

MySQL org.hibernate.dialect.MySQLDialect

Oracle10g org.hibernate.dialect.Oracle10gDialect

By – Rakesh Kumar
Session
• 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.
• 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.

By – Rakesh Kumar
Session
• 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 associates with a
Session and has no representation in the database and no identifier value is
considered transient by hibernate.
 Persistent –Developer 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 the hibernate session is closed, the persistent instance will
become a detached instance.

By – Rakesh Kumar
Session Interface Methods
Method Description

Transaction Begin a unit of work and return the associated


beginTransaction() Transaction object.
Session Get the session factory which created this
getSessionFactory() session.
Query Create a new instance of Query for the given
createQuery(String HQL query string.
queryString)
void delete(Object Remove a persistent instance from the
object) datastore.

By – Rakesh Kumar
Session Interface Methods
Method Description

Transaction Get the transaction instance associated with this


getTransaction() session.
void Either save(Object) or update(Object) the given
saveOrUpdate(Object instance.
object)
void update(Object Update the persistent instance with the identifier
object) of the given detached instance.

By – Rakesh Kumar
Persistent Class
• The concept of hibernate is to take 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. Hibernate works best if these classes follow some
simple rules, also known as the Plain Old Java Object (POJO) programming
model.

By – Rakesh Kumar
Few Rules of Persistent Class
• All Java classes that will be persisted need a default constructor.
• All classes should contain an ID in order to allow easy identification of 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.

By – Rakesh Kumar
Annotations
• 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.

By – Rakesh Kumar
Annotated Class - Example
//Create Employee table in MySQL

create table employee


(empid int primary key,
name varchar(30));

By – Rakesh Kumar
Annotated Class - Example
import jakarta.*;

@Entity
@Table(name="employee")
public class Employee {
@Id
private int empid;
@Column(name="name")
private String name;

By – Rakesh Kumar
Annotated Class - Example
public Employee() {}
public Employee(int empid, String name)
{
this.empid=empid;
this.name=name;
}
public void setEmpid(int empid) {this.empid = empid;}
public void setName(String name) { this.name = name; }
public int getEmpid() { return empid; }
public String getName() { return name; } }

By – Rakesh Kumar
Annotations Used
• @Entity
This annotation marks this class as an entity bean, so it must have a no
argument constructor that is visible with at least protected scope.
• @Table
This annotation allows the developer to specify the details of the table that will
be used to persist the entry in the database.
@Id
Each entity bean will have a primary key. The primary key can be a single
field or combination of multiple fields depending on the table structure.

By – Rakesh Kumar
Annotations Used
• @GeneratedValue
This annotation is used in conjunction with the @Id annotation to specify that
the value of the primary key field will be automatically generated by the
database of persistence provider.
• @Column
It is used to specify the details of the column to which a field or property will
be mapped. This annotation is used with the attributes
 name – It permits the name of the column to be explicitly specified.
 length – It permits the size of the column used to map a value particularly for a string
value.
 nullable – It permits the column to be marked NOT NULL when the schema is generated.
 unique – It permits the column to be marked as containing only unique values.

By – Rakesh Kumar
Example – Student
package com.example;
import jakarta.persistence.*;
@Entity
@Table(name = "student")
public class Student {
@Id
private int rollno;
@Column(name="name")
private String name;
public Student()
{ }
public Student(int rollno,String name)
{
this.rollno=rollno;
this.name=name;
}
By – Rakesh Kumar
Example – Student
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

By – Rakesh Kumar
Example – Configuration
<?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>
<property name="hibernate.connection.driver.class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/college</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- JDBC connection pool (use built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

By – Rakesh Kumar
Example – Configuration
<!-- Show SQL -->
<property name="show_sql">true</property>
<!-- Automatically create/drop tables -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.example.Student"></mapping>
</session-factory>
</hibernate-configuration>

By – Rakesh Kumar
Example – Main
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.List;

public class Main {


public static void main(String[] args) {
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();

// Create session
Session session = factory.openSession();

By – Rakesh Kumar
Example – Main
session.beginTransaction();
List<Student> std=session.createQuery("from Student",Student.class).getResultList();
for(Student s:std)
{
System.out.println(s.getRollno()+" "+s.getName());
}
session.close();
factory.close();
}
}

By – Rakesh Kumar
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.
• Keywords like SELECT, FROM and WHERE are not case sensitive, but
properties like table and column names are case sensitive in HQL.

By – Rakesh Kumar
FROM Clause
• This clause is used when the developer want to load a complete persistent
objects into memory. Syntax

String hql = "FROM Employee";


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

By – Rakesh Kumar
SELECT Clause
• This 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. Syntax

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


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

By – Rakesh Kumar
WHERE Clause
• This clause narrow the specific objects that are returned from storage. Syntax

String hql = "FROM Employee E WHERE E.id = 10";


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

By – Rakesh Kumar
INSERT Clause
• HQL supports INSERT INTO clause only where records can be inserted from
one object to another object. Syntax

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

By – Rakesh Kumar
DELETE Clause
• This clause can be used to delete one or more objects. Syntax

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

By – Rakesh Kumar
UPDATE Clause
• This clause can be used to update one or more properties of one or more
objects. Syntax

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

By – Rakesh Kumar

You might also like