Hibernate Quick Start

110
异异异异异异 异异异 异异异异 () ERRY Network Technology (Shanghai) Co., Ltd. The Business Is The Component Hibernate Quick Start Justin PS

description

Hibernate Quick Start. Justin PS. Agenda. O/R Mapping Concepts Introduce example data model O/R mapping with hibernate Basic O/R Mapping Advanced O/R Mapping Hibernate Query Language (HQL) Native Query Interactive HQL execution Hibernate performance tuning - PowerPoint PPT Presentation

Transcript of Hibernate Quick Start

Page 1: Hibernate Quick Start

异联信息技术(上海)有限公司ERRY Network Technology (Shanghai) Co., Ltd.

The Business Is The Component

Hibernate Quick Start

Justin PS

Page 2: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Agenda

O/R Mapping Concepts Introduce example data model O/R mapping with hibernate

Basic O/R Mapping Advanced O/R Mapping

Hibernate Query Language (HQL) Native Query Interactive HQL execution

Hibernate performance tuning Hibernate and Junco integration Speedup Hibernate Development with Middlegen

Page 3: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Objectives

Introduce basic knowledge of: O/R ABC Basic Hibernate Hibernate Query Language (HQL) Hibernate tools

Share experience with Hibernate

Page 4: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Object-Orientation & Rational Database In most business application, object-oriented

technology is used to write application, but data are stored in rational database

Object-Orientation is good at encapsulation, reuse and adaptive to change

Rational database excels in data manipulation, sort, search, batch update & insert

Page 5: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Object-Rational Impendence Mismatch Object is described by Class, properties Database is described by table, fields Objects are related to each other by association & reference Tables are related to each other by join Object contains both data and behaviors Behaviors are provided by trigger or stored procedure

separately Object-Orientation place emphasis on fast development Rational database emphasize on efficient storage and fast

retrieval of data The object-oriented paradigm is based on proven software

engineering principles The relational paradigm, however, is based on proven

mathematical principles

Page 6: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Page 7: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Let there be a bridge… Translate the semantic in one world into another Combine both advantages

Page 8: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

What is Hibernate OSS Java object-relational mapping tools Created by Gavin King ([email protected]) JavaWorld Editor’s Choice for 2003 2003 SD magazine Jolt award Popular: increasing development community (13 000

downloads/month) Joined JBoss Group (Will be core of JBoss CMP 2.0 eng

ine) Chinese forum and website available (www.hibernate.

org.cn)

Page 9: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Before we have Hibernate Raw JDBC/SQL-J (labor-intensive, error-prone and not

portable) Standard based JDO, EJB

JDO implementations (immature) J2EE EJB2.x CMP (complex)

O/R mapping (Lightweight) Commercial solutions

TopLink CocoBase

Open source solutions Castor (not stable)

Page 10: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Features of Hibernate

Transparent persistence (POJO/JavaBeans) Three basic inheritance mapping strategies

Table per class Table per concrete class Table per hierarchy

Powerful query Projection, aggregation Sub-query, join Native query

Smart data retrieval strategies Lazy fetching Outer join fetching Session level and JVM level cache Pagination

Support versioned data

Page 11: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Features of Hibernate(cont) Third party rapid development tool support

Modeling tools/code generators AndroMDA (UML driven development) Middlegen (Data driven development)

IDE plug-ins: Eclipse, IDEA XDoclet

Optimized main-stream RDBMS support Oracle 8i,9i DB2 7.1, 7.2 MySQL 3.23 PostgreSQL 7.x Sybase12.5 MS SQL Server 2000

Page 12: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Benefits of Hibernate Improve developer’s productivity

Code can be tested without container Classes may be reused in “non-persistent” context Handy tools (Middlegen, xdoclet, Hibern8IDE) Minimize LOC

Improve application’s performance Minimize database access with smart fetching strategies Opportunities for aggressive caching Provision for proprietary SQL to enhance batch insert/update

efficiency

Page 13: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Example data model Introduction

Let’s introduce part as an example throughout this presentation

And suppose MS SQL Server 2000 is underlying database

Part has Basic info like id, code, englishName, standardCost Inventory and turnover data like pt, blevel, ifg, lead time Supply vendors Aliases Currency Inventory info kept in separate table

Page 14: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Example data model(cont)

Part procurement infos are described by PurchaseOrder and POLine

PurchaseOrder info includes: supplier, submit time, code, operator

POLine info includes: ordered part, ordered qty, purchase price, remark

See data diagram on next slide

Page 15: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Part Data Diagram

CURR_PART

PART_PA

PART_PV

VENDOR_PV

Part

