Sei sulla pagina 1di 44

Introduction To Hibernate

Presented by
Ryan Bohn and John Stein
Versatile, Inc.

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Agenda

• The problem with programming to relational databases


• The problem with EJB2 persistence
• What is Hibernate and how does it solve these problems?
• Where to get Hibernate
• Hibernate ORM
– Ways To Map:
• XML Mappings
• Annotations
– Types of mappings:
• basic - one-to-many / many-to-one / many-to-many/ one-to-one

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Agenda (continued)

• Hibernate basics
– The Session
– Operations:
• load, save, delete
• Hibernate queries
– HQL
– Criteria queries
– Query by example
– Native queries
• Hibernate and Transactions
• Lazy loading
• Alternatives to Hibernate
• Q&A

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Problem Programming to Relational DBs

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


What do relational DBs do well?

• Work with large amounts of data


– Searching, sorting
• Work with sets of data
– Joining, aggregating
• Sharing
– Concurrency (Transactions)
– Many applications
• Integrity
– Constraints
– Transaction isolation

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


What do relational DBs do badly?

• Modeling
– No polymorphism / inheritance
– No support for automatic conversion to objects
• Business logic
– There’s stored procedures, but:
• Very database specific
• Very coupled with the data, really belongs in the
application domain
• Transaction
– No concept of application level transactions

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Problem with EJB

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


EJB the answer?

• EJB spec tried to bridge the gap between


programming and interacting with relational
dbs
• EJB provides:
– Basic persistence (CMP)
– Method-level transaction management
– Automatic management of associations
– EJBQL provides a very basic object query language

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Problems with EJB

• Noisy Programming model


– Inheritance from javax.ejb
– Interface / Implementation required but do we really need
interfaces of our entity beans
– Complex deployment descriptors
– Weird combo of checked / unchecked exceptions
• No Polymorphism
• Can’t Test Outside Container
– For example, in JUnit
– Why not?
• Home is an interface
• Relationships/instantiation done by container

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Problems with EJB (continued)

• EJBQL too limited – none of:


– Aggregation/projection for reporting
– Outer-join fetching
– Pagination
– Dynamic queries

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


The Hibernate Solution

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


The Hibernate Solution

• Hibernate is a persistence framework aimed at


