You are on page 1of 31

HIBERNATE TUTORIAL

HIBERNATE - Introduction to Hibernate

Hibernate is an open source object/relational mapping tool for Java. Hibernate lets you develop persistent classes following
common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework.

Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data
types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with
manual data handling in SQL and JDBC.

Hibernates goal is to relieve the developer from 95 percent of common data persistence related programming tasks.

Hibernate is Free Software. The LGPL license is sufficiently flexible to allow the use of Hibernate in both open source and
commercial projects (see the LicenseFAQ for details). Hibernate is available for download at http://www.hibernate.org/. This
tutorial aims to provide insight into Hibernate version 3.0RC and its usage

Some of the main features of hibernate are listed below and we have tried to explain some of them in detail later in this tutorial.
Transparent persistence without byte code processing
Transparent persistence
JavaBeans style properties are persisted
No build-time source or byte code generation / processing
Support for extensive subset of Java collections API
Collection instance management
Extensible type system
Constraint transparency
Automatic Dirty Checking
Detached object support
Object-oriented query language
Powerful object-oriented query language
Full support for polymorphic queries
New Criteria queries
Native SQL queries
Object / Relational mappings
Three different O/R mapping strategies
Multiple-objects to single-row mapping
Polymorphic associations
Bidirectional associations
Association filtering
Collections of basic types
Indexed collections
Composite Collection Elements
Lifecycle objects
Automatic primary key generation
Multiple synthetic key generation strategies
Support for application assigned identifiers
Support for composite keys
Object/Relational mapping definition
XML mapping documents
Human-readable format
XDoclet support
HDLCA (Hibernate Dual-Layer Cache Architecture)
Thread safeness
Non-blocking data access
Session level cache
Optional second-level cache
Optional query cache
Works well with others
High performance
Lazy initialization
Outer join fetching
Hibernate

High level architecture of Hibernate can be described as shown in following illustration.

Hibernate makes use of persistent objects commonly called as POJO (POJO = "Plain Old Java Object".) along with XML mapping
documents for persisting objects to the database layer. The term POJO refers to a normal Java objects that does not serve any
other special role or implement any special interfaces of any of the Java frameworks (EJB, JDBC, DAO, JDO, etc...).

Rather than utilize byte code processing or code generation, Hibernate uses runtime reflection to determine the persistent
properties of a class. The objects to be persisted are defined in a mapping document, which serves to describe the persistent
fields and associations, as well as any subclasses or proxies of the persistent object. The mapping documents are compiled at
application startup time and provide the framework with necessary information for a class. Additionally, they are used in support
operations, such as generating the database schema or creating stub Java source files.

Typical Hibernate code

sessionFactory = new Configuration().configure().buildSessionFactory();

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

Customer newCustomer = new Customer();


newCustomer.setName("New Customer");
newCustomer.setAddress("Address of New Customer");
newCustomer.setEmailId("NewCustomer@NewCustomer.com");

session.save(newCustomer);

tx.commit();

session.close();
First step is hibernate application is to retrieve Hibernate Session; Hibernate Session is the main runtime interface between a
Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate
configurations file hibernate.cfg.xml.

After specifying transaction boundaries, application can make use of persistent java objects and use session for persisting to the
databases.

HIBERNATE TUTORIAL

HIBERNATE - Features of Hibernate


Transparent persistence without byte code processing
Transparent persistence
JavaBeans style properties are persisted
No build-time source or byte code generation / processing
Support for extensive subset of Java collections API
Collection instance management
Extensible type system
Constraint transparency
Automatic Dirty Checking
Detached object support
Object-oriented query language
Powerful object-oriented query language
Full support for polymorphic queries
New Criteria queries
Native SQL queries
Object / Relational mappings
Three different O/R mapping strategies
Multiple-objects to single-row mapping
Polymorphic associations
Bidirectional associations
Association filtering
Collections of basic types
Indexed collections
Composite Collection Elements
Lifecycle objects
Automatic primary key generation
Multiple synthetic key generation strategies
Support for application assigned identifiers
Support for composite keys
Object/Relational mapping definition
XML mapping documents
Human-readable format
XDoclet support
HDLCA (Hibernate Dual-Layer Cache Architecture)
Thread safeness
Non-blocking data access
Session level cache
Optional second-level cache
Optional query cache
Works well with others
High performance
Lazy initialization
Outer join fetching
HIBERNATE TUTORIAL

HIBERNATE - Getting Started With Hibernate

Hibernate is Free Software. The LGPL license is sufficiently flexible to allow the use of Hibernate in both open source and
commercial projects (see the LicenseFAQ for details). Hibernate is available for download at http://www.hibernate.org/

We wll take up an simple java example that authenticates users based on the credentials to get started with hibernate.

HIBERNATE TUTORIAL

HIBERNATE - Getting Started With Hibernate

Preparing Database

Let’s consider a simple database schema with a singe table as APPLABSUSER.