IDCURR_IDCODEENGLISH_NAMELOCAL_NAMESTANDARD_COSTUSD_PRICELOCAL_PRICEIFG_MODIFY_TIMEPT_MODIFY_TIMEIS_VALIDB_LEVELLEAD_TIMEIFGPT

numeric(20)numeric(20)varchar(60)varchar(100)varchar(100)numeric(20,4)numeric(20,4)numeric(20,4)datetimedatetimeintnumeric(20)intnumeric(20,4)numeric(20)

<pk><fk>

Part Alias

IDPART_IDALIAS_NAME

numeric(20)numeric(20)varchar(30)

<pk><fk>

Part Vendor

IDVENDOR_IDPART_IDIS_DEFAULT

numeric(20)numeric(20)numeric(20)int

<pk><fk2><fk1>

Currency

IDCODERATEREGION_CODEIS_DEFAULT

numeric(20)varchar(60)numeric(20,4)varchar(60)int

<pk>

Vendor

IDCURR_IDCODENAMETYPECUSTOM_TYPEALARM_TIMELEAD_TIMEWEBSITEFREIGHT_AGENTBILL_TYPEIS_FROZENIS_USEDIS_VALID

numeric(20)numeric(20)varchar(60)varchar(30)intvarchar(30)intintvarchar(60)varchar(50)intintintint

<pk><fk>

Inventory

IDPART_IDLOC_IDWH_IDTOTAL_QTYRESERVED_QTYLOCKED_QTYSTD_COSTCHK_IN_TIME

numeric(20)numeric(20)numeric(20)numeric(20)numeric(20)numeric(20)numeric(20)numeric(20,4)datetime

<pk>

Page 16: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Purchase Order Diagram

PART_POLINE_ORDER

VENDOR_PO

PO_LINE

PurchaseOrder

I DCODETYPEIS_BIGSUPPLIER_IDOPERATORCREATE_TIMESUBMIT_TIMETOTAL_MONEYSTATUS

numeri c(20)varchar(60)intintnumeric(20)varchar(30)datetimedatetimenumeric(20,4)int

<pk><ak>

<fk>

PurchaseOrderLine

I DLINE_SEQHEAD_IDORDER_PART_IDPURCHASE_PRICEORDER_QTYREMARK

numeri c(20)varchar(20)numeric(20)numeric(20)numeric(20,4)numeric(20)varchar(500)

<pk>

<fk1><fk2>

Vendor

I DCURR_IDCODENAMETYPECUSTOM_TYPEALARM_TIMELEAD_TIMEWEBSITEFREIGHT_AGENTBILL_TYPEIS_FROZENIS_USEDIS_VALID

numeri c(20)numeric(20)varchar(60)varchar(30)intvarchar(30)intintvarchar(60)varchar(50)intintintint

<pk><fk>

Part

I DCURR_IDCODEENGLISH_NAMELOCAL_NAMESTANDARD_COSTUSD_PRICELOCAL_PRICEIFG_MODIFY_TIMEPT_MODIFY_TIMEIS_VALIDB_LEVELLEAD_TIMEIFGPT

numeri c(20)numeric(20)varchar(60)varchar(100)varchar(100)numeric(20,4)numeric(20,4)numeric(20,4)datetimedatetimeintnumeric(20)intnumeric(20,4)numeric(20)

<pk><fk>

Page 17: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

O/R mapping with Hibernate

Hibernate mapping is specified in xml (*.hbm.xml) Table is mapped to class Primary key is mapped to object identifier Columns are mapped to properties Foreign key is mapped to object reference to other cla

ss One-to-Many and Many-to-Many relations are mapped

to collection

Page 18: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Basic Mapping by example Suppose we have an entity Currency with

private Long id;private String code;private double rate;private boolean isDefault;

Here’s the mapping:

Page 19: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Basic Mapping Steps Step 1: map table to object

Specify fully qualified java class name And optionally corresponding table name

Step 2: map primary key to object identifier Specify if auto key generation is needed If so give extra info like sequence name

Step 3: map column to object’s property Specify property name property type (so-called hibernate type) And optionally corresponding column name

Repeat step 3 for the rest columns

Page 20: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Object to table mapping syntax

Page 21: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Map identifier to primary key syntax

Page 22: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Auto key generation—Generator details Supported key generation strategies:

identity: auto-increment column in database like MS SQL Server, Sybase, MySQL

sequence: sequence in database like oracle hilo: use a table and column (by default hibernate_unique_ke

y and next) to efficiently generate identifiers of type long, short or int,

UUID:A unique string or 32-hex string consists of: IP address, startup time of the JVM (accurate to a quarter second), system time, counter value (unique within the JVM).

