Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
of Hibernate
Agenda
• ORM
• What is Hibernate ?
• Hibernate Architecture.
• Hibernate Installation
• Hibernate Configuration.
• Programming.
• HQL.
• Criteria
• Hibernate Object States
• Caching Techniques in Hibernate
• Advantages of Hibernate over JDBC
ORM
ORM
Object-relational mapping (ORM) is a mechanism that
makes it possible to access and manipulate objects
without having to consider how those objects relate
to their data sources.
Persistent Framework
A persistence framework is a tool for simplifying the
development and maintenance of object systems.
Hibernate is considered as a persistent framework
for Java!
So why do we need a persistence framework?
- To avoid hard coding SQL into our Java applications
What is Hibernate?
• Hibernate is an object-relational mapping (ORM)
library for the Java language, providing a framework
for mapping an object-oriented domain model to a
traditional relational database.
Persistent
Objects
(Hibernate)
Database
Hibernate Architecture(Contd..)
Hibernate - Instalation
Pre-requisites
• JDK 1.4 or above
• SQL Database and JDBC libraries
• Web/App Server (If development is Web-based)
Steps to install
1. Place the Hibernate Jar and Dependant jars in the Classpath.
2. Place the JDBC jar in the classpath
3. Configure Hibernate using Property file
4. Create Persistance Objects (Simple POJOs)
5. Create ORM Mappings in XML as per hibernates specification.
9
Hiberbate – Jars
antlr.jar
cglib.jar
asm.jar
asm-attrs.jars
commons-collections.jar
commons-logging.jar
hibernate3.jar
jta.jar
dom4j.jar
log4j.jar
10
Hibernate - Programming
Model
entity.hbm.xml
Persistence
POJO DB
Class
Hibernate-cfg.xml
11
Hibernate – POJO
POJO gets and sets values to Database filed thru Persistence class.
12
Sample POJO
public class Message {
private Long id;
private String text;
Message() {}
13
Hibernate Configuration file
Hibernate-cfg.xml is an XML file which contains configuration
information about Database driver, URL , and access credentials etc.
14
Hibernate –CFG file
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
org.hsqldb.jdbcDriver</property>
<property name="hibernate.connection.url">
jdbc:hsqldb:hsql://localhost</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">sa</property>
<property name="hibernate.dialect">
org.hibernate.dialect.SybaseDialect</property>
</mapping>
</session-factory>
15
</hibernate-configuration>
Hibernate –Mapping XML.
This XML file maps the POJO member fields in to corresponding database table
and fields.
To mange the primary key (auto increment etc) , need to specify generator
class tag.
16
Hibernate Mapping File
<hibernate-mapping>
</hibernate-mapping>
17
Hibernate – Generator Tags
Generator Tags
–Increment
–Identity
–Sequence
–Hilo
–Seqhilo
–uuid
–guid
–Native
–assigned
–Select
–foreign
18
Hibernate- Java Class
public class HibernateExample {
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
Transaction tx = session.beginTransaction();
*******************************************
session.load(AuctionItem.class, id); // SELECT
*******************************************
Multiple rows:
*******************************************
session.delete(items ); // delete from …
*******************************************
session.update(items );
*******************************************
session.saveOrUpdate(items ); To Save it in DB:
*******************************************
Transaction.commit() (OR)
Session.flush()
20
HQL
Make SQL be object oriented
• Classes and properties instead of tables and columns
• Much less verbose than SQL
21
Hibernate - HQL
select * from Salary // In Java
22
Criteria Query API
1. Criteria
2. Criterion
3. Restrictions
4. Projection
5. Order
23
Criteria - Methods
Methods
• add
• addOrder ----- addOrder( Order.asc("age") )
• createAlias ---- .createAlias(“Books", “notes")
• createCriteria ---- .createCriteria(“studentmarks")
• setFetchSize
• setFirstResult
• setMaxResults
• uniqueResult
24
Criteria – Applying Restrictions
Criteria Query:
Criteria crit = session.createCriteria(SavingsAccount.class);
crit.add(Expression.between(“BalanceAmount", new Integer(1000),
new Integer(2500))); //
Between condition
crit.setMaxResults(5); //
Restricts the max rows to 5
SavingsAccount saveAcns = crit.list();
for(Iterator it = saveAcns.iterator();it.hasNext();){
SavingsAccount sa = (SavingsAccount) it.next();
System.out.println("ID: " + sa.getSavingsId());
System.out.println("Name: " + sa.getAccHolderName());
Equivalent HQL:
Query query = session.createQuery
(from SavingsAccount sa where sa.balanceAmount between new
Integer(1000) and new Integer(2000))
25
Criteria Ordering
Criteria criteria = session.createCriteria(Student.class)
criteria.addOrder(Order.desc(“Stud_name"))
List books = criteria.list();
HQL:
26
Criteria Grouping
Criteria criteria = session.createCriteria(Student.class)
criteria.add(Projections.groupProperty(“passedOutYear"))
criteria.add(Projections.avg(“marks"))
List books = criteria.list();
SQL:
27
Criteria – Applying Restrictions
Criteria criteria = session.createCriteria(Topics.class)
criteria.add(Restrictions.or(
Restrictions.like("name", "%Hibernate%"),
Restrictions.like("name", "%Java%")
)
)
criteria.add(Restrictions.between(“credit", new Integer(100),
new Integer(200)));
List topics = criteria.list();
28
Hibernate Object States
Transient - an object is transient if it has just been instantiated
using the new operator and it is not associated with a
Hibernate Session
new Transient
Garbage Collector
save/ saveorupdate delete
load Persistent
evict, close, clear saveorupdate, lock, update
Detached
Caching Techniques in Hibernate
1) Hibernate is data base independent, same code will work for all data bases like
ORACLE,MySQL ,SQLServer etc.
In case of JDBC query must be data base specific.
3) Don't need Query tuning in case of Hibernate. If you use Criteria Quires in
Hibernate then hibernate automatically tuned your query and return best result
with performance.
In case of JDBC you need to tune your queries.
4) You will get benefit of Cache. Hibernate support two level of cache. First level
and 2nd level. So you can store your data into Cache for better performance.
In case of JDBC you need to implement your java cache .
Advantages of Hibernate over JDBC(Contd..)
7) In the xml file you can see all the relations between tables in
case of Hibernate. Easy readability.
35
References
http://www.hibernate.org/hib_docs/annotations/reference/en/html
_single/
http://www.java2s.com/Code/Java/Hibernate/CascadeSaveOrUpdat
e.htm
http://www.devarticles.com/c/a/Java/Hibernate-Criteria-Queries-
in-Depth/1/
36
ANY Questions ?
Thank You