You are on page 1of 10

Presentation Overview

Introduction to Hibernate 2.0


• Hibernate overview
• Building an application
• Other useful stuff
Steve Peterson
• Hibernate vs. JDO
Acorn Bay Software, Inc. • Wrap up
http://www.acornbay.com
http://www.acornbay.com

http://www.acornbay.com

About Steve Peterson Facts about Hibernate


• System architect, designer, and project manager • Java object-relational mapping tool
• 23 years experience in software development • One step up from direct JDBC access
• Client list includes: • Not based on a standard
– Macromedia
– 3M • Only OSS Data Access tool selected as
– NASA JavaWorld Editor’s Choice for 2003
– Solectron • Popular

http://www.acornbay.com http://www.acornbay.com

1
Technologies in the “objects
RDBMS support
to database” space
• Standardized API Tested with:
• DB2 7.1, 7.2;


Mckoi SQL 0.93
Progress 9
– JDO implementations • MySQL 3.23; • Pointbase Embedded 4.3
– J2EE CMP • PostgreSQL 7.1.2, 7.2, 7.3; • SAP DB 7.3
• Oracle 8i, 9i;
– OJB • Sybase 12.5 (JConnect
(JConnect 5.5); Thought to be compatible with
• Proprietary API • Interbase 6.0.1 (Open Source)
with Firebird InterClient 2.01;
the latest versions of:
• Informix
– TopLink • HypersonicSQL 1.61, 1.7.0; • Ingres
– CocoBase O/R • Microsoft SQL Server 2000; • FrontBase
– Hibernate

http://www.acornbay.com http://www.acornbay.com

Creating your persistent


Tool support
class
• XDoclet public class Customer {
private Account _account = new Account( );

• Modeling tools/code generators


private CreditCard _creditCard = new CreditCard(
CreditCard( );
private String _email = "";
// ...

– Middlegen public Customer() { }

– AndroMDA public void setAccount(Account acct) { _account = acct; }


public Account getAccount()
getAccount() { return _account; }

• IDE plug-in support: Eclipse, IDEA public void setCreditCard(CreditCard cc) { _creditCard
public CreditCard getCreditCard()
_creditCard = cc; }
getCreditCard() { return _creditCard
_creditCard;
; }

public void setEmail(String email) { _email = email; }


public String getEmail()
getEmail() { return _email; }

// and so on

http://www.acornbay.com http://www.acornbay.com

2
Rules for your class Creating the mapping file
• Must have Bean-
Bean-style getXXX()
getXXX() and setXXX()
setXXX() • Defining a class
• Must have default constructor
– <class>
• Not final
• Identifier recommended (not required) – <id>
– any primitive type – <generator>
– any primitive wrapper
– <property>
– String
– Date • Defining relationships
– user-
user-defined class (good for existing tables with
composite keys) • Tools support

http://www.acornbay.com http://www.acornbay.com

<class> <id>
<class name=“name.of.class
name=“name.of.class”
” can be an interface <class name=“xpetstore.domain.Customer
name=“xpetstore.domain.Customer”” table=“T_CUSTOMER”>
table=“name_of_table
table=“name_of_table”
” default: class name <id name="userId
name="userId"
" length="10">
schema=“database_schema
schema=“database_schema”” default: none <generator class="assigned“ />
proxy=“name.of.proxy.class
proxy=“name.of.proxy.class”” default: no proxy i/f </id>
discrimator-
discrimator-value=“val
value=“val”
” default: class name </class>
mutable=“true”
polymorphism=“implicit”
dynamic-
dynamic-update=“false”
dynamic-
dynamic-insert=“false” Additional <id> attributes:
persister=“
persister=“PersisterClass
PersisterClass”>
”>
type=“typename
type=“typename”

...
column=“column_name
column=“column_name”

unsaved-
unsaved-value=“something” options: any, none, null, value
</class>

http://www.acornbay.com http://www.acornbay.com

3
<generator> options <property>
<class name=“xpetstore.domain.Customer
name=“xpetstore.domain.Customer”” table=“T_CUSTOMER”>
<id name="userId
name="userId"
" length="10">
Class Description Types
<generator class="assigned“ />
vm Intra-
Intra-VM identifier long, short, int </id>
identity DB-
DB-supported identity column long, short, int <property name=“email” length=“100” not-
not-null=“false”
unique=“false”/>
sequence DB-
DB-supported sequence long, short, int ...
hilo Database-
Database-unique values long, short, int </class>
seqhilo hi/lo using sequences long, short, int
uuid.hex 128 bit UUID algorithm incorporating IP 32 digit hex string
address Additional <property> attributes:
uuid.string same 16 character ASCII string
type=“typename
type=“typename”

native Varies best of identity, sequence, or
column=“column_name
column=“column_name”

hilo,
hilo, based on database
update=“true”
capabilities
insert=“true”
assigned Application assigned Any supported type
foreign Uses identifier of associated object, for one-
one-to-
to- Any supported type
one associations
http://www.acornbay.com http://www.acornbay.com

<property> types Creating the mapping file


• Java primitives & wrappers • Defining a class ;
• string
• date, time, timestamp
• Defining relationships
• calendar, calendar_date – <one-
<one-to-
to-one>
• big_decimal – <one-
<one-to-
to-many>
• locale, timezone,
timezone, currency (maps to VARCHAR) – <many-
<many-to-
to-many>
• class (maps to name) – <collection>
• binary (byte array)
– <map>
• serializable
• clob,
clob, blob • Tools support
http://www.acornbay.com http://www.acornbay.com

4
One-to-one mapping One-to-many mapping
Java usage:
Java usage:
Set myBars = Foo.getBars();
Foo.getBars();
Bar myBar = Foo.getBar();
Foo.getBar();
Mapping file:
Mapping file:
<class name=“Foo
name=“Foo”>
”>
<class name=“Foo
name=“Foo”>
”> ...
... <set role=“bars” table=“bar” inverse=“true” lazy=“true”>
<one-
<one-to-
to-one name=“bar” class=“Bar” /> <key column-
column-”foo_id”
foo_id” />
</class> <one-
<one-to-
to-many class=“Bar”>
</set>
Schema: </class>

Schema:
Foo Bar
id id Foo Bar
id Id foo_id
http://www.acornbay.com http://www.acornbay.com

Many-to-many mapping Collection


Java usage: Java usage:

Set myBars = Foo.getBars();


Foo.getBars(); Set myPeople = Foo.getPeople();
Foo.getPeople();

Mapping file: Mapping file:

<class name=“Foo
name=“Foo”>
”> <class name=“Foo
name=“Foo”>
”>
... ...
<set role=“bars” table=“Foo_Bar
table=“Foo_Bar”>
”> <set role=“people” table=“Person”>
<key column=”foo_id
column=”foo_id”
” /> <key column=”foo_id
column=”foo_id”
” />
<many-
<many-to-
to-many column=“bar_id
column=“bar_id”
” class=“Bar”> <element column=“name” type=“string”>
</set> </set>
</class> </class>

Schema: Schema:

Bar Foo Foo_Bar Foo Person


id id foo_id bar_id id foo_id name
http://www.acornbay.com http://www.acornbay.com

5
Map Creating the mapping file
Java usage:
• Defining a class ;
• Defining relationships ;
Map myAges = Foo.getAges();
Foo.getAges();

Mapping file:

<class name=“Foo
name=“Foo”>
”> • Tools support
...
<map role=“ages” table=“Ages”>
<key column=”id” />
<index column=“name” type=“string” />
<element column=“age” type=“string”>
</map>
</class>

Schema:
Foo Ages
id foo_id name age
http://www.acornbay.com http://www.acornbay.com

Mapping file tools support hibernate.properties file


# example hibernate.properties

# put me in the root of the classpath


# or do Configuration.setProperties(startupProperties)
Configuration.setProperties(startupProperties)
# or set System properties using –Dproperty-
Dproperty-value

# Example configuration for Oracle

hibernate.dialect net.sf.hibernate.dialect.OracleDialect
hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
hibernate.connection.username SCOTT
hibernate.connection.password TIGER
hibernate.connection.url jdbc:oracle:thin:@localhost:1521:test

hibernate.show_sql false

http://www.acornbay.com http://www.acornbay.com

6
Manipulating objects Initialization

• Initialization
// Loading the configuration
// Looks for mapping files in same classpath location as class

• Creating/loading objects Configuration cfg = new Configuration()


.addClass(eg.Vertex.class)
addClass(eg.Vertex.class)
.addClass(eg.Edge.class);
addClass(eg.Edge.class);

• Updating/deleting objects // This binds you to a database configuration

• Updating stale objects


SessionFactory sessions = cfg.buildSessionFactory();
cfg.buildSessionFactory();

// obtain a JDBC connection and instantiate a new Session

• Filtering results Session sess = sessions.openSession();


sessions.openSession();

• Other query features // start a new transaction (optional)


Transaction tx = sess.beginTransaction();
sess.beginTransaction();

http://www.acornbay.com http://www.acornbay.com

Creating and loading Updating and deleting


objects objects
// Creating an object // Updating object saved/loaded in current session

Customer customer = new Customer(); Customer customer = (Customer) sess.load(Customer.class,


sess.load(Customer.class, id);
customer.setAccount(new Account()); customer.setEmail(“abc@123.com”);
customer.setEmail(“speterson@acornbay.com”);
customer.setEmail(“speterson@acornbay.com”); sess.flush();
sess.flush();
// ...
Long id = (Long) sess.save(customer);
sess.save(customer); // Deleting an object

// Later sess.delete(customer);
sess.delete(customer);
// Loading an object
// Deleting many objects
// If we know the ID
Customer customer = (Customer) sess.load(Customer.class,
sess.load(Customer.class, id); sess.delete(“from customer as Customer where amount_purchased < ?”,
new Double(10.0),
// Querying Hibernate.DOUBLE);
Hibernate.DOUBLE);
List customers = sess.find(
sess.find(
“from Customer as customer where customer.email = ?”,
email,
Hibernate.STRING);
Hibernate.STRING);

http://www.acornbay.com http://www.acornbay.com

7
Updating stale objects Filtering results
// Updating objects from a previous session // Filtering query results

// First session List customers = sess.find(


sess.find(
Customer customer = (Customer) s1.load(Customer.class, id); “from Customer as customer where account_balance > ?”,
Account newAccount = new Account(); new Double(10.0),
s1.save(newAccount); Hibernate.DOUBLE);
Hibernate.DOUBLE);

// Somewhere else in the application after s1 is defunct // Give me them in customer.name order
customer.setAccount(newAccount);
customer.setAccount(newAccount); List sortedUsers = sess.filter(customers,
sess.filter(customers, “order by this.name”);
this.name”);

// Second session // Give me only those who owe more than 100.00
s2.update(customer); List lotsDueFromThem = sess.filter(customers,
sess.filter(customers,
s2.update(newAccount); “where this.account_balance > 100”);

// Iteration over query results

Iterator it = sess.iterate(“from Customer customer order by “


+ “ customer.account_balance”);
customer.account_balance”);

http://www.acornbay.com http://www.acornbay.com

Queries Other useful stuff


• Table joins expressed as property paths • Extension points
• Support for SQL aggregate functions sum, avg,
avg,
min, max, count • Interfaces
• Support for left|right outer join, full join • Performance
• Support for group by, having and order by
• Support for subqueries (on databases with • Hibernate vs JDO
subselects)
subselects)
• Queries may return tuples of objects or scalar
values
• Batch delete

http://www.acornbay.com http://www.acornbay.com

8
Extension points Other useful interfaces

• Transaction definition • Persistent object lifecycle callbacks


• RDBMS support • Validatable
• Database connection management • Interceptor
• Primary key generation • Metadata API

http://www.acornbay.com http://www.acornbay.com

Managing performance Hibernate vs. JDO

• < 10% slower than straight JDBC in nearly Hibernate JDO


all cases • Single “vendor” • JCP Standard
• More expressive QL • Commercial (but viable
• Options for managing performance • Open source OSS approaching)
– Lazy initialization (proxies) • Uses standard build • Modified class files (extra
– Caching process compile step)
• Support for nonrelational
data stores
• Mapping not standard

http://www.acornbay.com http://www.acornbay.com

9
HQL vs JDOQL Wrap up

JDO: • Demo applications


Query query = pm.newQuery(pm.getExtent(GameObject.class, false)); – xPetstore - http://xpetstore.sourceforge.net
Query.setFilter(“age > ageParam”);
Query.declareParameters(“int ageParam”); – Struts-
Struts-resume -
Collection oldGameObjects = (Collection)
q.execute(newInteger(25)); http://static.raibledesigns.com/downloads
– Struts-
Struts-hibernate - http://struts.sourceforge.net
Hibernate:
List oldObjects =
sess.find("from
("from GameObjects go where go.age > ?", • Where to find out more
age, Hibernate.INTEGER);
Hibernate.INTEGER);
// Note: Hibernate supports JDO-
JDO-style queries too – Type “hibernate” into Google

http://www.acornbay.com http://www.acornbay.com

Presentation Sources

• Hibernate Reference Manual


– http://hibernate.bluemars.net/5.html
• Tom Sedge – Hibernate Association Styles
– http://www.xylax.net
http://www.xylax.net/hibernate
/hibernate

http://www.acornbay.com

10

You might also like