Page 23: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Auto key generation—Generator details Supported key generation strategies:

native: use identity, hilo or sequence according to capability of underlying database

foreign: use associated object’s id, applicable to one-to-one mapping

<id name="id" type="java.lang.Long" column="ID" unsaved-value="null" > <generator class="foreign"> <param name="property">client</param> </generator> </id> <one-to-one name="client" cascade="none" class="com.erry.model.baseinfo.Client"/>

Page 24: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Example for Oracle 8i, 9i

Page 25: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Example for MS SQL Server

Page 26: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Map simple property to column syntax

Page 27: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Map simple property to column name—property name in Java class column—column name in database table type—Hibernate data type

Page 28: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Hibernate Data Type Basic value type

Numeric Type integer, long, short, float, double, character, byte, bool

ean, yes_no, true_false string Time Type

date, time, timestamp, calendar, calendar_date big_decimal

Entity—Persistent Class Customized Type

Class that implemets net.sf.hibernate.UserType or net.sf.hibernate.CompositeUserType

Page 29: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Basic Mapping another example Suppose we have an entity Vendor with

private Long id;private String code;private String name;private int type;private String customType;private int alarmTime;private int leadTime;private String website;private String freightAgent;private int billType;private boolean isFrozen;private boolean isUsed;private boolean isValid;private Currency currency;private Collection contactInfos;

Page 30: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Another example mapping xml

Here’s the mapping:

Page 31: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Advanced Mapping Relationship Mapping

One-to-Many Many-to-One Many-to-Many

Customizing the DDL

Page 32: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

M:1 Mapping Many-to-One relation links a many side entity to a

one side entity Simply think of many-to-one relation as a property

with entity data type

Page 33: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

M:1 Mapping Syntax

Page 34: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Vendor example revisited Still take Vendor for example, examine property currency:

private Long id;private String code;private String name;private int type;private String customType;private int alarmTime;private int leadTime;private String website;private String freightAgent;private int billType;private boolean isFrozen;private boolean isUsed;private boolean isValid;private Currency currency;private Collection contactInfos;

Page 35: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

M:1 example mapping xml

Here’s the mapping:

Page 36: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

1:M Mapping One-to-Many relation contains a collection of

associated entities Simply treat One-to-Many relation as a property of

collection type contains associated entities

Page 37: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

1:M Mapping Syntax

Page 38: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

1:M Mapping Java Source

private Long id;

private String code;

private String englishName;

private String localName;

private double standardCost;

private java.util.Date ifgModifyTime;

private boolean isValid;

private long blevel;

private int leadTime;

private int ifg;

private long pt;

private Currency currency;

private Collection partVendors;

private Collection partAliases;

private Collection replacements;

private Collection canReplaceParts;

Page 39: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

1:M Mapping Sample

Mapping source snippet:

Page 40: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

M:N Mapping Many-to-Many relation links a many side entity to

another many side entity Simply consider Many-to-Many relation as a

property with a collection of entity data

Page 41: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

M:N Mapping Syntax

Page 42: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

M:N Mapping Java Source

private Long id;

private String code;

private String englishName;

private String localName;

private double standardCost;

private java.util.Date ifgModifyTime;

private boolean isValid;

private long blevel;

private int leadTime;

private int ifg;

private long pt;

private Currency currency;

private Collection partVendors;

private Collection partAliases;

private Collection replacements;

private Collection canReplaceParts;

Page 43: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

M:N Mapping Sample Mapping source snippet

Page 44: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Customizing the DDL Hibernate mapping can contains information used on

ly for DDL generation tools like SchemaExport. Specify a column type by using the sql-type attribute of a <column> element.

For instance, you can define a BigDecimal type property ‘amount’ then mapping it to sql-typeNUMERIC(11,2) as following:

Page 45: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Mapping caveat Although hibernate can guess what table name,

column name and data type to use if they are omitted, Always explicitly specify table name, data type and column name!

Hibernate does check the consistency of data type specified in mapping file and the one declared in java class, Always ensure the twos are consistent to avoid some strange problems!

Since writing mapping file manually is inherently error-prone and time-consuming, Always prefer using mapping file auto-generation tools to hand-craft.

Page 46: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Hibernate Query Language Wrapper of SQL with object-oriented semantics

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 Sub-query SQL function calls

Page 47: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Hibernate Query Language(cont) Hibernate is capable of creating query from native

SQL query Advantages:

Easy to express complicated search conditions Easy to use proprietary SQL functions

Disadvantages: Make application not portable

Named Query/SQL-Query to decouple java code and query statement

Built-in pagination support for various database

Page 48: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

