0% found this document useful (0 votes)
21 views25 pages

IntroductiontoHibernate V1

The document provides an overview and introduction to using Hibernate as an object-relational mapping tool. It discusses what Hibernate is, why it should be used, its basic concepts and usage including mapping objects to tables and performing CRUD operations.
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)
21 views25 pages

IntroductiontoHibernate V1

The document provides an overview and introduction to using Hibernate as an object-relational mapping tool. It discusses what Hibernate is, why it should be used, its basic concepts and usage including mapping objects to tables and performing CRUD operations.
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/ 25

Introduction to Hibernate

Overview
What is Hibernate?
• Hibernate is an object-relational mapping
tool (ORM) that allows for persisting
Java objects in a relational database
• Driven by XML configuration files to
configure data connectivity and map
classes to database tables
• Not a Java/SQL code generation
tool
– Developer writes code to call API
– API executes necessary SQL at runtime
Why Use Hibernate?
• Eliminate need for repetitive SQL
• Work with classes and objects instead
of queries and result sets
– More OO, less procedural
• Mapping approach can resist changes
in object/data model more easily
• Strong support for caching
Why Use Hibernate?
• Handles all create-read-update-delete
(CRUD) operations using simple API; no SQL
• Generates DDL scripts to create DB schema
(tables, constraints, sequences)
• Flexibility to hand-tune SQL and call stored
procedures to optimize performance
• Supports over 20 RDBMS; change the
database by tweaking configuration files
Introduction to Hiberate

The Basics
Simple Object Model
• AuctionItem • Bid
– description – amount
– type
– datetime
– successfulBid

• AuctionItem has zero or


more bids
• Auction item has zero or
one successfulBid
Plain Old Java Object (POJO)
public class AuctionItem {
• Default private Long _id;
private Set _bids;
constructor private Bid _successfulBid
private String _description;
• Identifier public Long getId() {
return _id;
}
private void setId(Long id) {
property _id = id;
}
• Get/set public String getDescription() {
return _description;

pairs }
public void
setDescription(String desc) {
• Collection _description = desc;
}
property is an } …

interface
XML Mapping File
• Readable metadata <class name=“AuctionItem”
table=“AUCTION_ITEM”>
• Column / table <id name=“id”
column=“ITEM_ID”>
mappings <generator
class=“native”/>
• Surrogate key </id>
generation strategy <property name=“description”
column=“DESCR”/>
• Collection metadata <many-to-one name=“successfulBid”

• Fetching strategies column=“SUCCESSFUL_BID_ID”/>


<set name=“bids”
cascade=“all”
lazy=“true”>
<key
column=“ITEM_
ID”/>
<one-to-many
class=“Bid”/>
Creating Objects
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

AuctionItem item = new AuctionItem();


item.setDescription(“Batman
Begins”); item.setType(“DVD”);
session.save(item);

tx.commit();
session.close();
Updating Objects
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

AuctionItem item =
(AuctionItem) session.get(ActionItem.class, itemId);
item.setDescription(newDescription);

tx.commit();
session.close();
Deleting Objects
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

AuctionItem item =
(AuctionItem) session.get(ActionItem.class, itemId);
session.delete(item);

tx.commit();
session.close();
Selecting Objects
• Hibernate Query Language (HQL), similar to SQL
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

List allAuctions = session.createQuery(“


select item
from AuctionItem item
join item.bids bid
where item.description like ‘Batman%’
and bid.amount < 15
”).list();

tx.commit();
session.close();
Introduction to Hibernate

The Details
Key Hibernate Classes
• Configuration – uses mapping and database
connection metadata to create
SessionFactory
• SessionFactory – thread-safe cache of
compiled mappings for database; created
once at application startup (expensive)
• Session – represents a “conversation”
between application and database; holds 1st
level cache of objects
• Transaction – an atomic unit of work
Configuration
hibernate.properties
hibernate.dialect =
org.hibernate.dialect.SQLServerDialect
hibernate.connection.driver_class = net.sf.jtds.Driver
hibernate.connection.url =
jdbc:sqlserver://localhost/db:1433
hibernate.connection.username = myuser
hibernate.connection.password =
mypass
• Also configurable via using XML
• Several ways to add mapping files to
configuration, including XML or API-based
SessionFactory
• Once the Configuration is prepared,
obtaining the SessionFactory is
easy:

Configuration cfg = new Configuration();


// … do some configuration …
cfg.configure();
SessionFactory sf =
cfg.buildSessionFactory();
Typical Usage Pattern
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
// … perform some operation …
tx.commit();
s.close();

• Although some additional boilerplate code is


required for proper error handling***
Hibernate Querying Options
• HQL
– Syntax similar to SQL
– Unlike SQL, HQL is still database-agnostic
• Criteria
– Java-based API for building queries
– Good for queries that are built up using lots of
conditional logic; avoids messy string manipulation
• SQL / PLSQL
– Often needed to optimize for performance or
leverage vendor-specific features
Example Queries
• Criteria API
List auctionItems =
session.createCriteria(AuctionItem.class)
.setFetchMode(“bids”,
FetchMode.EAGER)
.add( Expression.like(“description”,
description) )
.createCriteria(“successfulBid”)
.add( Expression.gt(“amount”,
• minAmount) )
.list();
Equivalent HQL:
from AuctionItem item
left join fetch item.bids
where item.description like :description
and item.successfulbid.amount >
Example Queries
• “Query by example” approach
AuctionItem item = new AuctionItem();
item.setDescription(“hib”);
Bid bid = new Bid();
bid.setAmount(1.0);
List auctionItems =
session.createCri
teria(AuctionItem
.class)
.
add( Example.cr
eate(item).enab
• leLike(MatchMod
e.START) )
.
createCriteria(
“bids”)
.
add( Ex
ample.c
reate(b
Introduction to Hibernate

More than Hibernate


Simplifying Hibernate
Boilerplate
public void deleteItem(Long itemId) throws HibernateException
{
Session session = null;
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
AuctionItem item =
(AuctionItem) session.get(ActionItem.class, itemId);
session.delete(item);
tx.commit();
catch(HibernateException ex) {
tx.rollback();
// … do something
useful, like log and
rethrow exception
} finally
{ session.close
();
}
}
Spring to the Rescue
• Spring offers a convenient HibernateSupportDao
class that offers “free” convenience methods and
exception handling
public void deleteItem(Long itemId)
throws DataAccessException
{ AuctionItem item =
(AuctionItem)
getHibernateTemplate().get(ActionItem.class,
itemId);
session.delete(item);
}
Any Questions?
Thank You!

You might also like