CREATE TABLE `applabsuser` (
`USER_ID` int(11) NOT NULL default '0',
`USER_NAME` varchar(255) NOT NULL default '',
`USER_PASSWORD` varchar(255) NOT NULL default '',
`USER_FIRST_NAME` varchar(255) default NULL,
`USER_LAST_NAME` varchar(255) default NULL,
`USER_EMAIL` varchar(255) default NULL,
`USER_CREATION_DATE` date default NULL,
`USER_MODIFICATION_DATE` date default NULL,
PRIMARY KEY (`USER_ID`),
UNIQUE KEY `USER_NAME` (`USER_NAME`)
);

HIBERNATE TUTORIAL

HIBERNATE - Getting Started With Hibernate

Creating persistent java objects

Hibernate works best with the Plain Old Java Objects programming model for persistent classes.

Hibernate is not restricted in its usage of property types, all Java JDK types and primitives (like String, char and Date) can be
mapped, including classes from the Java collections framework. You can map them as values, collections of values, or
associations to other entities. The id is a special property that represents the database identifer (primary key) of that class,
Hibernate can use identifiers only internally, but we would lose some of the flexibility in our application architecture.

No special interface has to be implemented for persistent classes nor do you have to subclass from a special root persistent
class. Hibernate also doesn't require any build time processing, such as byte-code manipulation, it relies solely on Java
reflection and runtime class enhancement (through CGLIB). So, without any dependency of the POJO class on Hibernate, we can
map it to a database table.

Following code sample represents a java object structure which represents the AppLabsUser table. Generally these domain
objects contain only getters and setters methods. One can use Hibernate extension toolset to create such domain objects.

AppLabsUser.java
package org.applabs.quickstart;

import java.io.Serializable;
import java.util.Date;
import org.apache.commons.lang.builder.ToStringBuilder;