HQL basic construct Case-insensitive: HQL is case-insensitive, except

for names of Java classes and properties. HQL construct:

The select clause The from clause The where clause The order by clause The group by clause Associations and joins Aggregate functions Expressions

Page 49: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

HQL By Example(simplest) Problem: find all parts whose standard cost is betwee

n 10.00 & 1000.00 Solution:

select p from com.erry.model.part.Part as p where p.standardCost>=10.00 and p.standardCost<=1000.00

Page 50: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

HQL By Example(simple join) Problem: find parts by default vendor and part name Solution:

select p from com.erry.model.part.Part as p inner join p.partVendors as pv

where p.isValid=1 and pv.vendor.id=:vendorId Explanation: string precede with semicolon is HQL na

med parameter

Page 51: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Execute HQL Overview After you craft the HQL query statement, you

should execute them using Hibernate API Steps:

1. Obtain Hibernate Session2. Create Hibernate Query3. Bind Named Parameter if any4. Issue query5. Retrieve results

Page 52: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Execute HQL Typical Code Code snippet: List ret = new ArrayList(); try { Session sess = TransactionManager.getHBSession(); String ql = "select p from com.erry.model.part.Part as p " + "inner join p.partVendors as pv " + "where p.isValid=1 and pv.vendor.id=:vendorId and p.englishName=:name"; Query q = sess.createQuery(ql); q.setLong("vendorId", vendorId.longValue()); q.setString("name", name);

q.setFirstResult(begin - 1); q.setMaxResults(count);

Collection parts = new ArrayList(); Iterator it = q.iterate(); while (it.hasNext()) { parts.add(it.next()); } ret.add(parts); return ret; } catch (HibernateException e) { log.error("Data Access Layer error in findByNameAndVDEx(): ", e); throw new UnexpectedException("Data Access Layer error in findByNameAndVDEx()"); }

Page 53: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Execute HQL Bind Named Parameter Hibernate support named parameter to make query

more readable Named parameters are preceded with semicolon Use Query’s setXXX() method to bind these paramet

ers

Page 54: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Bind Named Parameter Code Snippet Code snippet: List ret = new ArrayList(); try { Session sess = TransactionManager.getHBSession(); String ql = "select p from com.erry.model.part.Part as p " + "inner join p.partVendors as pv " + "where p.isValid=1 and pv.vendor.id=:vendorId and p.englishName=:name"; Query q = sess.createQuery(ql); q.setLong("vendorId", vendorId.longValue()); q.setString("name", name);

q.setFirstResult(begin - 1); q.setMaxResults(count);

Collection parts = new ArrayList(); Iterator it = q.iterate(); while (it.hasNext()) { parts.add(it.next()); } ret.add(parts); return ret; } catch (HibernateException e) { log.error("Data Access Layer error in findByNameAndVDEx(): ", e); throw new UnexpectedException("Data Access Layer error in findByNameAndVDEx()"); }

Page 55: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Issue Query Basically you have two choices: Query.list()

Fetch object at one Need 1 SQL select Capable fill cache after loading objects Useful for object without cache

Query.iterate() Retrieve id at first time Retrieve object on demand Need n+1 SQL select Capable of utilizing cache

Page 56: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Partial Loading(page support) Partial loading or paging is a common requirement for

most application Hibernate support partial loading It automatically generates proprietary SQL statement

for different underlying database To use partial loading feature you simply call:

Query.setFirstResult() //first record begin with 0 Query.setMaxResults()

See sample code on next slide

Page 57: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Partial Loading Code Snippet Code snippet: List ret = new ArrayList(); try { Session sess = TransactionManager.getHBSession(); String ql = "select p from com.erry.model.part.Part as p " + "inner join p.partVendors as pv " + "where p.isValid=1 and pv.vendor.id=:vendorId and p.englishName=:name"; Query q = sess.createQuery(ql); q.setLong("vendorId", vendorId.longValue()); q.setString("name", name);

q.setFirstResult(begin - 1); q.setMaxResults(count);

Collection parts = new ArrayList(); Iterator it = q.iterate(); while (it.hasNext()) { parts.add(it.next()); } ret.add(parts); return ret; } catch (HibernateException e) { log.error("Data Access Layer error in findByNameAndVDEx(): ", e); throw new UnexpectedException("Data Access Layer error in findByNameAndVDEx()"); }

Page 58: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

More complex HQL Problem: find all parts whose current inventory is belo

w secure inventory(described by property blevel) Solution:

select p from com.erry.model.part.Part as p where p.isValid=1