solving the shortcomings presented by EJB2.
• Persistence classes (entities) are POJOs
– Easy to write and refactor
– Can be serialized
– Can execute outside of the container (JUnit)
– Eg.
public class Book {
private Author author;
public Author getAuthor()…
public void setAuthor(….
}

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


The Hibernate Solution (cont.)

• POJO programming model


– Persistent properties are not abstract
– Can instantiate POJOS using new()
– Detached from persistence layer
• No Home Interface
– Generic Session interface is provided for persistence
operations
– May write own DAO
• No method-level transactions for entities
– Rather emphasize transactions at the business level

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


The Hibernate Solution (cont.)

• Truly object-oriented
– Polymorphic associations and queries
– Three inheritance mapping strategies

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Where to get Hibernate

• http://www.hibernate.org
– Download Jar
– Source code
– Javadoc
– Reference documentation
– Support forums
• Requirements
– JDK 1.4 or later
– Ehcache, commons logging, commons collections, asm,
dom4j, antlr, cglib

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate ORM

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate ORM

• ORM = Object Relational Mapping: way of telling


the container (Hibernate) how to map tables and
columns to entity beans
– Eg.
AUCTION_ITEM
public class AuctionItem {
private Long id;
ITEM_ID int8
private String description;
DESC varchar(100)
private Set bids;
BID }
BID_ID int8
ITEM_ID int8
AMT int4

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate ORM with XML

• Hibernate supports mappings via XML:


<class name=“AuctionItem” table=“AUCTION_ITEM”>
<id name=“id” column=“ITEM_ID”>
<generator class=“native”/>
</id>
<property name=“description” column=“DESCR”/>
<set name=“bids”
cascade=“all”
lazy=“true”>
<key column=“ITEM_ID”/>
<one-to-many class=“Bid”/>
</set>
</class>

XML is yucky!

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate ORM with EJB3 annotations

• Hibernate 3 supports ORM via annotations.


Advantages are:
– Compatible with EJB3
– Keeps mapping with the entity
– No XML sit-ups
• Disadvantage:
– Java 5 required

• So what does AuctionItem look like in the annotated


version

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate ORM with Annotations

@Entity
@Table(name = “AUCTION_ITEM”)
public class AuctionItem {
private Long id;
private String description;
private Set<Bid> bids;

@Id
@Column(name = “ITEM_ID”, nullable = false)
public Long getId() {…}

@Column(name = “DESC”, nullable = false)


public String getDescription {…}

@OneToMany(mappedBy = “item”)
public Set<Bid> getBids {…}
}

Example

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Available Annotations

• @Entity – tells Hibernate Persist Me!


• @Table – basic table info such as name
• @Id – Marks the getter as primary key, by default
uses databases native id generator (auto-increment,
sequences, etc.)
• @Column – generic information about the column
(name, allows null, length, etc.)
• @OneToOne – maps a one-to-one relationship
between 2 tables
• @OneToMany / @ManyToOne
• @ManyToMany – association table

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Available Annotations

• @Inheritence
– Three strategies
• Table per class
• Table per class hierarchy
• Joined subclass

• Many more annotations!

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Basic Persistence Operations

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Basic Persistence Operations

• All persistence operations are done through


org.hibernate.Session , which is retrieved through a
SessionFactory

• Loading an object by its id


long itemId = 500;
Session session =
sessionFactory.openSession();
AuctionItem item =
(AuctionItem) session.get(AuctionItem.class,
itemId);

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Basic Persistence Operations

• Creating a new row in the database


AuctionItem item = new AuctionItem();
item.setDescription(“Antique Chair”);
session.save(item)
• Updating a row
item.setDescription(“Old Chair”);
session.update(item); // not always
necessary
• For fun, let’s see equivalent operations in JDBC

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


JDBC get
Connection conn =
DriverManager.getConnection(…)
String sql = “SELECT * FROM auction”;
stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while (rs.next) {
Auction auction = new Auction();
auction.setName(rs.getString(“name”));
.
.
.
}

// we did not even cover getting


// the associated entities!!!
example

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Querying objects in Hibernate

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate Querying

• Hibernate several ways to query for objects


– HQL – Hibernate Query Language
– Criteria Queries
– Query by Example
– Native SQL Queries

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate Query Language

• Make SQL be object oriented


– Classes and properties instead of tables and columns
– Polymorphism
– Associations
– Much less verbose than SQL
• Full support for relational operations
– Inner/outer/full joins, cartesian products
– Projection
– Aggregation (max, avg) and grouping
– Ordering
– Subqueries
– SQL function calls

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate Query Language

Simplest HQL Query:

from AuctionItem

i.e. get all the AuctionItems:

List allAuctions = session.createQuery(“from


AuctionItem”)
.list();

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate Query Language

More realistic example:

select item
from AuctionItem item
join item.bids bid
where item.description like :desc
and bid.amount > 100

:desc is a named parameter

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate Query Language

Projection:

select item.description,
bid.amount
from AuctionItem item
join item.bids bid
where bid.amount > 100
order by bid.amount desc

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate Query Language

Aggregation:

select max(bid.amount), count(bid)


from AuctionItem item
left join item.bids bid
group by item.type
order by max(bid.amount)

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Criteria Queries

Criteria queries provide:


- way of generating queries through method calls
- suited well for dynamic queries
- extensible

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Criteria Queries

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 > :minAmount

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate Querying

• Query By Example:
AuctionItem item = new AuctionItem();
item.setDescription(“hib”);
Bid bid = new Bid();
bid.setAmount(1.0);
List auctionItems =
session.createCriteria(AuctionItem.class)

.add( Example.create(item).enableLike(MatchM
ode.START) )
.createCriteria(“bids”)
.add( Example.create(bid) )
.list();
EXAMPLE

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Transactions in Hibernate

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate Transactions
• Like other operations, transactions are performed using the Session object. Here’s an
example:

Session session = sf.openSession();


Transaction tx = session.beginTransaction();

try {
AuctionItem item =
(AuctionItem) session.get(ActionItem.class, itemId);
bid.setItem(item);
item.getBids().add(bid);
tx.commit();
} catch (Exception e) {
tx.rollback();
throw e;
} finally {
session.close();
}

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Hibernate Transactions

• Some advice - Wrap all write operations in a transaction.


Otherwise, calling a setter could automatically go back to the
database

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Lazy Loading

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Lazy Loading

• By default all one-to-many associations don’t get


fetched immediately. For example, load an
AuctionItem, but it doesn’t load bids until the first
call
• Accomplished with dynamic proxies using CGLIB
• Can change by setting fetchmode on a column
mapping
• Be wary of this if passing object to view after session
has been closed

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Alternatives to Hibernate

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Alternatives to Hibernate

• Oracle Toplink
• Ibatis
• JDO
• Many more

• EJB3 – not really, most likely Hibernate will be an


implementation of EJB3 persistence
– JBOSS does this today!

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.


Q&A

From the data center to users on the move, Versatile turns data into knowledge.

(c) Versatile Systems, Inc.

Potrebbero piacerti anche