public class AppLabsUser implements Serializable {

public void setName(String name) {


/** identifier field */
private Long id;

/** persistent field */


private String userName;

/** persistent field */


private String userPassword;

/** persistent field */


private String userFirstName;

/** persistent field */


private String userLastName;

/** persistent field */


private String userEmail;

/** persistent field */


private Date userCreationDate;

/** persistent field */


private Date userModificationDate;

/** full constructor */


public Applabsuser(String userName, String userPassword, String userFirstName, String userLastName, String
userEmail, Date userCreationDate, Date userModificationDate) {
this.userName = userName;
this.userPassword = userPassword;
this.userFirstName = userFirstName;
this.userLastName = userLastName;
this.userEmail = userEmail;
this.userCreationDate = userCreationDate;
this.userModificationDate = userModificationDate;
}

/** default constructor */


public Applabsuser() {
HIBERNATE TUTORIAL

HIBERNATE - Getting Started With Hibernate

Mapping POJO with persistence layer using hibernate mapping document

Each persistent class needs to be mapped with its configuration file. Following code represents Hibernate mapping file for
AppLabsUser class.

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="org.applabs.hibernate.quickstart.AppLabsUser" table="applabsuser">

<id column="USER_ID" name="id" type="java.lang.Long">


<generator class="sequence"/>
</id>

<property column="USER_NAME" length="255" name="userName" not-null="true" type="java.lang.String"/>


<property column="USER_PASSWORD" length="255" name="userPassword" not-null="true"
type="java.lang.String"/>
<property column="USER_FIRST_NAME" length="255" name="userFirstName" type="java.lang.String"/>
<property column="USER_LAST_NAME" length="255" name="userLastName" type="java.lang.String"/>
<property column="USER_EMAIL" length="255" name="userEmail" type="java.lang.String"/>
<property column="USER_CREATION_DATE" length="10" name="userCreationDate" type="java.util.Date"/>
<property column="USER_MODIFICATION_DATE" length="10" name="userModificationDate" type="java.util.Date"/>

</class>
</hibernate-mapping>
One can also generate Hibernate mapping documents using Hibernate extension toolset. Hibernate mapping documents are
straight forward. The <class> element maps a table with corresponding class. The <id> element represents the primary key
column, and its associated attribute in the domain object. The <property> elements represent all other attributes available in
the domain object.
HIBERNATE TUTORIAL

HIBERNATE - Getting Started With Hibernate

Hibernate Configuration File

Hibernate configuration file information needed to connect to persistent layer and the linked mapping documents. You can either
specify the data source name or JDBC details that are required for hibernate to make JDBC connection to the database. The
element <mapping-resource> refers to the mapping document that contains mapping for domain object and hibernate mapping
document.

<!DOCTYPE hibernate-configuration PUBLIC


"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLMyISAMDialect</property>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/applabs</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">r00Tp@$wd</property>

<mapping resource="org/applabs/hibernate/quickstart/Applabsuser.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HIBERNATE TUTORIAL

HIBERNATE - Getting Started With Hibernate

Hibernate Configuration File

Hibernate configuration file information needed to connect to persistent layer and the linked mapping documents. You can either
specify the data source name or JDBC details that are required for hibernate to make JDBC connection to the database. The
element <mapping-resource> refers to the mapping document that contains mapping for domain object and hibernate mapping
document.
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLMyISAMDialect</property>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/applabs</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">r00Tp@$wd</property>

<mapping resource="org/applabs/hibernate/quickstart/Applabsuser.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HIBERNATE TUTORIAL

HIBERNATE - Getting Started With Hibernate

Hibernate Sample Code (Inserting new record)

Here is how you can use Hibernate in your programs. Typical Hibernate programs begin with configuration that is required for
Hibernate. Hibernate can be configured in two ways. Programmatically and Configuration file based. In Configuration file based
mode, hibernate looks for configuration file “hibernate.cfg.xml” in the claspath. Based on the resource mapping provided
hibernate creates mapping of tables and domain objects. In the programmatic configuration method, the details such as JDBC
connection details and resource mapping details etc are supplied in the program using Configuration API.

Following example shows programmatic configuration of hibernate.

Configuration config = new Configuration()


.addResource("org/applabs/hibernate/quickstart/Applabsuser.hbm.xml")
Configuration config = new Configuration()
.addClass(org.hibernate.quickstart.Applabsuser.class)
.setProperty("hibernate.dialect", "org.hibernate.dialect. MySQLMyISAMDialect")
.setProperty("hibernate.connection.driver_class", " org.gjt.mm.mysql.Driver")
. . . SessionFactory sessions = config.buildSessionFactory();
In configuration file based approach, “hibernate.cfg.xml” is placed in the classpath, Following Hibernate code can be used in this
method.
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
AppLabsUser user = new AppLabsUser();
Transaction tx = session.beginTransaction();
user.setUserCreationDate(new Date());
user.setUserEmail("user@allapplabs.com");
user.setUserFirstName("userFirstName");
user.setUserLastName("userLastName");
user.setUserName("userName-1");
user.setUserPassword("userPassword");
session.saveOrUpdate(user);
tx.commit();
session.close();

HIBERNATE - Getting Started With Hibernate

Hibernate Sample Code (Quering the database)

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();


Session session = sessionFactory.openSession();
ArrayList arrayList = null;

String SQL_STRING = "FROM AppLabsUser as users";


Query query = session.createQuery(SQL_STRING);
ArrayList list = (ArrayList)query.list();

for(int i=0; i<list.size();i++){


System.out.println(list.get(i));
}

session.close();

HIBERNATE - Hibernate O/R Mapping

This section will explain how to write the mapping documents manually. Although there are tools available to create these
mapping documents, learning how to create these documents manually helps in fine tuning and setting up advance table
mapping.
Mapping Declaration

Object/relational mappings are usually defined in XML document. The mapping language is Java-centric, meaning that
mappings are constructed around persistent class declarations, not table declarations.

Mapping Document
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.somepackage.eg">
<class name="Foo" table=”FooTable”>
<id name="id" type=”java.lang.Long”>
<generator class=”sequence”/>
</id>
</class>
</hibernate-mapping>
The above example shows a typical mapping document that contains class mapping with table.
All mapping XML document should refer to hibernate-mapping-3.0.dtd via doctype.

HIBERNATE TUTORIAL

HIBERNATE - Hibernate O/R Mapping

<class> element
The <Class> element maps the domain object with corresponding entity in the database. hibernate-mapping element
allows you to nest several persistent <class> mappings, as shown above. It is however good practice to map only a
single persistent class in one mapping file and name it after the persistent superclass, e.g. User.hbm.xml,
Group.hbm.xml.

<class
name="ClassName" (1)
table="tableName" (2)
discriminator-value="discriminator_value" (3)
mutable="true|false" (4)
schema="owner" (5)
catalog="catalog" (6)
proxy="ProxyInterface" (7)
dynamic-update="true|false" (8)
dynamic-insert="true|false" (9)
select-before-update="true|false" (10)
polymorphism="implicit|explicit" (11)
where="arbitrary sql where condition" (12)
persister="PersisterClass" (13)
batch-size="N" (14)
optimistic-lock="none|version|dirty|all" (15)
lazy="true|false" (16)
entity-name="EntityName" (17)
catalog="catalog" (18)
check="arbitrary sql check condition" (19)
rowid="rowid" (20)
subselect="SQL expression" (21)
abstract="true|false" (22)

/>

(1) name (optional): The fully qualified Java class name of the persistent class (or interface). If this attribute is
missing, it is assumed that the mapping is for a non-POJO entity.
(2) table (optional - defaults to the unqualified class name): The name of its database table.
(3) discriminator-value (optional - defaults to the class name): A value that distiguishes individual subclasses, used
for polymorphic behaviour. Acceptable values include null and not null.
(4) mutable (optional, defaults to true): Specifies that instances of the class are (not) mutable.
(5) schema (optional): Override the schema name specified by the root <hibernate-mapping> element.
(6) catalog (optional): Override the catalog name specified by the root <hibernate-mapping> element.
(7) proxy (optional): Specifies an interface to use for lazy initializing proxies. You may specify the name of the class
itself.
(8) dynamic-update (optional, defaults to false): Specifies that UPDATE SQL should be generated at runtime and
contain only those columns whose values have changed.
(9) dynamic-insert (optional, defaults to false): Specifies that INSERT SQL should be generated at runtime and
contain only the columns whose values are not null.
HIBERNATE TUTORIAL
HIBERNATE - Hibernate O/R Mapping

<id> element
The <id> element defines the mapping from that property to the primary key column. Mapped classes must declare the
primary key column of the database table. Most classes will also have a JavaBeans-style property holding the unique
identifier of an instance.

<id
name="propertyName" (1)
type="typename" (2)
column="column_name" (3)
unsaved-value="null|any|none|undefined|id_value" (4)
access="field|property|ClassName"> (5)

<generator class="generatorClass"/>
/>
(1) name (optional): The name of the identifier property.
(2) type (optional): A name that indicates the Hibernate type.
(3) column (optional - defaults to the property name): The name of the primary key column.
(4) unsaved-value (optional - defaults to a "sensible" value): An identifier property value that indicates that an
instance is newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in
a previous session.
(5) access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.

HIBERNATE - Hibernate O/R Mapping

<generator> element

The optional <generator> child element names a Java class used to generate unique identifiers for instances of the persistent
class. If any parameters are required to configure or initialize the generator instance, they are passed using the <param>
element.

<id name="id" type="long" column="cat_id">


<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">uid_table</param>
<param name="column">next_hi_value_column</param>
</generator>
</id>
All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface; some applications
may choose to provide their own specialized implementations. However, Hibernate provides a range of built-in implementations.
There are shortcut names for the built-in generators:

increment generates identifiers of type long, short or int that are unique only when no other process is inserting data into
the same table. Do not use in a cluster. .
identity supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is
of type long, short or int.
sequence uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier
is of type long, short or int
hilo uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by
default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates
identifiers that are unique only for a particular database.
seqhilo uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database
sequence.
uuid uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is
used). The UUID is encoded as a string of hexadecimal digits of length 32.
guid uses a database-generated GUID string on MS SQL Server and MySQL.
native picks identity, sequence or hilo depending upon the capabilities of the underlying database.
assigned lets the application to assign an identifier to the object before save() is called. This is the default strategy if no
<generator> element is specified.
select retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving
the primary key value
foreign uses the identifier of another associated object. Usually used in conjunction with a <one-to-one> primary key
association.

HIBERNATE - Hibernate O/R Mapping

<property> element

The <property> element declares a persistent, JavaBean style property of the class.

<property
name="propertyName" (1)
column="column_name" (2)
type="typename" (3)
update="true|false" (4)
insert="true|false" (4)
formula="arbitrary SQL expression" (5)
access="field|property|ClassName" (6)
lazy="true|false" (7)
unique="true|false" (8)
not-null="true|false" (9)
optimistic-lock="true|false" (10)
/>
All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface; some applications
may choose to provide their own specialized implementations. However, Hibernate provides a range of built-in implementations.
There are shortcut names for the built-in generators:

(1) name: the name of the property, with an initial lowercase letter.
(2) column (optional - defaults to the property name): the name of the mapped database table column. This may also be
specified by nested <column> element(s).
(3) type (optional): a name that indicates the Hibernate type.
(4) update, insert (optional - defaults to true) : specifies that the mapped columns should be included in SQL UPDATE
and/or INSERT statements. Setting both to false allows a pure "derived" property whose value is initialized from some
other property that maps to the same colum(s) or by a trigger or other application.
(5) formula (optional): an SQL expression that defines the value for a computed property. Computed properties do not have
a column mapping of their own.
(6) access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.
(7) lazy (optional - defaults to false): Specifies that this property should be fetched lazily when the instance variable is first
accessed (requires build-time bytecode instrumentation).
(8) unique (optional): Enable the DDL generation of a unique constraint for the columns. Also, allow this to be the target of
a property-ref.
(9)
not-null (optional): Enable the DDL generation of a nullability constraint for the columns.

(10) optimistic-lock (optional - defaults to true): Specifies that updates to this property do or do not require acquisition of the
optimistic lock. In other words, determines if a version increment should occur when this property is dirty.
typename could be:

• The name of a Hibernate basic type (eg. integer, string, character, date, timestamp, float, binary, serializable, object,
blob).
• The name of a Java class with a default basic type (eg. int, float, char, java.lang.String, java.util.Date, java.lang.Integer,
java.sql.Clob).
• The name of a serializable Java class.

• The class name of a custom type (eg. com.illflow.type.MyCustomType).


An especially powerful feature are derived properties. These properties are by definition read-only, the property value is
computed at load time. You declare the computation as a SQL expression, this translates to a SELECT clause subquery in the
SQL query that loads an instance:

<property name="totalPrice"
formula="( SELECT SUM (li.quantity*p.price) FROM LineItem li, Product p
WHERE li.productId = p.productId
AND li.customerId = customerId
AND li.orderNumber = orderNumber )"/>

HIBERNATE TUTORIAL

HIBERNATE - Hibernate O/R Mapping


<many-to-one> element
An ordinary association to another persistent class is declared using a many-to-one element. The relational model is a
many-to-one association: a foreign key in one table is referencing the primary key column(s) of the target table.

<many-to-one
name="propertyName" (1)
column="column_name" (2)
class="ClassName" (3)
cascade="cascade_style" (4)
fetch="join|select" (5)
update="true|false" (6)
insert="true|false" (6)
property-ref="propertyNameFromAssociatedClass" (7)
access="field|property|ClassName" (8)
unique="true|false" (9)
not-null="true|false" (10)
optimistic-lock="true|false" (11)
lazy="true|false" (12)
entity-name="EntityName"

/>

(1) name: The name of the property.


(2) column (optional): The name of the foreign key column. This may also be specified by nested <column>
element(s).
(3) class (optional - defaults to the property type determined by reflection): The name of the associated class.
(4) cascade (optional): Specifies which operations should be cascaded from the parent object to the associated
object.
(5) join (optional - defaults to select): Chooses between outer-join fetching or sequential select fetching.
(6) update, insert (optional - defaults to true) specifies that the mapped columns should be included in SQL UPDATE
and/or INSERT statements. Setting both to false allows a pure "derived" association whose value is initialized
from some other property that maps to the same colum(s) or by a trigger or other application.
(7) property-ref: (optional) The name of a property of the associated class that is joined to this foreign key. If not
specified, the primary key of the associated class is used.
(8)
access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.

(9) unique (optional): Enable the DDL generation of a unique constraint for the foreign-key column. Also, allow this
to be the target of a property-ref. This makes the association multiplicity effectively one to one.
(10)
not-null (optional): Enable the DDL generation of a nullability constraint for the foreign key columns.

(11) optimistic-lock (optional - defaults to true): Specifies that updates to this property do or do not require
acquisition of the optimistic lock. In other words, dertermines if a version increment should occur when this
property is dirty.
(12) lazy (optional - defaults to false): Specifies that this property should be fetched lazily when the instance variable
is first accessed (requires build-time bytecode instrumentation).
A typical many-to-one declaration looks as simple as this:
HIBERNATE - Hibernate O/R Mapping

<one-to-one> element

A one-to-one association to another persistent class is declared using a one-to-one element. .

<one-to-one
name="propertyName" (1) (1)
class="ClassName" (2) (2)
cascade="cascade_style" (3) (3)
constrained="true|false" (4) (4)
fetch="join|select" (5) (5)
property-ref="propertyNameFromAssociatedClass" (6) (6)
access="field|property|ClassName" (7) (7)
formula="any SQL expression" (8) (8)
entity-name="EntityName"
/>

(1) name: The name of the property.


(2) class (optional - defaults to the property type determined by reflection): The name of the associated class.
(3) cascade (optional) specifies which operations should be cascaded from the parent object to the associated object.
(4) constrained (optional) specifies that a foreign key constraint on the primary key of the mapped table references the
table of the associated class. This option affects the order in which save() and delete() are cascaded, and determines
whether the association may be proxied (it is also used by the schema export tool).
(5) fetch (optional - defaults to select): Chooses between outer-join fetching or sequential select fetching.
(6) property-ref: (optional) The name of a property of the associated class that is joined to the primary key of this class. If
not specified, the primary key of the associated class is used.
(7)
access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.

(8) formula (optional): Almost all one to one associations map to the primary key of the owning entity. In the rare case that
this is not the case, you may specify a some other column, columns or expression to join on using an SQL formula. (See
org.hibernate.test.onetooneformula for an example.)
A typical many-to-one declaration looks as simple as this:

<many-to-one name="product" class="Product" column="PRODUCT_ID"/>

HIBERNATE - Hibernate Mapping In Depth

Hibernate allows the mapping of Mapped tables with the domain objects using the persistent collection-valued fields. These
fields needs be declared as an interface type. The actual interface can be java.util.Set, java.util.Collection, java.util.List,
java.util.Map, java.util.SortedSet, java.util.SortedMap or custom implementations of org.hibernate.usertype.UserCollectionType

Collections instances have the usual behavior of value types. They are automatically persisted when referenced by a persistent
object and automatically deleted when unreferenced. If a collection is passed from one persistent object to another, its elements
might be moved from one table to another. Two entities may not share a reference to the same collection instance. Due to the
underlying relational model, collection-valued properties do not support null value semantics;

public class Product {


private String serialNumber;
private Set parts = new HashSet();
public Set getParts() { return parts; }
void setParts(Set parts) { this.parts = parts; }
public String getSerialNumber() { return serialNumber; }
void setSerialNumber(String sn) { serialNumber = sn; }
}
Collection Mapping

<map
name="propertyName" (1)
table="table_name" (2)
schema="schema_name" (3)
lazy="true|false" (4)
inverse="true|false" (5)
cascade="all|none|save-update|delete|all-delete-orphan" (6)
sort="unsorted|natural|comparatorClass" (7)
order-by="column_name asc|desc" (8)
where="arbitrary sql where condition" (9)
fetch="join|select" (10)
batch-size="N" (11)
access="field|property|ClassName" (12)
optimistic-lock="true|false" (13)
>

<key .... />


<map-key .... />
<element .... />

</map>
(1) name the collection property name
(2) table (optional - defaults to property name) the name of the collection table (not used for one-to-many associations)
(3) schema (optional) the name of a table schema to override the schema declared on the root element
(4) lazy (optional - defaults to true) enable lazy initialization (not available for arrays)
(5) inverse (optional - defaults to false) mark this collection as the "inverse" end of a bidirectional association
(6) cascade (optional - defaults to none) enable operations to cascade to child entities

(7) sort (optional) specify a sorted collection with natural sort order, or a given comparator class

order-by (optional, JDK1.4 only) specify a table column (or columns) that define the iteration order of the Map, Set or
(8)
bag, together with an optional asc or desc
where (optional) specify an arbitrary SQL WHERE condition to be used when retrieving or removing the collection (useful
(9)
if the collection should contain only a subset of the available data)
fetch (optional, defaults to select) Choose between outer-join fetching and fetching by sequential select. Only one
(10)
collection may be fetched by outer join per SQL SELECT.

(11) batch-size (optional, defaults to 1) specify a "batch size" for lazily fetching instances of this collection.

(12) access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.

optimistic-lock (optional - defaults to true): Species that changes to the state of the collection results in increment of the
(13)
owning entity's version. (For one to many associations, it is often reasonable to disable this setting.)
These are some more mapings which we will discuss later

Association Mapping
Component Mapping

HIBERNATE TUTORIAL

HIBERNATE - Hibernate Query Language


Hibernate is equipped with an extremely powerful query language that looks very much like SQL. Queries are case-
insensitive, except for names of Java classes and properties.

Clause

The from clause

The simplest possible Hibernate query is of the form:

From org.applabs.base.User
From User

which simply returns all instances of the class org.applabs.base.User.

Most of the time, you will need to assign an alias, since you will want to refer to the User in other parts of the query.

from User as user

This query assigns the alias user to User instances, so we could use that alias later in the query. The as keyword is
optional; we could also write:

from User user

Multiple classes may appear, resulting in a cartesian product or "cross" join.

from User, Group


from User as user, Group as group

The select clause

The select clause picks which objects and properties to return in the query result set. Queries may return properties of
any value type including properties of component type:

select user.name from User user


where user.name like 'mary%'

select customer.contact.firstName from Customer as cust

The where clause

The where clause allows you to narrow the list of instances returned.

from User as user where user.name='mary'


HIBERNATE - Hibernate Complete Example

In this section we will extend our quick start sample into to a web based application that comprises of struts and Hibernate
support.

Introduction
In this example we will build a simple web based document repository application using hibernate. The document repository
under consideration will have categorization of the documents based on the topics (Folder based like structure), Keywords for
each document (this will simplify searches), versioning for each document, Document modification history, permissions based
access for each entity based on users and groups.

Database scheme.
The concept of properties tables: Here we have extended the concept of Hash tables to the database, Instead of adding more
and more columns as per growing needs A properties table is created per Entity, Each property (Prop) table contains name and
value pair that stores additional information for particular entity, thus you can store as many properties as you want for a given
entity. Getter and setter methods need to be provided from the domain object so that we can represent these properties inside
domain objects.

Basic entities.
Basic entities such as User, Group, and Permissions along with Prop tables for each are provided to persistent data for
corresponding entities, Now as a business rule a group contains multiple Users and One User can be a part of multiple Groups.
Each entity, User, Group, and Permission have UserProp, GroupProp and PremissionProp respectively. The relation between
Entity and Prop is one to many. E.g. User can have multiple Properties. (For simplicity, Permission tables are not shown in the
model)

Categories and Documents


Category refers to a Folder/Directory like structure on the file system. Each category may or may not have its Parent Category.
Category contains information like name, description, creation details, modification deleted and deletion details. Each category
can have multiple entries. (Each Folder can contain one or more Documents (Entries) in it. Each Document can have one or
more versions in it.(Document corresponds to version). Document contains information such as Title, Body, Summary, life cycle
details, version number, keywords, workflow status, Entry details and Attachment details; Document also contains properties
associated with it. Attachment is a file associated with each Document, Database stores the name of file stored on the file
system and the size of Attachment.

HIBERNATE TUTORIAL

HIBERNATE - Hibernate Complete Example

Database Scripts
--Drop Tables
DROP TABLE "APP"."ATTACHMENT";
DROP TABLE "APP"."CATEGORY";
DROP TABLE "APP"."CATEGORY_PROP";
DROP TABLE "APP"."DOCUMENT";
DROP TABLE "APP"."DOCUMENT_ATTACHMENT";
DROP TABLE "APP"."DOCUMENT_KEYWORDS";
DROP TABLE "APP"."DOCUMENT_PROP";
DROP TABLE "APP"."ENTRY";
DROP TABLE "APP"."GROUP";
DROP TABLE "APP"."GROUP_PROP";
DROP TABLE "APP"."IDGENERATOR";
DROP TABLE "APP"."KEYWORD";
DROP TABLE "APP"."USER";
DROP TABLE "APP"."USER_GROUP";
DROP TABLE "APP"."USER_PROP";
-- Table: "APP"."ATTACHMENT"
CREATE TABLE "APP"."ATTACHMENT"
(
"ATTACHMENT_ID" numeric NOT NULL,
"DOCUMENT_ID" numeric,
"ATTACHMEMT_PATH" varchar,
"ATTACHMENT_SIZE" numeric,
CONSTRAINT "ATTACHMENT_pkey" PRIMARY KEY ("ATTACHMENT_ID")
);
-- Table: "APP"."CATEGORY"
CREATE TABLE "APP"."CATEGORY"
(
"CATAGORY_ID" numeric NOT NULL,
"CATEGORY_NAME" varchar,
"CATEGORY_DESCRIPTION" varchar,
"CREATED_BY" numeric,
"CREATION_DATE" date,
"MODIFIED_BY" numeric,
"MODIFICATION_DATE" date,
"DELETED_BY" numeric,
"DELETE_DATE" date,
"PARENT_CATAGORY" numeric,
CONSTRAINT "CATEGORY_pkey" PRIMARY KEY ("CATAGORY_ID"),
CONSTRAINT "CATEGORY_PARENT_CATAGORY_fkey" FOREIGN KEY ("PARENT_CATAGORY") REFERENCES
"APP"."CATEGORY" ("CATAGORY_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT authorfk FOREIGN KEY ("CREATED_BY") REFERENCES "APP"."USER" ("USER_ID") ON UPDATE NO
ACTION ON DELETE NO ACTION,
CONSTRAINT deletorfk FOREIGN KEY ("DELETED_BY") REFERENCES "APP"."USER" ("USER_ID") ON UPDATE NO
ACTION ON DELETE NO ACTION,
HIBERNATE - Hibernate Complete Example

Database Tables Overview

Click to Download Table Overview


HIBERNATE - Hibernate Complete Example

hbm files

User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.applabs.base.User" table="USER">
<id column="USER_ID" name="id" type="java.lang.Long">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">idgen</param>
<param name="column">NEXT</param>
</generator>
</id>
<property column="USER_NAME" name="userName" type="java.lang.String"/>
<property column="USER_PASSWORD" name="userPassword" type="java.lang.String"/>
<property column="USER_FIRST_NAME" name="userFirstName" type="java.lang.String"/>
<property column="USER_EMAIL" name="userEmail" type="java.lang.String"/>
<property column="USER_LAST_NAME" name="userLastName" type="java.lang.String"/>
<property column="CREATION_DATE" length="4" name="creationDate" type="java.util.Date"/>
<property column="CREATED_BY" name="createdBy" type="java.lang.Double"/>
<property column="MODIFICATION_DATE" length="4" name="modificationDate" type="java.util.Date"/>
<property column="MODIFIED_BY" name="modifiedBy" type="java.lang.Double"/>
<property column="DELETE_DATE" length="4" name="deleteDate" type="java.util.Date"/>
<property column="DELETED_BY" name="deletedBy" type="java.lang.Double"/>
<set name="properties" lazy="true" inverse="true" cascade="all-delete-orphan">
<key column="USER_ID" />
<one-to-many class="org.applabs.base.UserProp" />
</set>
</class>
</hibernate-mapping>
UserProp.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.applabs.base.UserProp" table="USER_PROP">
<id column="USER_PROP_ID" name="id" type="java.lang.Long">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">idgen</param>
<param name="column">NEXT</param>
</generator>
</id>
<property column="CATEGORY_NAME" name="categoryName" type="java.lang.String"/>
<property column="CATEGORY_DESCRIPTION" name="categoryDescription" type="java.lang.String"/>
<property column="CREATED_BY" name="createdBy" type="java.lang.Double"/>
<property column="CREATION_DATE" length="4" name="creationDate" type="java.util.Date"/>
<property column="MODIFIED_BY" name="modifiedBy" type="java.lang.Double"/>
<property column="MODIFICATION_DATE" length="4" name="modificationDate" type="java.util.Date"/>
<property column="DELETED_BY" name="deletedBy" type="java.lang.Double"/>
<property column="DELETE_DATE" length="4" name="deleteDate" type="java.util.Date"/>
<!—- One way of implementing -->
<!-- <property column="PARENT_CATAGORY" name="parentCatagory" type="java.lang.Long"/> -->
<!—- Another way of One-to-many Mapping -->
<set name="childCatagories">
<key column="CATAGORY_ID" not-null="true"/>
<one-to-many class="org.applabs.base.Category"/>
</set>
<set name="properties" lazy="true" inverse="true" cascade="all-delete-orphan">
<key column="CATEGORY_ID" />
<one-to-many class="org.applabs.base.CategoryProp" />
</set>
</class>
</hibernate-mapping>
Category.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.applabs.base.Category" table="CATEGORY">
<id column="CATAGORY_ID" name="id" type="java.lang.Long">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">idgen</param>
<param name="column">NEXT</param>
</generator>
</id>
<property column="CATEGORY_NAME" name="categoryName" type="java.lang.String"/>
<property column="CATEGORY_DESCRIPTION" name="categoryDescription" type="java.lang.String"/>
<property column="CREATED_BY" name="createdBy" type="java.lang.Double"/>
<property column="CREATION_DATE" length="4" name="creationDate" type="java.util.Date"/>
<property column="MODIFIED_BY" name="modifiedBy" type="java.lang.Double"/>
<property column="MODIFICATION_DATE" length="4" name="modificationDate" type="java.util.Date"/>
<property column="DELETED_BY" name="deletedBy" type="java.lang.Double"/>
<property column="DELETE_DATE" length="4" name="deleteDate" type="java.util.Date"/>
<!—- One way of implementing -->
<!-- <property column="PARENT_CATAGORY" name="parentCatagory" type="java.lang.Long"/> -->
<!—- Another way of One-to-many Mapping -->
<set name="childCatagories">
<key column="CATAGORY_ID" not-null="true"/>
<one-to-many class="org.applabs.base.Category"/>
</set>
<set name="properties" lazy="true" inverse="true" cascade="all-delete-orphan">
<key column="CATEGORY_ID" />
<one-to-many class="org.applabs.base.CategoryProp" />
</set>
</class>
</hibernate-mapping>
CategoryProp.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.applabs.base.CategoryProp" table="CATEGORY_PROP">
<id column="CATEGORY_PROP_ID" name="id" type="java.lang.Long">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">idgen</param>
<param name="column">NEXT</param>
</generator>
</id>
<property column="CATEGORY_ID" name="categoryId" type="java.lang.Long"/>
<property column="PROP_NAME" name="propName" type="java.lang.String"/>
<property column="PROP_VALUE" name="propValue" type="java.lang.String"/>
</set>
</class>
</hibernate-mapping>

Document.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.applabs.base.Document" table="DOCUMENT">
<id column="DOCUMENT_ID" name="id" type="java.lang.Long">
<generator class="sequence"/>
</id>
<property column="DOCUMENT_TITLE" name="documentTitle" type="java.lang.String"/>
<property column="DOCUMENT_BODY" name="documentBody" type="java.lang.String"/>
<property column="DOCUMENT_SUMMARY" name="documentSummary" type="java.lang.String"/>
<property column="CREATED_BY" length="65535" name="createdBy" type="java.lang.Double"/>
<property column="CREATION_DATE" length="4" name="creationDate" type="java.util.Date"/>
<property column="MODIFIED_BY" length="65535" name="modifiedBy" type="java.lang.Double"/>
<property column="MODIFICATION_DATE" length="4" name="modificationDate" type="java.util.Date"/>
<property column="DELETED_BY" length="65535" name="deletedBy" type="java.lang.Double"/>
<property column="DELETED_DATE" length="4" name="deletedDate" type="java.util.Date"/>
<property column="DOCUMENT_VERSION" length="65535" name="documentVersion" type="java.lang.Double"/>
<property column="DOCUMENT_STATUS" length="65535" name="documentStatus" type="java.lang.Double"/>
<property column="ENTRY_ID" length="65535" name="entryId" type="java.lang.Double"/>
</class>
</hibernate-mapping>

DocumentProp.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.applabs.base.DocumentProp" table="DOCUMENT_PROP">
<id column="document_prop_id" name="id" type="java.lang.Long">
<generator class="sequence"/>
</id>
<property column="document_id" length="65535" name="documentId" not-null="true" type="java.lang.Double"/>
<property column="prop_name" name="propName" not-null="true" type="java.lang.String"/>
<property column="prop_value" name="propValue" type="java.lang.String"/>
<property column="prop_value_details" name="propValueDetails" type="java.lang.String"/>
</class>
</hibernate-mapping>

You might also like