and (not exists(select inv.id from com.erry.model.warehouse.Inventory as inv where inv.part=p) or exists(select inv.part from com.erry.model.warehouse.Inventory as inv where inv.part=p group by inv.part having sum(inv.totalQty)<p.blevel))

Explanation:This example illustrate how to use sub query and aggregate function

Page 59: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Query with native SQL Problem: we want to use proprietary SQL functions no

t supported by Hibernate but don’t want to use JDBC API directly because we still need hibernate’s partial loading, named parameter feature

Solution: Simply use Hibernate’s native query feature

Page 60: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Query with native SQL Steps Craft your complex SQL query Assign an alias to the object you want to fetch and enc

lose it into curly brace Call Query.createSQLQuery(sql, alias, objectClass) Do rest steps as normal Hibernate query

Page 61: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Query with native SQL example Problem: Find all parts whose monthly purchase

quantity exceed a given amount, paging results Solution:

Since aggregate by month is required we have to rely on MS SQL Server proprietary SQL function datepart()

Paging results is needed so direct invocation of JDBC API is unwise

So the best choice is obvious—use Hibernate’s native query

Page 62: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Query with native SQL Code Snippet Code snippet: Collection ret = new ArrayList(); try { Session sess = TransactionManager.getHBSession(); String ql = "select {p.*} from T_PI_PART p," + "(select ln.ORDER_PART_ID, sum(ln.ORDER_QTY) ORDER_QTY," + "datepart(month, h.SUBMIT_TIME) SUBMIT_TIME " + "from T_PO_PURCHASE_ORDER h " + "inner join T_PO_POLINE ln on ln.po_Id=h.id " + "group by ln.ORDER_PART_ID, datepart(month, h.SUBMIT_TIME) " + "having sum(ln.ORDER_QTY)>:qty) tt " + "where p.id=tt.ORDER_PART_ID and p.is_valid=1"; Query q = sess.createSQLQuery(ql, "p", Part.class); q.setLong("qty", qty); q.setFirstReuslt(begin -1); q.setMaxResults(count); ret.addAll(q.list()); return ret; } catch (HibernateException e) { log.error("Data Access Layer error in findMonthlyPurchareQtyOver(): ", e); throw new UnexpectedException("Data Access Layer error in findMonthlyPurchareQtyOver()"); }

Page 63: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Named Query—Make Native SQL More Portable You can move the above complex SQL statement

out of your code by using Named SQL-Query Benefits of Named Query:

Centralize complex SQL statements to ease maintenance Make change from one proprietary SQL to another much

easier

Page 64: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Named Query—Overview You can move the above complex SQL statement

out of your code by using Named SQL-Query Benefits of Named Query:

Centralize complex SQL statements to ease maintenance Make change from one proprietary SQL to another much

easier

Page 65: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Named Query Definition Example

Page 66: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Named Query Java Source Example Collection ret = new ArrayList(); try {

Session sess = TransactionManager.getHBSession();

Query q = sess.getNamedQuery("findMonthlyPurchareQtyOver");

q.setLong("qty", qty);

ret.addAll(q.list());

return ret;

}

catch (HibernateException e) {

log.error("Data Access Layer error in findMonthlyPurchareQtyOver(): ", e);

throw new UnexpectedException("Data Access Layer error in findMonthlyPurchareQtyOver()");

}

Page 67: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Debug HQL interactively Write complex HQL is error-prone, however,

inevitable sometimes A tool named Hibern8IDE can help you examine

your HQL

Page 68: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Basic Usage of Hibern8IDE Get Hibern8IDE

http://www.xam.dk/hibern8ide Write a script to run Hibern8IDE

Sample Ant script:<target name="hql" description="Run hql..."> <echo>Run HQL interactively...</echo> <java fork="yes" failonerror="yes" dir="${basedir}" classname="net.sf.hibern8ide.Hibern8IDE" description="Run HQL intera

ctively..."> <classpath refid="default_classpath"/> <classpath refid="tools.classpath"/> <arg line=""/> </java> </target>

Run Hibern8IDE Load Hibernate configuration and application mapping Write and examine your HQL query

Page 69: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Hibern8IDE Overview

Page 70: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Hibern8IDE Query UI

Page 71: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Performance Tuning Optimizing Data Access

Lazy loading to avoid unnecessary database access Outer-join fetch to decrease data access roundtrips Dynamic insert and update to eliminate unnecessary

database access Caching data

Page 72: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Lazy loading Load object from database only when necessary Enable proxy for object reference lazy-loading Declare collection lazy-loading N+1 Selects Problem (too many roundtrips)

Page 73: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Lazily-loaded Collection & Session In ThreadLocal pattern access to lazily-loaded collecti

on need to re-associate object with a new session session.lock(object, LockMode.NONE)

Page 74: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Outer-join fetch Advantage: Minimize database roundtrips Disadvantage: May cause huge result set

Page 75: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Caching Data Cache can improve overall performance dramatically Hibernate 2.1(or above) provide pluggable cache supp

ort Three OSS cache products are integrated into Hiberna

te OSCache SwarmCache JBossTreeCache

Page 76: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Use Cache in Hibernate Overview Declare cache usage in mapping file

Object cache Association cache

Configure cache

Page 77: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Class Cache Declaration Sample

Page 78: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Collection Cache Declaration Sample

Page 79: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Configure Cache Sample(OSCache)# CACHE SIZE## Default cache size in number of items. If a size is specified but not# an algorithm, the cache algorithm used will be LRUCache.#cache.capacity=1000

com.erry.model.part.Part.refresh.period = 4000com.erry.model.part.Part.cron = 30 2 * * *com.erry.model.part.Part.capacity = 5000

com.erry.model.part.PartModel.refresh.period = 4000com.erry.model.part.PartModel.cron = 30 2 * * *com.erry.model.part.PartModel.capacity = 5000

com.erry.model.part.PartVendor.refresh.period = 4000com.erry.model.part.PartVendor.cron = 30 2 * * *com.erry.model.part.PartVendor.capacity = 5000

com.erry.model.part.PartAlias.refresh.period = 4000com.erry.model.part.PartAlias.cron = 30 2 * * *com.erry.model.part.PartAlias.capacity = 5000

Page 80: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Interact with Hibernate cache

If you issue direct SQL update or delete, you should synchronize cache and database programmatically

Session level cache Session.evict()

JVM level cache Clear class cache--SessionFactory.evict () Clear collection cache--SessionFactory.evictCollection()

Role name is composed of fully qualified class name and collection field name

Page 81: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Hibernate Cache Removal Sample Clear class cache Session sess = TransactionManager.getHBSession();

sess.getSessionFactory().evict(Part.class); Clear collection cacheSession sess = TransactionManager.getHBSession();

sess.getSessionFactory().evictCollection(Part.class.getName() + ".replacements");

Page 82: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Hibernate and Junco integration Features of Hibernate Junco integration Map value object pattern SearchTerm for dynamic query ThreadLocal Hibernate Session management pattern Master-detail data type support

Page 83: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Map value object pattern A pattern which transfers data from model layer to presentation layer in map format The map may contain:

Keys defined for a given model (attribute names) Simple data type (string, numeric, boolean, date) properties o

f a given model Nested map for any entity type property

To access simple data type: To access entity data type (also called extended prope

rty)

Page 84: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Attribute Name Overview Used to access simple property in map data Used to access extended property in map data Used to construct dynamic query(Search Term)

Page 85: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Attribute Name Rules Each entity has its own attribute name class Each attribute name class defines keys for related enti

ty’s properties Each attribute name is a public final String For simple data type property the string consists of en

tity’s model name and property name (JavaBean Style), joined by underscore

Page 86: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Attribute Name rules For 1:m, m:n association, attribute name string is

preceded with ‘$’, followed by contained object’s model name, underscore and field name

For m:1, 1:1 association, an indicate is defined to access the nested map for associated object. Indicate begin with associated model’s name, followed by underscore, field name and literal ‘indicate’

For derivative properties attribute name string begin with model name, end with method name, joined by double underscore

Page 87: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Attribute Name Samplepublic interface PartAttributeNames { public final static String ID = "Part_id"; public final static String CODE = "Part_code"; public final static String ENGLISH_NAME = "Part_englishName"; public final static String LOCAL_NAME = "Part_localName"; public final static String STANDARD_COST = "Part_standardCost"; public final static String USD_PRICE = "Part_usdPrice"; public final static String LOCAL_PRICE = "Part_localPrice"; public final static String IFG_MODIFY_TIME = "Part_ifgModifyTime"; public final static String IS_VALID = "Part_isValid";

public final static String B_LEVEL = "Part_blevel"; public final static String LEAD_TIME = "Part_leadTime"; public final static String IFG = "Part_ifg"; public final static String PT = "Part_pt";

public final static String CURRENCY_ID = "Part_currencyId"; public final static String CURRENCY_INDICATE = "Currency_currencyIndicate";

public final static String $PART_VENDORS = "$PartVendor_partVendors"; public final static String $PART_ALIASES = "$PartAlias_partAliases"; public final static String $REPLACEMENTS = "$Part_replacements"; public final static String $CAN_REPLACE_PARTS = "$Part_canReplaceParts";

public final static String SUPPLIER_NAME_ = "Part__supplierName"; public final static String DEFAULT_SUPPLIER_ID_ = "Part__defaultSupplierId"; public final static String UNDER_BLEVEL_PURCHASE_QTY_ = "Part__underBLevelPurchaseQty";}

Page 88: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Access simple data type properties Determine which properties to use Figure out their corresponding keys(attribute names) Put these keys into an Collection (ArrayList typically) Invoke the model’s getAttributes() method Sample code snippet: ArrayList group = new ArrayList(); group.add(PartAttributeNames.ID); group.add(PartAttributeNames.CODE); group.add(PartAttributeNames.FORMATED_CODE_); group.add(PartAttributeNames.SUPPLIER_NAME_); group.add(PartAttributeNames.ENGLISH_NAME); group.add(PartAttributeNames.LOCAL_PRICE); group.add(PartAttributeNames.PT); group.add(PartAttributeNames.CUR_INVENTORY_QTY_); group.add(AC02AttributeNames.CODE);

Iterator it = this.home.findAllEx(1, 100).iterator(); while (it.hasNext()) { Part part = (Part) it.next(); Map map = part.getAttributes(group); System.out.println(map); }

Page 89: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Attribute Name Class Generator Attribute name rules seem to be complex and

boring , fortunately, there is a code generator to produce attribute name class on the fly

Page 90: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

SearchTerm for Dynamic Query Sometimes construct query according to user’s searc

h criteria dynamically is necessary SearchTerm serves this purpose by defining attribute

name based search criteria and combining them together

Features: Support basic comparison >>=<<=<> like, is null, is not null, in Support order by clause Support search against associated object

Limitations: Unable to express logical or relation between SearchTerms

Page 91: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Simple SearchTerm Example Problem: find all parts that is valid and has English na

me is like ‘resistor’ and ifg value over 4 Solution: see next slide

Page 92: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Simple SearchTerm Code Snippet List list = new ArrayList();

list.add(new SearchTerm(PartAttributeNames.IS_VALID, new Boolean(true), SearchTerm.EQUAL));

list.add(new SearchTerm(PartAttributeNames.ENGLISH_NAME, "resistor", SearchTerm.LIKE));

list.add(new SearchTerm(PartAttributeNames.IFG, new Integer(4), SearchTerm.GREATE_EQUAL));

List ret = this.home.findAllByCriteriaEx(list, 1, 40);

int total = ((Integer) ret.get(0)).intValue();

System.out.println("Total result is: " + total);

List records = (List) ret.get(1);

Iterator it = records.iterator();

while (it.hasNext()) {

Part o = (Part) it.next();

System.out.println(o);

}

Page 93: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Search Against Associated Object Example Problem: find all parts that is valid and has one

alias ‘super coil’ Solution: see next slide

Page 94: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Code Snippet List list = new ArrayList();

list.add(new SearchTerm(PartAttributeNames.IS_VALID, new Boolean(true), SearchTerm.EQUAL));

list.add(new AssociationSearchTerm(PartAliasAttributeNames.ALIAS_NAME,

"super coil",

SearchTerm.EQUAL,

PartAttributeNames.$PART_ALIASES));

List ret = this.home.findAllByCriteriaEx(list, 1, 40);

int total = ((Integer) ret.get(0)).intValue();

System.out.println("Total result is: " + total);

List records = (List) ret.get(1);

Iterator it = records.iterator();

while (it.hasNext()) {

Part o = (Part) it.next();

System.out.println(o);

}

Page 95: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

ThreadLocal Pattern We use ThreadLocal pattern to simplify Hibernate sess

ion management(or transaction management) All business logic are assumed that Hibernate session i

n progress Simply open Hibernate session before invoke any busi

ness operations ThreadLocal Pattern is implemented by TransactionM

anager, see code sample

Page 96: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

ThreadLocal Pattern Code Sampletry { TransactionManager.openDatabase(); ... ... ... //your business operation TransactionManager.commitDatabase();}catch (BusinessException e) { TransactionManager.rollbackDatabase(); log.error("your error message ", e);}catch (Throwable e) { TransactionManager.rollbackDatabase(); log.error("your error message ", e);}

Page 97: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Master-detail data type support Master-detail relationship is quite phenomenal in busi

ness application HeadEntity and LineEntity encapsulate common oper

ation like add line, merge and provides callback Simply extends the two class to save you from these te

dious tasks

Page 98: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Master-detail method overview

Manipulate line getLineById(Long lineId) removeLineItemById(Long lineId)

Add lines using Map data addLinesAsMap(Collection lineMaps)

Merge lines using Map data mergeLinesAsMap(Collection lineMaps)

Page 99: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Master-detail Callback Method overview

updateDerivatives()—At this time all independent properties of head-line are initialized, any derivative properties can be determined.

Automatically invoked within addLinesAsMap() ,addLines(), removeLineItemById() and mergeLinesAsMap()

Otherwise, need to call manually

Page 100: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Middlegen and Hibernate Middlegen is a general-purpose database reverse engi

neering tools A Middlegen-Hibernate plug-in allow us to generate m

apping from existing database schema

Page 101: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Harness Middlegen Install Middlegen Configure Middlegen Use Middlegen Generate java code

Page 102: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Install Middlegen Get the latest middlegen(So far middlegen-2.0-b1) Exact the tar ball or zip file into a directory Set an environment variable MIDDLE_GEN_HOME

On Unix/Linux: export MIDDLE_GEN_HOME=/opt/OSS/middlegen

On MS Windows: my computer->properties->advanced->environment variable

The above environment variables will be used in ant build file to find necessary jars and plug-ins

Page 103: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Configure Middlegen Tell Middlegen where the tables,JDBC driver reside:<property name="database.script.file" value=""/><property name="database.driver.classpath" value="${lib.dir}/msbase.jar;${lib.dir}/msuti

l.jar"/><property name="database.driver.file" value="${lib.dir}/mssqlserver.jar"/><property name="database.driver" value="com.microsoft.jdbc.sqlserver.SQLServerDriver"/><property name="database.url" value="jdbc:microsoft:sqlserver://datacenter:1433;Database

Name=psms4;SelectMethod=cursor"/><property name="database.userid" value=“jack"/><property name="database.password" value=“;-)xx"/><property name="database.schema" value=“jack"/><property name="database.catalog" value="psms4"/>

<property name="jboss.datasource.mapping" value="MS SQLSERVER2000"/>

Page 104: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Use Middlegen Determine which entities to be generated Configure middlegen-hibernate plug-in Optionally tell Middlegen many-to-many relationship t

able if any Run ant target Set properties in Swing UI

Page 105: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Ant Middlegen Script Sample <middlegen appname="${name}" prefsdir="${build.middlegen.dir}" gui="${gui}" databaseurl="${database.url}" initialContextFactory="${java.naming.factory.initial}" providerURL="${java.naming.provider.url}" datasourceJNDIName="${datasource.jndi.name}" driver="${database.driver}" username="${database.userid}" password="${database.password}" schema="${database.schema}" catalog="${database.catalog}" > <table name="T_PI_PART" singular="part" plural="parts"/> <table name="T_BI_CURRENCY" singular="currency" plural="currencies"/> <table name="T_BI_VENDOR" singular="vendor" plural="vendors"/> <table name="T_PI_PART_VENDOR" singular="partVendor" plural="partVendors"/> <table name="T_PI_PART_ALIAS" singular="partAlias" plural="partAliases"/> <table name="T_WH_INVENTORY" singular="inventory" plural="inventories"/> <many2many> <tablea name="T_PI_PART"/> <jointable name="T_PI_PART_REPLACE" /> <tableb name="T_PI_PART"/> </many2many> <hibernate destination="${build.dir}/gen-src" package="com.erry.model.part" /> </middlegen>

Page 106: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Middlegen Swing UI

Page 107: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Middlegen tricks & tips Always explicitly specify which tables to be reverse en

gineered Reverse engineer tables belongs to the same module a

t a time Always tell Middlegen the singular and plural form of y

our entities Enable proxy Enable dynamic insert and update Include most columns in toString() Specify a base class

Page 108: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Generate POJO Source From Mapping Add an Ant task Add a target to execute hibernate hbm2java

extension tool Run the ant target Modify generated source

Page 109: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Sample Ant Script for hbm2java tool <target name="gen-model-class" depends="init" description="Genera

te java source from hibernate mapping file">

<echo>Generate model class...</echo>

<java fork="yes" failonerror="yes" dir="${build.dir}"

classname="net.sf.hibernate.tool.hbm2java.CodeGenerator">

<classpath refid="hibernate.classpath"/>

<classpath refid="default_classpath"/>

<arg line="${mapping.file} --output=${build.dir}/gen-src"/>

</java>

</target>

Page 110: Hibernate Quick Start

ERRY Network Technology (Shanghai) Co., Ltd.

Reference Hibernate2 Document & FAQ Books:

Agile Database Techniques Scott W. Ambler Hibernate In Action (due in 2004)

Web resource: Object-rational Mapping theory

http://www.agiledata.org/essays/mappingObjects.html Hibernate

www.hibernate.org Hibernate Official Site www.hibernate.org.cn Hibernate Chinese Community