0% found this document useful (0 votes)
146 views87 pages

Presented By: Digital Book

The document discusses Java beans, POJOs, and the Data Access Object (DAO) pattern. It defines POJOs as plain old Java objects that are used to transfer data between layers. The DAO pattern abstracts data access to encapsulate database access and handle different data sources. Implementations of the DAO interface can provide different ways to store and retrieve data from sources like a database, LDAP, or CORBA. The DAO hides data source details from client code.

Uploaded by

cheswaraprasad
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
146 views87 pages

Presented By: Digital Book

The document discusses Java beans, POJOs, and the Data Access Object (DAO) pattern. It defines POJOs as plain old Java objects that are used to transfer data between layers. The DAO pattern abstracts data access to encapsulate database access and handle different data sources. Implementations of the DAO interface can provide different ways to store and retrieve data from sources like a database, LDAP, or CORBA. The DAO hides data source details from client code.

Uploaded by

cheswaraprasad
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

www.activenetdindia.

com Digital Book

Presented by

Lead a colorful life

1
www.activenetdindia.com Digital Book

Gavin King
Inventor of Hibernate
Distribution given from
sourceforge.net
Working at JBoss on EJB 3.0

Gavin is the founder of the


Hibernate project, the leading
persistence solution for Java.
He is an active member of the
JSR-220 expert group, and
contributed heavily to the design
of EJB 3.0. With Christian
Bauer, he was author of
Hibernate in Action. Gavin
works for JBoss, Inc, leading the
development of Hibernate,
implementing EJB 3.0, and
providing services to JBoss
customers.

Rod Johnson
Inventor of Spring
CEO of Interface 21

Rod Johnson is the author of the best-selling "Expert One-on-


One J2EE Design and Development" and "J2EE without EJB,"
and the founder of the Spring Framework. He is on the Servlet
2.4 and JDO 2.0 Expert Groups. Rod has been working with Java
and J2EE since their release, consulting in the media, insurance
and financial industries. He is CEO of Interface21, an
international company providing expert Spring Framework and

Craig McClanahan
Inventor of Struts
Licensing from Apache
Working at Sun

Craig is a Senior Staff Engineer for Sun Microsystems, Inc. He is currently


architect for Sun Java Studio Creator, an IDE focused on visual development
of web applications. Previously, he was co-specification lead for Java Server
Faces 1.0 (JSR-127). In the open source arena, Craig was the original author
of the Struts Framework, as well as Shale -- a next generation framework
built on top of Java Server Faces.

2
www.activenetdindia.com Digital Book

Scott W Ambler
Inventor of Agile Modeling
Founder of AmbySoft
Scott is an industry-recognized software process improvement (SPI) expert. He is the practice
leader of the Agile Modeling (AM), Agile Data (AD), Agile Unified Process (AUP), and
Enterprise Unified Process (EUP) methodologies. Scott is the (co-)author of several books,
including Refactoring Databases (Prentice Hall), Agile Modeling (John Wiley & Sons), Agile
Database Techniques (John Wiley & Sons), The Object Primer 3 rd Edition (Cambridge
University Press), and The Enterprise Unified Process (Prentice Hall ). Scott is a contributing
editor with Software Development magazine.
Own Software methodologies

Java Bean/POJO/VO/TO
studID
studName
•Must be declared as public Address
mobile

•Must be designated with Package declaration, otherwise it cannot be accessed outside the package
•To have persistence nature to the objects of a class, derive class from Serializable interface orderID

•Protect/Encapsulate the data by declaring member variables of the class as private


orderDate
custID
totalAmt
•Exposing the state via by providing one pair of setXXX() and getXXX() function for each variable
•equals(), toString() and hashCode() functions are optional empNo

•application
Use POJO for holding the domain object state and moving from one layer to another layer of the
architecture such as MVC, Broker etc
ename
sal
desig

Java Bean/POJO/VO/TO
•How POJO is different from Java Bean
•Before this we should know why POJO got lot of popularity in the market
•Since from J2EE/EJB development onwards It became like every java developer feel that
interface/class is derived from some interface such as java.rmi.Remote/javax.ejb.EJBHome/
javax.ejb.EJBObject

• In contrast to above said interfaces, the java class which is directly derived from java.io.Serializable
interface is more generic one, which can be both used on the same VM as well as across VM also

•To differentiate remote class from a normal class, normal Java Bean class are called as POJOs

3
www.activenetdindia.com Digital Book

Normal JDBC program


Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con=DriverManager.getConnection(“jdbc:odbc:mysqlDSN”, “root”, “active”);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(“SELECT * FROM emp”);
while(rs.next())
{
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2)); Emp
System.out.println(rs.getString(3)); empno, ename, desig, sal
System.out.println(rs.getDouble(4));
}
1
rs.close(); 2
stmt.close(); 3
con. close();

DAO sample
interface EmpDAO class Emp implements Serializable
{ {
Emp getEmployee(int empNo); private int emoNo;
Collection getEmployees(); private String ename, desig;
Collection getEmployeesByDesig(String private double sal;
desig); public Emp(){}
Collection getEmployeesBySal(double sal); public void setEmpNo(int eno) Emp
void insertEmp(Emp emp); {empNo=eno;} empno, ename, desig, sal
void updateEmp(Emp emp); public int getEmpNo(){return empNo;} 1
void deleteEmp(int empNo); } 2
} 3

class EmpMySQLDAOImpl

class EmpEJBDAOImpl

class EmpLDAPDAOImpl

class EmpXLSDAOImpl

class EmpIIOPDAOImpl

4
www.activenetdindia.com Digital Book

DAO
Use a Data Access Object (DAO) to abstract and encapsulate all access to the data source. The DAO manages the
connection with the data source to obtain and store data.

The DAO implements the access mechanism required to work with the data source. The data source could be a
persistent store like an RDBMS, an external service like a B2B exchange, a repository like an LDAP database, or a
business service accessed via CORBA Internet Inter-ORB Protocol (IIOP) or low-level sockets. The business
component that relies on the DAO uses the simpler interface exposed by the DAO for its clients. The DAO
completely hides the data source implementation details from its clients. Because the interface exposed by the DAO
to clients does not change when the underlying data source implementation changes, this pattern allows the DAO to
adapt to different storage schemes without affecting its clients or business components. Essentially, the DAO acts as
an adapter between the component and the data source.

DAO

DAO

5
www.activenetdindia.com Digital Book

DAO
Business object
is a Servlet/EJB/standalone/Applet program

DAO
which hides how to access different data sources to access the data
interface EmpDAO, class EmpMySQLDAOImpl, class EmpEJBDAOImpl, EmpLDAPDAOImpl,
EmpCORABDAOImpl, EmpXLSDAOImpl

DataSource is from where we access database - DB/EJB/Speardsheet/LDAP/CORBA

Transfer Object
POJO (Plain Old JavaBean Object) is called Transfer Object in which the data retrieved from various
datasources are stored and moved in different layers of the application architecture
Emp
Transfer Object
Servlet (VO/POJO)
create/use
create/use Emp
empno, ename, desig, sal
1
Standalone 2
3

Applet DAO Implementation


classes for
various data sources

JSP

EJB
DAO
CORBA

6
www.activenetdindia.com Digital Book

Limitation with DAO to act as a full fledged model component

Model component must have following capabilities


•Support to all CRUD operations
•TX capable (ACID properties – both local & distributed TX management)
•PK generation capability (UUID, User defined, Vendor supplied,
Sequence, Stored procedure etc)
Relationship between entity objects/domain model objects at application
level Secondary cache / in-memory-cache to prevent accessing the data
oftenly from the database

•Framework’s native QL for retrieve data from various data sources


Any model component which born with all the above said features can be called as a
ORM component

Short for object-relation mapping / object-relation model, a conceptual database design


methodology that allows the user to express information as an object and explore how it relates
to other information objects.
– source: webopedia.com
Object-Relational mapping (or O/RM), is a programming technique that links
databases to object-oriented language concepts, creating (in effect) a "virtual
object database."
-en.wikipedia.com

Simple ORM diagram Source: Object Primer 3rd Edition


More complex ORM diagram

7
www.activenetdindia.com Digital Book

ORM Contd..
Object-relational mapping is the process of transforming between object and relational modeling
approaches and between the systems that support those approaches. Doing a good job at object-
relational mapping requires a solid understanding of object modeling and relational modeling, how they
are similar, and how they are different.

Object = Relational
=

ORM Contd..
Object-relational mapping is the process of transforming between object and relational modeling
approaches and between the systems that support those approaches. Doing a good job at object-
relational mapping requires a solid understanding of object modeling and relational modeling, how they
are similar, and how they are different.

Object == Relational
modeling == modeling

8
www.activenetdindia.com Digital Book

ORM Contd.. Object modeling terminology


Basic concepts:
Identity
Objects have identity, which distinguishes them from all other objects. This is the crucial step for
describing how objects are different from ADTs. When an object is created it is distinguishable from all
other objects whether its state (or "value") happens to be equal

State
Because an object can be distinguished independently of its "value", it has a state: the current value
associated with this identity. Objects can have a single state through their whole life (which would
make them degenerately like ADTs) or can go through many state transitions. Because objects are
encapsulated, the state is an abstraction and is only visible by examining the behavior of the object.

ADT: Abstract Data Type

Object modeling terminology


ORM Contd..
Behavior
Objects provide an abstraction that clients can interact with. The behavior of an object is the collection
of provided interactions (called methods or operations and, collectively, an interface) and the response
to these method calls (or "messages"). All interactions with an object must be through its interface and
all knowledge about an object is from its behavior (returned values or side effects) to the interface
interaction.

Encapsulation
Encapsulation provides an abstraction and prevents external parties from seeing the implementation
details for that abstraction. For objects, clients can interact with the public behavior of the object (and
by so doing identify the state of an object) but they can not see how the behavior and the state are
implemented.

Object modeling terminology


ORM Contd..
Higher-level Concepts
Type
A type is the specification of an interface that objects will support. An object implements a (is a) type if it
provides the interface described by the type. All object of the same type can be interacted with through
the same interface. An object can implement multiple types at the same time.

Associations
Types can be associated with other types, which specifies that the objects of one type can be linked to
objects of the other type. Having a link provides the ability to traverse from one object to the other
objects involved in the link.

9
www.activenetdindia.com Digital Book

ORM Contd..
Object modeling terminology
Class
One approach for implementing objects is to have a class, which defines the implementation for multiple
objects. A class defines what types the objects will implement, how to perform the behavior required for
the interface and how to remember state information. Each object will then only need to remember its
individual state. Although using classes is by far the most common object approach, it is not the only
approach (using prototypes is another approach) and is really peripheral to the core concepts of object-
oriented modeling.

Inheritance
Inheritance can apply to types or to classes. When applied to types, inheritance specifies that object of
‘Type B’ that inherits from ‘Type A’ can be used just like an object of ‘Type A’. Type B is said to conform to
Type A and all objects that are Type Bs are also Type As.
When applied to Classes, inheritance specifies that a class uses the implementation of another class with
possible overriding modification. This frequently implies type inheritance also but that is not always the
case.

ORM Contd..
Relation
Relational modeling terminology
A relation is a truth predicate. It defines what attributes are involved in the predicate and what the
meaning of the predicate is. Frequently the meaning of the relation is not represented explicitly, but this
is a very significant source for human error in using the database system. An example of a relation is:
Person: {SSN#, Name, City} There exists a person with social security number SSN#, who has the
name Name, and lives in a city named City.

Attribute
An attribute identifies a name that participates in the relation and specifies the domain from which
values of the attribute must come. In the above relation, Name is an attribute defined over the String
domain. The above relation should explicitly identify the domains for each attribute:
Person: {SSN# : SSN, Name : String, City : CityName} There exists a person with social security
number SSN#, who has the name Name, and lives in a city named City.

ORM Contd..
Relational modeling terminology
Domain
A domain is simply a data type. It specifies a data abstraction: the possible values for the data and the
operations available on the data. For example, a String can have zero or more characters in it, and has
operations for comparing strings, concatenating string, and creating strings.

Tuple
A tuple is a truth statement in the context of a relation. A tuple has attribute values which match the
required attributes in the relation and that state the condition that is known to be true. An example of a
tuple is:
<Person SSN# = "123-45-6789" Name = "Art Larsson" City = "San Francisco">
Tuples are values and two tuples are identical if their relation and attribute values are equal. The
ordering of attribute values is immaterial.

10
www.activenetdindia.com Digital Book

ORM Contd..
Relational modeling terminology
Attribute Value
An attribute value is the value for an attribute in a particular tuple. An attribute value must come from the
domain that the attribute specifies.

Relation Value
A relation value is composed of a relation (the heading) and a set of tuples (the body). All the tuples must
have the same relation as the heading and, because they are in a set, the tuples are unordered and have
no duplicates. A relation value could be shown as a set of tuples:
{ <Person SSN# = "123-45-6789" Name = "Art Larsson" City = "San Francisco">,

<Person SSN# = "231-45-6789" Name = "Lino Buchanan" City = "Philadelphia">,

<Person SSN# = "321-45-6789" Name = "Diego Jablonski" City = "Chicago"> }

ORM Contd..
Relation Variable
Relational modeling terminology
A relation variable holds onto a single relation value at any point in time, but can change value at any
point in time. Relation variables are typed to a particular relation, so they will always hold relation values
that have a heading with that relation. A relation variable would look like:
People : Person

This shows the variable name "People" and the variable relation type "Person".

Using the tabular structure from above, we can show a relation variable and its current value.

People : Person
City SSN# Name
Philadelphia 231-45-6789 Lino BuchananSan
Francisco 123-45-6789 Art Larrson
Chicago 321-45-6789 Diego Jablonski

ORM Contd..
Relational modeling terminology
Database
A database is a collection of relation variables. It describes the complete state of an
information model, can change state (by changing the relation variables), and can answer
questions about its particular state.

Derived Relation Values


Derived relation values are calculated from other relation values known to the database. For our
example data, the number of people located in each city is:
: PersonCount
City Count
Philadelphia 1
San Francisco 1
Chicago 1

Which can be derived from the information in the "People" relation variable. Derived relation values
are most commonly the result of relational expressions and queries. They are also frequently
permanently remembered (and recalculated) through views: derived relation variables.

11
www.activenetdindia.com Digital Book

ORM Contd..
Relational modeling terminology
Coupling between relations, variables, and values
Relations, variables, and values are more coupled than they may first appear to be. Because
a relation includes a meaning, a relation variable must have the same meaning as the
relation. So defining a variable "HappyPeople : Person" does not make sense because the
predicate for ‘Person’ does not describe happiness. What we are really saying is we have a
new relation ‘HappyPerson’ which is almost identical to person but has a slightly extended
meaning:

HappyPerson: {SSN#, Name, City} There exists a person with social security number SSN#, who has
the name Name, and lives in a city named City, and that person is happy.

or using a more concise definition

HappyPerson extends Person: And that person is happy.

ORM Contd..
Relational modeling terminology
Common Relational
table relation variable
row tuple
column attribute
column value attribute value
database database

ORM Contd..
Variations in ORM implementation
1 Pure Relational Use relational database model in the client and the server. The client UI is organized
around rows and tables and uses the standard relational operations to tables and rows.

2 Light Object Mapping Have some use of objects on the client and try to isolate most of the application
code from the specifics of SQL. Convert rows from the database into basic objects on the client.
Encapsulate hard-coded SQL calls within certain classes/methods so most of the application does not
have to be coupled to them.

3 Medium Object Mapping Primarily use objects on the client and write the entire application behavior in
terms of these objects. Application may have to manage transactions of these objects. Flexibly convert
rows from the database into the appropriate type of objects and maintain identity for these objects.
Manage associations between objects of variable types. Allow retrieval queries to be specified in object
model terms and then converted to the needed SQL calls. Also allow simple identity based retrieval
queries to be answered locally (without the database hit).

ORM Contd..
Variations in ORM implementation
4 Full Object Mapping Completely use objects in the application code. As above but allow very
general class data storage formats (for inheritance and composition), manage replicate vs. server state
differences, allow queries to be completely executed locally when possible, combine multiple simple
object queries into a single, larger database queries.

5 Object Server Server itself also uses objects to organize both the information and behavior, so
retrievals and updates can be completely specified in terms of the object model and then executed on
either the server or client as appropriate (for processing power vs. data movement).

12
www.activenetdindia.com Digital Book

ORM Contd..
Source from:
Variations in ORM implementation
Booch 94 Grady Booch. Object-Oriented Analysis and Design with Applications. Benjamin/Cummings, Redwood City,
CA, 1994.

Codd 90 E.F. Codd. The Relational Model for Database Management, Version 2. Addison-Wesley, Reading, MA, 1990

Date 95 C.J. Date. An Introduction to Database Systems. Addison-Wesley, Reading, MA, 1995.

Date 95b C.J. Date. Relational Database Writings 1991- 1994. Addison-Wesley, Reading, MA, 1995.

Rumbaugh+BPEL 91 James Rumbaugh, Michael Blaha, William Premerlani, Frederick Eddy, and William Lorenson.
Object-Oriented Modeling and Design. Prentice-Hall, Englewood Cliffs, NJ, 1991.

Stonebraker+M 96 Michael Stonebraker with Dorothy Moore. Object-Relational DBMSs, The Next Great Wave.
Morgan Kauffman, San Francisco, CA, 1996.

Short Hibernate is an open source object-relation mapping ORM tool for Java. Hibernate
lets you develop persistent classes following common Java idiom - including
Introdution 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 Features
•Transparent persistence
Transparent
•JavaBeans style properties are persisted
persistence without
byte code processing •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

13
www.activenetdindia.com Digital Book

Hibernate Features

Object-oriented
query language •Powerful object-oriented query language
•Full support for polymorphic queries
•New Criteria queries
•Native SQL queries
Hibernate Features
•Three different O/R mapping strategies
Object / Relational •Multiple-objects to single-row mapping
mappings •Polymorphic associations
•Bidirectional associations
•Association filtering
•Collections of basic types
•Indexed collections
•Composite Collection Elements
•Lifecycle objects
Hibernate Features

Automatic primary
key generation
•Multiple synthetic key generation strategies
•Support for application assigned identifiers
•Support for composite keys

14
www.activenetdindia.com Digital Book

Hibernate Features

HDLCA (Hibernate
Dual-Layer Cache •Thread safeness
Architecture)
•Non-blocking data access
•Session level cache
•Optional second-level cache
•Optional query cache
•Works well with others
Hibernate Features
•Lazy initialization
•Outer join fetching
High performance •Batch fetching
•Support for optimistic locking with versioning/time-stamping
•Highly scalable architecture
•High performance
•No "special" database tables
•SQL generated at system initialization time
•(Optional) Internal connection pooling and PreparedStatement
caching

Hibernate Features

J2EE Integration
•JMX support
•Integration with J2EE architecture (optional)
•New JCA support

15
www.activenetdindia.com Digital Book

High level view of Hibernate Architecture

High level view of Hibernate Architecture

High level view of Hibernate Architecture

16
www.activenetdindia.com Digital Book

High level view of Hibernate Architecture

Hibernate Components

Transaction Query Application

Session

SessionFactory

Configuration
hibernate.cfg.xml hibernate.propertie Mapping files
s

17
www.activenetdindia.com Digital Book

Hibernate Components

hiberna hbm.x
te ml
.cfg.xml
hbm.x
ml

Hibernate Components

SessionFactory (net.sf.hibernate.SessionFactory)

A threadsafe (immutable) cache of compiled mappings for a single


database. A factory for Session and a client of ConnectionProvider.
Might hold an optional (second-level) cache of data that is reusable
between transactions, at a process- or cluster-level.

•Session s=openSession();
•Session s=openSession(con);
•evict(Class persistence class); Evict all entries from the second-level cache.
•evictQueries(); Evict any query result sets cached in the default query cache
region.
•close(); Destroy this SessionFactory and release all resources (caches,
connection pools, etc). It is the responsibility of the application to ensure that
there are no open Sessions before calling close().

18
www.activenetdindia.com Digital Book

Hibernate Components

Session (net.sf.hibernate.Session)

A single-threaded, short-lived object representing a conversation


between the application and the persistent store. Wraps a JDBC
connection. Factory for Transaction. Holds a mandatory (first-level)
cache of persistent objects, used when navigating the object graph or
looking up objects by identifier.

Transaction beginTransaction() save(Object o)


save(Object o, Serializable id)
saveOrUpdate(Object o)
update(Object o) flush() - see setFlushMode for details
update(Object o, Serializable id) setFlushMode(FlushMode mode)
AUTO, COMMIT, NEVER
Criteria createCriteria(Class Collect filter(Object collection, String filter)
persistentClass) List find(String query)
Query createFilter(Object List find(String query, Object values[], Type[] types)
collection, String queryString) List find(String query, Object value, Type type)
Query createQuery(String
queryString)

Object get(Object class, Serializable id) Iterator iterate(String query)


Object get(Object class, Serializable id, Iterator iterate(String query, Object values[],
LockMode mode) - see lock(Object, Type[] types)
LockMode) Iterator iterate(String query, Object value, Type
type)
boolean isDirty() Object load(Class theClass, Serializable id)
boolean contains(Object o) Object load(Class theClass, Serializable id,
LockMode mode)
NONE, READ, UPGRADE,
UPGRADE_NOWAIT, WRITE

refresh(Object o) clear()
lock(Object o, LockModel mode) close()
setFlushMode(FlushMode mode) connection()

19
www.activenetdindia.com Digital Book

Persistent Objects and Collections

Short-lived, single threaded objects containing persistent state and business function. These might be
ordinary JavaBeans/POJOs, the only special thing about them is that they are currently associated with
(exactly one) Session. As soon as the Session is closed, they will be detached and free to use in any
application layer (e.g. directly as data transfer objects to and from presentation).

Transient Objects and Collections

Instances of persistent classes that are not currently associated with a Session. They may have been
instantiated by the application and not (yet) persisted or they may have been instantiated by a closed
Session.

Transaction (net.sf.hibernate.Transaction)

(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work.
Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several
transactions in some cases.

ConnectionProvider (net.sf.hibernate.connection.ConnectionProvider)

(Optional) A factory for (and pool of) JDBC connections. Abstracts application from underlying
Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the
developer.

TransactionFactory (net.sf.hibernate.TransactionFactory)

(Optional) A factory for Transaction instances. Not exposed to the application, but can be
extended/implemented by the developer.
Configuration
This class instance refers to an entire set of mappings of an application’s java types to a SQL database.
The Configuration is used to build a SessionFactory. The mappings are compiled from various XML
mapping files.

Configuration c=new Configuration();


// loads hibernate.properties file from %HIB_HOME%\etc folder
followed by Bean class properties loaded explicitly as shown below

Configuration cfg = new Configuration()


.addFile("Item.hbm.xml")
.addFile("Bid.hbm.xml");
Or
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class);

If we want to send properties manually


Properties props = new Properties();
...
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class)
.setProperties(props);

JDBC Hibernate properties

20
www.activenetdindia.com Digital Book

JDBC Hibernate properties

hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">active</property>
<property name=“connection.datasource">jdbc/mysqlPool</property> <!– optional -->
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Property name Purpose

hibernate.connection.driver_class jdbc driver class


hibernate.connection.url jdbc URL
hibernate.connection.username database user
hibernate.connection.password database user password

hibernate.connection.pool_size maximum number of pooled connections

hibernate.connection.provider_class Connection pool class vendor

C3P0 properties
Connection pools are common way to improve the performance of the application. Rather than opening
a new connection for each request, the connection pool maintains a collection of open database
connections that are reused.

Hibernate supports three connection pooling services:

•C3P0
•Apache’s DBCP
•Proxool
C3P0 configuration

<property name=“hibernate.connection.provider_class”>
org.hibernate.connection.C3P0ConnectionProvider
</property>
21
<property name=“hibernate.c3p0.minPoolSize”>
5
</property>
www.activenetdindia.com Digital Book

Pooling Provider class Configuration prefix


Service
C3P0 org.hibernate.connection.C3P0ConnectionProvider c3p0

Apache org.hibernate.connection.DBCPConnectionProvider dbcp


DBCP
Proxool org.hibernate.connection.ProxoolConnectionProvider proxool

About C3P0 (pronounced as C thripio)

C3P0 is an open source JDBC connection pool distributed along with Hibernate in the lib directory.
Hibernate will use the built-in C3P0ConnectionProvider for connection pooling if you set the
hibernate.c3p0.* properties. There is also built-in support for Apache DBCP and for Proxool. (see
hibernate.properties)

C3P0
hibernate.connection.driver_ class org.postgresql.Driver
hibernate.connection.url jdbc:postgresql://localhost/mydatabase
hibernate.connection.username myuser
hibernate.connection.password secret
hibernate.c3p0.min_size 5
hibernate.c3p0.max_size 20
hibernate.c3p0.timeout 1800
hibernate.c3p0.max_statements 50
hibernate.dialect net.sf.hibernate.dialect.PostgreSQLDialect

Propery name Purpose


hibernate.connection.datasource datasource JNDI name
hibernate.jndi.url URL of the JNDI provider (optional)
hibernate.jndi.class class of the JNDI InitialContextFactory (optional)
hibernate.connection.username database user (optional)
hibernate.connection.password database user password (optional)

hibernate.connection.datasource java:/comp/env/jdbc/MyDB
hibernate.transaction.factory_class \net.sf.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class
\net.sf.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect \net.sf.hibernate.dialect.PostgreSQLDialect

Property name Purpose


hibernate.dialect The classname of a Hibernate Dialect - enables certain platform
dependent features. eg. full.classname.of.Dialect

hibernate.default_schema Qualify unqualified tablenames with the given schema/tablespace in


generated SQL. eg. SCHEMA_NAME

hibernate.session_factory_name The SessionFactory will be automatically bound to this name in JNDI


after it has been created. eg.jndi/composite/name

22
www.activenetdindia.com Digital Book

Property name Purpose


hibernate.use_outer_join Enables outer join fetching. Deprecated, use max_fetch_depth. eg.
true | false

hibernate.max_fetch_depth Set a maximum "depth" for the outer join fetch tree for single-ended
associations (one-to-one, manyto-one). A 0 disables default outer join fetching. eg. recommended values
between 0 and 3

hibernate.jdbc.fetch_size A non-zero value determines the JDBC fetch size (calls


Statement.setFetchSize()).

hibernate.jdbc.batch_size A non-zero value enables use of JDBC2 batch updates by


Hibernate. eg. recommended values between 5 and 30

Property name Purpose


hibernate.jdbc.batch_versioned_data Set this property to true if your JDBC driver
returns correct row counts from executeBatch() (it
is usually safe to turn this option on). Hibernate
will then use batched DML for automatically
versioned data. Defaults to false. eg. true | false

hibernate.jdbc.use_scrollable_resultset Enables use of JDBC 2 scrollable resultsets by


Hibernate. This property is only necessary when
using user supplied JDBC connections, Hibernate
uses connection metadata otherwise.
eg. true | false

hibernate.jdbc.use_streams_for_binary Enables use of JDBC2 scrollable


Use streams when writing/reading binary or
serializable types to/from JDBC (system-level
property). eg. true | false

Property name Purpose


hibernate.jdbc.use_get_generated_keys Enable use of JDBC3
PreparedStatement.getGeneratedKeys() to retrieve natively
generated keys after insert. Requires JDBC3+ driver and
JRE1.4+, set to false if your driver has problems with the
Hibernate identifier generators. By default, tries to
determine the driver capabilites using connection
metadata. eg. true|false

hibernate.cglib.use_reflection_optimizer Enables use of CGLIB instead of runtime reflection


(System-level property). Reflection can sometimes be
useful when troubleshooting, note that Hibernate always
requires CGLIB even if you turn off the optimizer. You can
not set this property in hibernate.cfg.xml. eg. true | false

23
www.activenetdindia.com Digital Book

Property name Purpose


hibernate.jndi.<propertyName> Pass the property propertyName to the JNDI
InitialContextFactory. hibernate.connection.isolation Set the
JDBC transaction isolation level. Check
java.sql.Connection for meaningful values but note that
most databases do not support all isolation levels. eg. 1, 2,
4, 8

hibernate.connection.<propertyName> Pass the JDBC property propertyName to


DriverManager.getConnection().

hibernate.connection.provider_class The classname of a custom ConnectionProvider.eg.


classname.of.ConnectionProvider

hibernate.cache.provider_class The classname of a custom CacheProvider. eg.


classname.of.CacheProvider

Property name Purpose


hibernate.cache.use_minimal_puts Optimize second-level cache operation to minimize writes,
at the cost of more frequent reads (useful for clustered
caches). eg. true|false

hibernate.cache.use_query_cache Enable the query cache, individual queries still have to be


set cachable. eg. true|false

hibernate.cache.query_cache_factory The classname of a custom QueryCache interface, defaults


to the built-in StandardQueryCache. eg.
classname.of.QueryCache

Property name Purpose


hibernate.cache.region_prefix A prefix to use for second-level cache region names. eg.
Prefix
hibernate.transaction.factory_class The classname of a TransactionFactory to use with
Hibernate Transaction API (defaults to
JDBCTransactionFactory). eg.
classname.of.TransactionFactory

jta.UserTransaction A JNDI name used by JTATransactionFactory to obtain the


JTA UserTransaction from the application server. eg.
jndi/composite/name

hibernate.transaction.manager_lookup_class The classname of a TransactionManagerLookup-


required when JVM-level caching is enabled in a JTA
environment. eg. classname.of.TransactionManagerLookup
Property name Purpose
hibernate.query.substitutions Mapping from tokens in Hibernate queries to SQL tokens
(tokens might be function or literal names, for example). eg.
hqlLiteral=SQL_LITERAL, hqlFunction= SQLFUNC

hibernate.show_sql Write all SQL statements to console. eg. true | false

hibernate.hbm2ddl.auto Automatically export schema DDL to the database when


the SessionFactory is created. With create-drop, the
database schema will be dropped when the
SessionFactory is closed explicitely. eg. update | create |
create-drop

24
www.activenetdindia.com Digital Book

RDBMS Dialect
DB2 net.sf.hibernate.dialect.DB2Dialect
DB2 AS/400 net.sf.hibernate.dialect.DB2400Dialect
DB2 OS390 net.sf.hibernate.dialect.DB2390Dialect
PostgreSQL net.sf.hibernate.dialect.PostgreSQLDialect
MySQL net.sf.hibernate.dialect.MySQLDialect
Oracle (any version) net.sf.hibernate.dialect.OracleDialect
Oracle 9/10g net.sf.hibernate.dialect.Oracle9Dialect
Sybase net.sf.hibernate.dialect.SybaseDialect
Sybase Anywhere net.sf.hibernate.dialect.SybaseAnywhereDialect
Microsoft SQL Server net.sf.hibernate.dialect.SQLServerDialect
SAP DB net.sf.hibernate.dialect.SAPDBDialect

Secondary Cache Provider


Why Cache?
Caching is so important in Hibernate that there isn’t a single caching mechanism; instead
Hibernate uses a multi level caching scheme. The first level cache is the Session object.

Why do we need other caches beyond the Session object?


The first is called a JVM or a SessionFactory-level class.

Hibernate delegates some caching of a specific classes and collections to this second-level
cache. The second-level cache is called as query cache.

Using this cache Hibernate can cache queries and their results in the event the application
executes the same query again. Of course, the query cache takes memory and cached queries
should have a likelihood of being executed again.

hibernate.cache.provider_class Indicates the class name of custom CacheProvider.

hibernate.cache.use_minimal_puts Optimizes second-level cache operation to minimize


writes, at the cost of more frequent reads. Possible
values are true and false.

hibernate.cache.use_query_cache Enables the query cache. The query cache is


disabled by default.

hibernate.cache.region_prefix Provides a prefix to use for second-level cache


region names.

Cache Provider Class Type Cluster Safe Query


Cache
Supported
EHCache net.sf.ehcache.hibernate.Provider Memory, disk No Yes

OSCache net.sf.hibernate. Memory, disk No Yes


cache.OSCacheProvider

25
www.activenetdindia.com Digital Book

SwarmCache net.sf.hibernate. Clustered Yes No


cache.SwarmCacheProvider (IP multicast) (clustered
invalidation)

TreeCache net.sf.hibernate. Clustered Yes No


cache.TreeCacheProvider (IP multicast (replication)
transactional)

Cache Read-only Read-write Nonstrict-read-write Transactional

EHCache Y Y Y N

OSCache Y Y Y N

SwarmCache Y Y Y N

TreeCache Y N N Y

If you are just starting out using caching the EHCache is a good choice (EH stands for Easy Hibernate).

RDBMS
hibernate.cache.provider_class
*net.sf.hibernate.cache.EhCacheProvider
net.sf.hibernate.cache.EmptyCacheProvider
net.sf.hibernate.cache.HashtableCacheProvider
*net.sf.hibernate.cache.TreeCacheProvider
*net.sf.hibernate.cache.OSCacheProvider
net.sf.hibernate.cache.JCSCacheProvider
*net.sf.hibernate.cache.SwarmCacheProvider

An Introduction to Caching

Caching is widely used for optimizing database applications. A cache is designed to reduce traffic
between your application and the database by conserving data already loaded from the database.
Database access is necessary only when retrieving data that is not currently available in the cache. The
application may need to empty (invalidate) the cache from time to time if the database is updated or
modified in some way, because it has no way of knowing whether the cache is up to date.

Hibernate Caching

Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level
cache is associated with the Session object, while second-level cache is associated with the Session
Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses
this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction.
For example, if an object is modified several times within the same transaction, Hibernate will generate
only one SQL UPDATE statement at the end of the transaction, containing all the modifications. This
article focuses on second-level cache.

26
www.activenetdindia.com Digital Book

To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level
between transactions. These objects are available to the whole application, not just to the user running
the query. This way, each time a query returns an object that is already loaded in the cache, one or more
database transactions potentially are avoided. In addition, you can use a query-level cache if you need
to cache actual query results, rather than just persistent objects.

EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write
caching, and memory- and disk-based caching. However, it does not support clustering.

OSCache is another open-source caching solution. It is part of a larger package, which also provides
caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which,
like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also
provides basic support for clustering via either JavaGroups or JMS.

SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or


non-strict read/write caching (the next section explains this term). This type of cache is appropriate for
applications that typically have many more read operations than write operations.

JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use
this solution if you really need a true transaction-capable caching architecture.

Another cache implementation worth mentioning is the commercial Tangosol Coherence cache.
Caching Strategies

Once you have chosen your cache implementation, you need to specify your access strategies. The
following four caching strategies are available:

• Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the
simplest and best-performing cache strategy.

•Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more
overhead than read-only caches. In non-JTA environments, each transaction should be completed when
Session.close() or Session.disconnect() is called.

•Non-strict read/write: This strategy does not guarantee that two transactions won'
t simultaneously
modify the same data. Therefore, it may be most appropriate for data that is read often but only
occasionally modified.

•Transactional: This is a fully transactional cache that may be used only in a JTA environment.
Cache Read-only Nonstrict Read/write Transactional
Read/write

EHCache Yes Yes Yes No

OSCache Yes Yes Yes No

SwarmCache Yes Yes No No

27
www.activenetdindia.com Digital Book

JBoss TreeCache Yes No No Yes

net.sf.hibernate.cache.EhCacheProvider
Easy Hibernate Cache is a fast and simple, pure Java, in-process cache, which acts as a pluggable
cache for Hibernate 2.1. It has a small memory footprint, minimal dependencies, and full documentation.

Scalable
The largest ehcache installations use memory and disk stores in the gigabyte range. Ehcache is tuned
for these large sizes.

Cache Configuration
To activate second-level caching, you need to define the hibernate.cache.provider_class property in the
hibernate.cfg.xml file as follows:
<hibernate-configuration>
<session-factory> ...
<property name="hibernate.cache.provider_class"> org.hibernate.cache.EHCacheProvider
</property> ...
</session-factory>
</hibernate-configuration>
Figure. The Employee UML Class Diagram The demo application uses three business classes:
Employee, Country, and Language.

<hibernate-mapping package="com.wakaleo.articles.caching.businessobjects"> <class


name="Country" table="COUNTRY" dynamic-update="true">
<meta attribute="implement-equals">true</meta>
<cache usage="read-only"/>
<id name="id" type="long" unsaved-value="null" >
<column name="cn_id" not-null="true"/>
<generator class="increment"/>
</id>
<property column="cn_code" name="code" type="string"/>
<property column="cn_name" name="name" type="string"/>
<set name="airports">
<key column="cn_id"/>
<one-to-many class="Airport"/>

28
www.activenetdindia.com Digital Book

</set>
</class>
</hibernate-mapping>

Figure. The Database Schema The demo uses a simple database design.

public class CountryDAO {


... public List getCountries() {
return SessionManager.currentSession() .createQuery( "from Country as c order by
c.name") .list();
}
public void testGetCountries() {
CountryDAO dao = new CountryDAO();
for(int i = 1; i <= 5; i++) {
Transaction tx = SessionManager.getSession().beginTransaction();
TestTimer timer = new TestTimer("testGetCountries");
List countries = dao.getCountries();
tx.commit();
SessionManager.closeSession();
timer.done();
assertNotNull(countries); assertEquals(countries.size(),229); } }
}

bean.hbm.xml

<hibernate-mapping package="com.wakaleo.articles.caching.businessobjects">
<class name="Country" table="COUNTRY" dynamic-update="true"> <meta
attribute="implement-equals">true</meta>

29
www.activenetdindia.com Digital Book

<cache usage="read-only"/> ...


</class>
</hibernate-mapping>

hibernate.cfg.xml

<hibernate-configuration>
<session-factory>
... <property name="hibernate.cache.provider_class">
org.hibernate.cache.EHCacheProvider </property> ...
<class-cache class="com.wakaleo.articles.caching.businessobjects.Country"
usage="read-only" />
</session-factory>
</hibernate-configuration>

<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />

<cache name="com.wakaleo.articles.caching.businessobjects.Country"
maxElementsInMemory="300" eternal="true" overflowToDisk="false" />
</ehcache>

There are two standard (built-in) choices:

• net.sf.hibernate.transaction.JDBCTransactionFactory delegates to database (JDBC) transactions


(default)

•net.sf.hibernate.transaction.JTATransactionFactory delegates to JTA (if an existing transaction is


underway, the Session performs its work in that context, otherwise a new transaction is started)

Transaction Factory Application


Server
net.sf.hibernate.transaction.JBossTransactionManagerLookup JBoss
net.sf.hibernate.transaction.WeblogicTransactionManagerLookup WebLogic
net.sf.hibernate.transaction.WebSphereTransactionManagerLookup WebSphere
net.sf.hibernate.transaction.OrionTransactionManagerLookup Orion
net.sf.hibernate.transaction.ResinTransactionManagerLookup Resin

30
www.activenetdindia.com Digital Book

Transaction Factory Application Server


net.sf.hibernate.transaction. JOTMTransactionManagerLookup JOTM

net.sf.hibernate.transaction. JOnASTransactionManagerLookup JOnAS

net.sf.hibernate.transaction.JRun4TransactionManagerLookup JRun4

net.sf.hibernate.transaction.BESTransactionManagerLookup Borland ES

How to install Hibernate

Web Site: http://www.hibernate.org

31
www.activenetdindia.com Digital Book

How to install Hibernate

Directory Structure explanation

32
www.activenetdindia.com Digital Book

Directory Structure explanation

Directory Structure explanation

33
www.activenetdindia.com Digital Book

Directory Structure explanation

Directory Structure explanation

34
www.activenetdindia.com Digital Book

Directory Structure explanation

Directory Structure explanation

35
www.activenetdindia.com Digital Book

Directory Structure explanation

Otherwise open MyEclipse on Eclipse 3.1 & above

And add struts capabilities to web project

36
www.activenetdindia.com Digital Book

Files required in Hibernate

hibernate.cfg.xml
<hibernate-configuration>
Contains DB driver information
or
DataSource information

One bean-hbm.xml for each POJO


</hibernate-configuration>

Bean-hbm.xml
•Each POJO is mapped
to table
•Each POJO field is
mapped to table column
•And also contains POJO
relationship with other POJOs

Files required in Hibernate

Main.java
One Java class that access
POJOs and request hibernate
framework to perform TX

Bean.java
Develop one POJO for each table

37
www.activenetdindia.com Digital Book

One sample example

One sample example

38
www.activenetdindia.com Digital Book

CLASSPATH

set
HYB_HOME=G:\Digital\RefMaterial\2005Workshops\Hibernate\Hibernate2
.1.6\hibernate-2.1

set TOMCAT_HOME=D:\Program Files\Apache Software


Foundation\Tomcat 5.0

set CLASSPATH=.\;%CLASSPATH%;%HYB_HOME%\hibernate2.jar;
%HYB_HOME%\lib\dom4j-1.4.jar;%HYB_HOME%\lib\cglib-full-2.0.2.jar;
%HYB_HOME%\lib\commons-logging-1.0.4.jar;
%TOMCAT_HOME%\common\lib\commons-collections.jar;
%TOMCAT_HOME%\common\lib\commons-dbcp-1.1.jar;
D:\Tomcat 5.0\common\lib\commons-pool-1.1.jar;
G:\Digital\Hibernate\Examples\Standalone\simple;g:\Digital\RefMaterial\20
05Workshops\Hibernate\Hibernate2.1.6\hibernate-
2.1\etc;%HYB_HOME%\lib\ehcache-0.9.jar

Have a deeper look into hibernate.cfg.xml

hibernate-configuration-2.0.dtd
<!ELEMENT hibernate-configuration (session-factory)>
<!ELEMENT session-factory (property*, mapping+,
(class-cache|collection-cache|jcs-class-cache|jcs-collection-cache)*)>
<!ATTLIST property name CDATA #REQUIRED>
<!ELEMENT mapping EMPTY>
<!ATTLIST mapping resource CDATA #IMPLIED>

<hibernate-configuration>
<session-factory>
<property name="connection.username">scott</property>
<property name="connection.url">jdbc:odbc:oracleDSN</property>
<property name="dialect">net.sf.hibernate.dialect.OracleDialect</property> Driver properties/
<property name="connection.password">tiger</property> datasource properties
<property name="connection.driver_class">sun.jdbc.odbc.JdbcOdbcDriver</property>
<!-- mapping files -->
<mapping resource="cart/Book.hbm.xml"/>
</session-factory>
</hibernate-configuration> Configure each bean-hbm.xml file here

39
www.activenetdindia.com Digital Book

hibernate-mapping-2.0.dtd
Have <!ELEMENT hibernate-mapping (class)>
a <!ELEMENT class (
id,
close discriminator?,
look (property|many-to-one|one-to-one|component|dynamic-component|any|
into map|set|list|bag|idbag|array|primitive-array)*,
((subclass*)|(joined-subclass*))
bean.hbm.x )>
ml <!ATTLIST id name CDATA #IMPLIED>
<!ATTLIST id column CDATA #IMPLIED>
<!ATTLIST id type CDATA #IMPLIED>
<!ATTLIST property name CDATA #REQUIRED>
<!ATTLIST property type CDATA #IMPLIED>
<!ATTLIST property column CDATA #IMPLIED>

<?xml version="1.0"?>
<hibernate-mapping package="cart">
<class name="Book" table="book"> POJO map to table
<id name="id" column="id" type="int"> PK field of the bean
<generator class="assigned"/> PK generation type
</id> Each POJO field map to table column
<property name="name" column="name" type="java.lang.String" />
<property name="type" column="type" type="java.lang.String" />
<property name="price" column="price" type="double" />
</class>
</hibernate-mapping>

Have
a // Book.java
close package cart;
look import java.io.*;
into public class Book implements Serializable {
Book.java private int id;
private String name, type; Encapsulate state
private double price;

public Book() {}
Expose the behavior
public void setId(int id) {this.id=id;}
public void setName(String name) {this.name=name;}
public void setType(String type) {this.type=type;}
public void setPrice(double price) {this.price=price;}

public int getId() {return id;}


public String getName() {return name;}
public String getType() {return type;}
public double getPrice() {return price;}
}

40
www.activenetdindia.com Digital Book

// BookInsertion.java
Have package cart;
a import net.sf.hibernate.*;
close import net.sf.hibernate.cfg.*;
look import java.util.*;
into public class BookInsertion
BookInsertion {
.java public static void main(String[] args) throws
Exception {
Configuration config=new Configuration(); This class load and parse
hibernate.cfg.xml file

config.configure("/hibernate.cfg.xml"); Configure shows the path of the


config file
// config.configure();
Takes config from hibernate.properties file from
classpath, usually etc directory if above one is
ignored
SessionFactory factory=config.buildSessionFactory();
Session contains config of the POJO
configured in config.xml file
Session session=.openSession(); All those objects are primary cached in
session; also called as TX cache

Transaction t=session.beginTransaction(); Begins new TX in case of


UPDATABLE operations

Have
a
close
look Book b=new Book(); POJO instantiated
into
BookInsertion b.setId(1); Populates values into POJO
.java b.setName("Practical J2EE");
b.setType("J2EE");
b.setPrice(350.00);

session.save(b); Generates id to the persistent object


session.flush(); Pushes that object into data store
t.commit(); Issues commit on the DB

System.out.println("Record inserted with the


Id.....");
session.close();
}//main()
}//class

41
www.activenetdindia.com Digital Book

O/P of
BookInsertion

Record
inserted
in the
DB

42
www.activenetdindia.com Digital Book

Have
a
close package cart;
look import net.sf.hibernate.*;
into import net.sf.hibernate.cfg.*;
BookSelection import net.sf.hibernate.expression.*;
.java import java.util.*;
public class BookSelection
{
public static void main(String[] args) throws
Exception {
Configuration config=new Configuration(); Configuration object is created

config.configure("/hibernate.cfg.xml"); Loads given config object

Session
session=config.buildSessionFactory().openSes
sion(); Loads all the bean configuration
into Session

Have
a Request SELECT operation on Book,
close that generates collection of Book bean instances
look Iterator i=session.iterate("from Book");
into
BookSelectio while(i.hasNext()) {
n Book b=(Book)i.next(); Each book instance is retrieved from iterator

.java
System.out.println(b.getId()+":"+b.getName()+":
"+
b.getType()+":"+b.getPrice()); And displaying the state
}
session.close();
}//main()
}//class

43
www.activenetdindia.com Digital Book

O/P of
BookSelection
.java

44
www.activenetdindia.com Digital Book

Can you identify each?


How really hibernate.cfg.xml bean-hbm.xml
flow is
going on
Class
which
insert/
select data

API

DB
Java Bean

Can you identify each?


How really hibernate.cfg.xml bean-hbm.xml
flow is
going on
Class
which
insert/
select data

API

DB
Java Bean

Configuration c=new Configuration();


c.configure(“/hibernate.cfg.xml”);
Loads configuration file

45
www.activenetdindia.com Digital Book

Can you identify each?


How really hibernate.cfg.xml bean-hbm.xml
flow is
going on
Class
which
insert/
select data

API

DB
Java Bean

SessionFactory factory=c.buildSessionFactory();
Session session=factory.openSession();
Loads all bean.hbm.xml files and
their mapping to DB

Can you identify each?


Book b=new Book();
How really
b.setId(1);
hibernate.cfg.xml bean-hbm.xml
flow is
b.setName(“Digital Hibernate”);
going on
Class b.setType(“Hibernate”);
which b.setPrice(350.00);
insert/
select data

API

DB
Java Bean

46
www.activenetdindia.com Digital Book

Can you identify each?


How really session.save(b);
hibernate.cfg.xml bean-hbm.xml
flow is session.flush();
going on tx.commit();
Class
which
insert/
select data

API

DB
Java
Bean

Domain
modeling
diagram

47
www.activenetdindia.com Digital Book

Hibernate O/R Mapping

Hibernate hibernate-mapping> element


O/R
Mapping The root element of hibernate mapping document is <hibernate-mapping>
element. This element has several optional attributes. The schema and catalog
attributes specify that tables referred to in this mapping belong to the named
schema and/or catalog. If specified, tablenames will be qualified by the given
schema and catalog names. If missing, tablenames will be unqualified. The
default-cascade attribute specifies what cascade style should be assumed for
properties and Collections which do not specify a cascade attribute. The auto-
import attribute lets us use unqualified class names in the query language, by
default.

<hibernate-mapping
schema="schemaName"
catalog="catalogName"
default-cascade="cascade_style"
default-access="field|property|ClassName"
default-lazy="true|false"
auto-import="true|false"
package="package.name"
/>

(1)schema (optional): The name of a database schema.


(2)catalog (optional): The name of a database catalog.
(3)default-cascade (optional - defaults to none): A default cascade style.
(4)default-access (optional - defaults to property): The strategy Hibernate should use for
accessing all properties. Can be a custom implementation of PropertyAccessor.
(5)default-lazy (optional - defaults to true): The default value for unspecifed lazy attributes of
class and collection mappings.
(6)auto-import (optional - defaults to true): Specifies whether we can use unqualified class
names (of classes in this mapping) in the query language.
package (optional): Specifies a package prefix to assume for unqualified class names in the
mapping document.

<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"
table="tableName"
discriminator-value="discriminator_value"
mutable="true|false"
schema="owner"
catalog="catalog"
proxy="ProxyInterface"
dynamic-update="true|false"
dynamic-insert="true|false"
select-before-update="true|false"
polymorphism="implicit|explicit"
where="arbitrary sql where condition"
persister="PersisterClass"
48
www.activenetdindia.com Digital Book

batch-size="N"
optimistic-lock="none|version|dirty|all"
lazy="true|false"
entity-name="EntityName"
catalog="catalog"
check="arbitrary sql check condition"
rowid="rowid"
subselect="SQL expression"
abstract="true|false"
/>

(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 distinguishes
individual subclasses, used for polymorphic behavior. 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.
(10)select-before-update (optional, defaults to false): Specifies that Hibernate should never
perform an SQL UPDATE unless it is certain that an object is actually modified. In certain
cases (actually, only when a transient object has been associated with a new session using
update()), this means that Hibernate will perform an extra SQL SELECT to determine if an
UPDATE is actually required.
(11)polymorphism (optional, defaults to implicit): Determines whether implicit or explicit query
polymorphism is used.
(12)where (optional) specify an arbitrary SQL WHERE condition to be used when retrieving
objects of this class
(13)persister (optional): Specifies a custom ClassPersister.
(14) batch-size (optional, defaults to 1) specify a "batch size" for fetching instances of this
class by identifier.
(15)optimistic-lock (optional, defaults to version): Determines the optimistic locking strategy.
(16)lazy (optional): Lazy fetching may be completely disabled by setting lazy="false".
(17)entity-name (optional): Hibernate3 allows a class to be mapped multiple times (to different
tables, potentially), and allows entity mappings that are represented by Maps or XML at the
java level. In these cases, you should provide an explicit arbitrary name for the entity. See
Section 4.4, “Dynamic models” for more information.
(18)catalog (optional): The name of a database catalog used for this class and its table.
(19)check (optional): A SQL expression used to generate a multi-row check constraint for
automatic schema generation.
(20)rowid (optional): Hibernate can use so called ROWIDs on databases which support. E.g.
on Oracle, Hibernate can use the rowid extra column for fast updates if you set this option to
rowid. A ROWID is an implementation detail and represents the physical location of a stored
tuple.

49
www.activenetdindia.com Digital Book

(21)subselect (optional): Maps an immutable and read-only entity to a database subselect.


Useful if you want to have a view instead of a base table, but don' t. See below for more
information.
(22)abstract (optional): Used to mark abstract superclasses in <union-subclass> hierarchies.

<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"
type="typename"
column="column_name"
unsaved-value="null|any|none|undefined|id_value"
access="field|property|ClassName"> <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.

<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.

50
www.activenetdindia.com Digital Book

• 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.

<property> element

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


the class.
<property name="propertyName"
column="column_name"
type="typename"
update="true|false"
insert="true|false"
formula="arbitrary SQL expression"
access="field|property|ClassName"
lazy="true|false"
unique="true|false"
not-null="true|false"
optimistic-lock="true|false"
/>

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 column(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.

51
www.activenetdindia.com Digital Book

(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).

<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"
column="column_name"
class="ClassName"
cascade="cascade_style"
fetch="join|select"
update="true|false"
insert="true|false"
property-ref="propertyNameFromAssociatedClass"
access="field|property|ClassName"
unique="true|false"
not-null="true|false"
optimistic-lock="true|false"
lazy="true|false"
entity-name="EntityName"
/>

52
www.activenetdindia.com Digital Book

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


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

<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)
class="ClassName" (2)
cascade="cascade_style" (3)
constrained="true|false" (4)
fetch="join|select" (5)
property-ref="propertyNameFromAssociatedClass" (6)
access="field|property|ClassName" (7)
formula="any SQL expression" (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.

53
www.activenetdindia.com Digital Book

(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"/>

Inheritance in Hibernate
Example on Table per Class

drop table book;

create table book(id number,


name varchar2(20),
type varchar2(20),
price number(10,2),
cds number,
discount number,
offer_type varchar2(20));

// Book.java
package cart;
import java.io.*;
public class Book implements Serializable
{
private int id;
private String name, type;
private double price;

public Book(){}

public void setId(int id)


{this.id=id;}
public void setName(String name)
{this.name=name;}
public void setType(String type)
{this.type=type;}
public void setPrice(double price)
{this.price=price;}
public int getId()
{return id;}
public String getName()
{return name;}
public String getType()
{return type;}
public double getPrice()
{return price;}
}

// SpecialEditionBook.java

54
www.activenetdindia.com Digital Book

package cart;
public class SpecialEditionBook extends Book
{
private int cds;
public SpecialEditionBook(){}

public void setCds(int cds)


{this.cds=cds;}
public int getCds()
{return cds;}
}

// AnnEditionBook.java
package cart;
public class AnnEditionBook extends Book
{
private int discount;

public AnnEditionBook(){}

public void setDiscount(int disc)


{
this.discount=disc;
}
public int getDiscount()
{
return discount;
}
}

// BookInsertion.java
package cart;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
import java.util.*;
public class BookInsertion
{
public static void main(String[] args) throws Exception
{
Configuration config=new Configuration();
config.configure("/hibernate.cfg.xml");
Session session=config.buildSessionFactory().openSession();
Transaction t=session.beginTransaction();

Book b=new Book();


b.setId(1);
b.setName("Digital Hibernate");
b.setType("Hibernate");
b.setPrice(350.00);
session.save(b);
/*
AnnEditionBook ab=new AnnEditionBook();

ab.setId(2);
ab.setName("Digital Hibernate");
ab.setType("Hibernate");

55
www.activenetdindia.com Digital Book

ab.setPrice(350.00);
ab.setDiscount(50);
session.save(ab);
*/
/*
SpecialEditionBook ab=new SpecialEditionBook();
sb.setId(3);
sb.setName("Digital Hibernate");
sb.setType("Hibernate");
sb.setPrice(350.00);
sb.setCds(2);
session.save(sb);
*/

session.flush();
t.commit();
System.out.println("Record inserted with the Id.....");
session.close();
}//main()
}//class

<hibernate-configuration>
<session-factory>
<!-- properties -->
<property name="connection.username">scott</property>
<property name="connection.url">jdbc:odbc:oracleDSN</property>
<property name="dialect">net.sf.hibernate.dialect.OracleDialect</property>
<property name="connection.password">tiger</property>
<property name="connection.driver_class">sun.jdbc.odbc.JdbcOdbcDriver</property>

<!-- mapping files -->


<mapping resource="cart/Book.hbm.xml"/>
</session-factory>
</hibernate-configuration>

<hibernate-mapping package="cart">
<class name="Book" table="book" discriminator-value="book">

<id name="id" column="id" type="int">


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

<discriminator column="offer_type" type="string"/>

<property name="name" column="name" type="java.lang.String" />


<property name="type" column="type" type="java.lang.String" />
<property name="price" column="price" type="double" />

<subclass name="SpecialEditionBook" discriminator-value="SpecialEditionBook">


<property name="cds" type="int"/>
</subclass>

<subclass name="AnnEditionBook" discriminator-value="AnnEditionBook">


<property name="discount" type="int"/>
</subclass>
</class>

56
www.activenetdindia.com Digital Book

</hibernate-mapping>

57
www.activenetdindia.com Digital Book

AnnEditionBook ab=new AnnEditionBook();

ab.setId(2);
ab.setName("Digital Hibernate");
ab.setType("Hibernate");
ab.setPrice(350.00);
ab.setDiscount(50);
session.save(ab);

SpecialEditionBook ab=new SpecialEditionBook();


sb.setId(3);
sb.setName("Digital Hibernate");
sb.setType("Hibernate");
sb.setPrice(350.00);
sb.setCds(2);
session.save(sb);

session.flush();
t.commit();
System.out.println("Record inserted with the Id.....");
session.close();

58
www.activenetdindia.com Digital Book

// BookSelection.java
package cart;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
import net.sf.hibernate.expression.*;
import java.util.*;
import cart.*;
public class BookSelection
{
public static void main(String[] args) throws Exception
{
Configuration config=new Configuration();
config.configure("/hibernate.cfg.xml");
Session session=config.buildSessionFactory().openSession();

// List list=session.createCriteria(Book.class).add(Expression.like("offer_type",
"%SpecialEditionBook%")).list();
// Iterator i=list.iterator();
// Iterator i=session.iterate("FROM Book");

List list=session.find("FROM Book");


Iterator i=list.iterator();

while(i.hasNext())
{
Book b=(Book)i.next();
System.out.println(b.getId()+":"+b.getName()+":"+b.getType()+":"+b.getPrice());
}
session.flush();
session.close();
}//main()
}//class

Example on Table per Sub Class

drop table book;

create table book(id number, name varchar2(20), type varchar2(20), price number(10,2));

create table aebook(id number, discount number);

create table sebook(id number, cds number);

<hibernate-mapping package="cart">
<class name="Book" table="book" discriminator-value="book">
<id name="id" column="id" type="int">
<generator class="assigned"/>
</id>
<property name="name" column="name" type="java.lang.String" />
<property name="type" column="type" type="java.lang.String" />
<property name="price" column="price" type="double" />

<joined-subclass name="SpecialEditionBook" table="sebook">


<key column="id"/>
<property name="cds" type="int"/>

59
www.activenetdindia.com Digital Book

</joined-subclass>

<joined-subclass name="AnnEditionBook" table="aebook">


<key column="id"/>
<property name="discount" type="int"/>
</joined-subclass>

</class>
</hibernate-mapping>

Example on Table per Concrete Class

drop table book;

drop table aebook;

drop table sebook;

create table book(id number, name varchar2(20), type varchar2(20), price number(10,2));

create table aebook(id number, name varchar2(20), type varchar2(20), price number(10,2),
discount number);

create table sebook(id number, name varchar2(20), type varchar2(20), price number(10,2),
cds number);

<hibernate-mapping package="cart">
<class name="Book" table="book" discriminator-value="book">
<id name="id" column="id" type="int" unsaved-value="0">
<generator class="assigned"/>
</id>
<property name="name" column="name" type="java.lang.String" />
<property name="type" column="type" type="java.lang.String" />
<property name="price" column="price" type="double" />
</class>
<class name="SpecialEditionBook" table="sebook">
<id name="id" type="int" unsaved-value="0">
<generator class="assigned"/>
</id>
<property name="name" column="name" type="java.lang.String" />
<property name="type" column="type" type="java.lang.String" />
<property name="price" column="price" type="double" />
<property name="cds" type="int"/>
</class>
<class name="AnnEditionBook" table="aebook">
<id name="id" type="int" unsaved-value="0">
<generator class="assigned"/>
</id>
<property name="name" column="name" type="java.lang.String" />
<property name="type" column="type" type="java.lang.String" />
<property name="price" column="price" type="double" />
<property name="discount" type="int"/>
</class>
</hibernate-mapping>

Collections mapping in Hibernate

60
www.activenetdindia.com Digital Book

Example on Mapping List


drop table grouptable;

drop table story;

create table grouptable(id number not null primary key auto_increament, name
varchar2(20));

create table story(id number not null primary key auto_increament, info varchar2(20), idx
number, parent_id number);

// Story.java
package group;
import java.io.*;
import java.util.*;
public class Story implements Serializable
{
private int id;
private String info;

public Story(){}
public Story(String i){
this.info=i;
}
public void setId(int id)
{this.id=id;}
public void setInfo(String i)
{this.info=i;}

public int getId()


{return id;}
public String getInfo()
{return info;}
}

// Group.java
package group;
import java.io.*;
import java.util.*;
public class Group implements Serializable
{
private int id;
private String name;
private List stories;

public Group(){}
public Group(String name){
this.name=name;
}
public void setId(int id)
{this.id=id;}
public void setName(String n)
{this.name=n;}
public void setStories(List s)
{this.stories=s;}

61
www.activenetdindia.com Digital Book

public int getId()


{return id;}
public String getName()
{return name;}
public List getStories()
{return stories;}
}

// GroupInsertion.java
package group;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
import java.util.*;
public class GroupInsertion
{
public static void main(String[] args) throws Exception
{
Configuration config=new Configuration();
config.configure("/hibernate.cfg.xml");
Session session=config.buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
Group sp=new Group();
sp.setId(1);
sp.setName("accounting");

ArrayList list=new ArrayList();


list.add(new Story("A Story"));
list.add(new Story("And yet another story"));
sp.setStories(list);

session.save(sp);
session.flush();
t.commit();
System.out.println("Record inserted with the Id.....");
session.close();
}//main()
}//class

<hibernate-mapping package="group">
<class name="Group" table="grouptable">

<id name="id" column="id" type="int">


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

<property name="name" type="string" />

<list name="stories" cascade="all">


<key column="parent_id"/>
<index column="idx"/>
<one-to-many class="Story"/>
</list>

</class>
<class name="Story" table="story">
<id name="id" unsaved-value="0">

62
www.activenetdindia.com Digital Book

<generator class="assigned"/>
</id>
<property name="info"/>
</class>

</hibernate-mapping>

What is key, index and element?

Since collection is owned by a class, you use the <key> element to indicate the property of the
class. The format is:

<key column=“column”/>

This element has a single attribute column, which specifies the foreign key column.

If collection is indexed like a list or map, you need use the <index> sub element.
<index column=“column” type=“class” [optional]/>

column: The column for the index values of the collection. The attribute is mandatory.
type: The type of the index. The attribute is optional

If a map is being used, the index might be a class. In this case you use the <index-many-to-
many> sub element with two attributes:
column: The column for the index values of the collection. This is required.
class: The class used as the index.

If the collection only includes values, you need to specify the <element> sub element.
<element column=“column” type=”type”/>

column: The column for the element values


type: The type of the element values

Example on Mapping ArrayList or Vector object as Bag

A bag is random grouping of objects. To change list to bag is a matter of removing the index sub
element.
<hibernate-mapping>
<class name="Group" table="grouptable">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<bag name="stories" cascade="all">
<key column="parent_id"/>
<one-to-many class="Story"/>
</bag>
<property name="name" type="string"/>
</class>
<class name="Story" table="story">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="info"/>
</class>

// Group.java

63
www.activenetdindia.com Digital Book

import java.util.*;
public class Group {
private int id;
private String name;
private List stories;

public Group(){}

public Group(String name) { this.name = name; }

public void setId(int i) {id = i; }

public int getId() { return id; }

public void setName(String n) { name = n; }

public String getName() { return name; }

public void setStories(List l) { stories = l; }

public List getStories() { return stories; }


}

// Story.java
import java.util.*;
public class Story {
private int id;
private String info;

public Story(){}

public Story(String info) { this.info = info; }

public void setId(int i) { id = i; }

public int getId() { return id; }

public void setInfo(String n) { info = n; }

public String getInfo() { return info; }


}

// Main.java
import java.io.Serializable;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.criterion.*;
import org.hibernate.event.*;
import org.hibernate.event.def.*;
public class Main {
public static void main(String[] args) throws Exception {
Group sp = new Group("Group Name");
ArrayList list = new ArrayList();
list.add(new Story("Story Name 1"));
list.add(new Story("Story Name 2"));

64
www.activenetdindia.com Digital Book

sp.setStories(list);

Transaction transaction = null;


transaction = session.beginTransaction();
session.save(sp);
transaction.commit();
session.close();
}
}
}

create table grouptable (id int,name varchar);

create table story (id int,info varchar,idx int,parent_id int);

Example on Mapping Set

create table HighScores (id int,name varchar);

create table gamescores (id int,name varchar,score int,parent_id int);

// GameScore.java
public class GameScore {
private int id;
private String name;
private int score;

public GameScore() {}

public GameScore(String name, int score) {


this.name = name;
this.score = score;
}

public void setId(int i) { id = i; }

public int getId() { return id; }

public void setName(String s) { name = s; }

public String getName() { return name; }

public void setScore(int i) { score = i; }

public int getScore() { return score; }

public boolean equals(Object obj) {


if (obj == null) return false;
if (!this.getClass().equals(obj.getClass())) return false;

GameScore obj2 = (GameScore)obj;

if ((this.id == obj2.getId()) &&


(this.name.equals(obj2.getName())) &&
(this.score == obj2.getScore())
){

65
www.activenetdindia.com Digital Book

return true;
}

return false;
}

public int hashCode() {


int tmp = 0;
tmp = (id + name + score).hashCode();

return tmp;
}
}

<hibernate-mapping>
<class name="HighScores" table="highscores">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<set name="games" cascade="all">
<key column="parent_id"/>
<one-to-many class="GameScore"/>
</set>
<property name="name" type="string"/>
</class>

<class name="GameScore" table="gamescores">


<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="name"/>
<property name="score"/>
</class>
</hibernate-mapping>

// HighScores.java
import java.util.*;
public class HighScores {
private int id;
private String name;
private Set games;

public HighScores() {
}

public HighScores(String name) {


this.name = name;
}

public void setId(int i) {


id = i;
}

public int getId() {


return id;
}

66
www.activenetdindia.com Digital Book

public void setName(String n) {


name = n;
}

public String getName() {


return name;
}

public void setGames(Set games) {


this.games = games;
}

public Set getGames() {


return games;
}
}

// Instructions.java
public class Instructions {
private int id;
private String info;

public Instructions() {
}

public Instructions(String info) {


this.info = info;
}

public void setId(int i) {


id = i;
}

public int getId() {


return id;
}
public void setInfo(String s) {
info = s;
}

public String getInfo() {


return info;
}
}

// Main.java
import java.io.Serializable;
import java.util.*;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.criterion.*;
import org.hibernate.event.*;
import org.hibernate.event.def.*;

67
www.activenetdindia.com Digital Book

public class Main {


public static void main(String[] args) throws Exception {
HighScores sp = new HighScores("HighScores Name");

HashSet set = new HashSet();


set.add(new GameScore("GameScore Name 1", 3));
set.add(new GameScore("GameScore Name 2", 2));
sp.setGames(set);
session.save(sp);

session.flush();
session.close();
}
}

Example on Mapping Map


<hibernate-configuration>
<session-factory>
<property name="connection.driver_class"></property>
<property name="connection.url"></property>
<property name="connection.username"></property>
<property name="connection.password"></property>

<!-- SQL dialect -->


<property name="dialect">org.hibernate.dialect.OracleDialect</property>

<!-- Mapping files -->


<mapping resource="SupportProperty.hbm.xml"/>
</session-factory>
</hibernate-configuration>

create table supportproperty (id int,name varchar);

create table properties (id int,property_name varchar,property_value varchar);

// SupportProperty.java
import java.util.*;
public class SupportProperty {
private int id;
private String name;
private Map properties;

public SupportProperty() {
}

public void setId(int i) {


id = i;
}

public int getId() {


return id;
}
public void setName(String s) {
name = s;
}

68
www.activenetdindia.com Digital Book

public String getName() {


return name;
}

public void setProperties(Map m) {


properties = m;
}

public Map getProperties() {


return properties;
}
}

<hibernate-mapping>
<class name="SupportProperty" table="supportproperty">
<id name="id">
<generator class="increment"/>
</id>

<map name="properties">
<key column="id"/>
<index column="property_name" type="string"/>
<element column="property_value" type="string"/>
</map>
<property name="name" type="string"/>
</class>
</hibernate-mapping>

// Main.java
import java.io.Serializable;
import java.util.*;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.criterion.*;
import org.hibernate.event.*;
import org.hibernate.event.def.*;

public class Main {


public static void main(String[] args) throws Exception {
Session session = cfg.openSession();
Transaction t=session.beginTransaction();
SupportProperty sp = new SupportProperty();
sp.setName("Joe");
HashMap p = new HashMap();
p.put("color", "blue");
p.put("lnf", "mac");
sp.setProperties(p);
session.save(sp);
session.flush();
t.commit();

SupportProperty sp2 = (SupportProperty)session.load(SupportProperty.class, new


Integer(sp.getId()));

Map p2 = sp2.getProperties();

69
www.activenetdindia.com Digital Book

System.out.println(p2.get("color"));
System.out.println(p2.get("lnf"));

session.flush();
session.close();
}
}

Example on One-to-Many element Mapping (refer Set Example & following


example)

Example on Many-to-one element Mapping

Event Location
1
1

1 1
*
Set Speaker * Attendee
Set

create table EVENTS ( uid int, name VARCHAR, start_Date date, duration int, location_id int);

create table speakers ( uid int, event_id int, firstName VARCHAR, lastName VARCHAR);

create table attendees ( uid int, event_id int, firstName VARCHAR, lastName VARCHAR);

create table location ( uid int, name VARCHAR, address VARCHAR);

<hibernate-configuration>
<session-factory>
<mapping resource="Event.hbm.xml"/>
<mapping resource="Speaker.hbm.xml"/>
<mapping resource="Attendee.hbm.xml"/>
<mapping resource="Location.hbm.xml"/>
</session-factory>
</hibernate-configuration>

// Attendee.java
public class Attendee {

70
www.activenetdindia.com Digital Book

private Long id;


private String firstName;
private String lastName;

public Attendee() {
}
public Attendee(String firstName, String lastName) {
setFirstName(firstName);
setLastName(lastName);
}
public Long getId() {
return id;
}

public void setId(Long id) {


this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

// Speaker.java
public class Speaker {

private Long id;


private String firstName;
private String lastName;

public Speaker() {
}
public Speaker(String firstName, String lastName) {
setFirstName(firstName);
setLastName(lastName);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}

71
www.activenetdindia.com Digital Book

public String getLastName() {


return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

public class Location {


private Long id;
private String name;
private String address;

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}
public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


this.address = address;
}
}

<hibernate-mapping>
<class name="Attendee" table="attendees">
<id name="id" column="uid" type="long">
<generator class="native"/>
</id>
<property name="firstName" type="string" length="20"/>
<property name="lastName" type="string" length="20"/>
</class>
</hibernate-mapping>

<hibernate-mapping>
<class name="Speaker" table="speakers">
<id name="id" column="uid" type="long">
<generator class="increment"/>
</id>
<property name="firstName" type="string" length="20"/>
<property name="lastName" type="string" length="20"/>
</class>
</hibernate-mapping>

72
www.activenetdindia.com Digital Book

<hibernate-mapping>
<class name="Location" table="locations">
<id name="id" column="uid" type="long">
<generator class="native"/>
</id>
<property name="name" type="string"/>
<property name="address" type="string"/>
</class>
</hibernate-mapping>

// Event.java
import java.util.Date;
import java.util.Set;
public class Event {
private Long id;
private String name;
private Date startDate;
private int duration;
private Set speakers;
private Set attendees;
private Location location;

public void setId(Long id) {


this.id = id;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

public Date getStartDate() {


return startDate;
}

public void setStartDate(Date startDate) {


this.startDate = startDate;
}
public int getDuration() {
return duration;
}

public void setDuration(int duration) {


this.duration = duration;
}

public Location getLocation() {


return location;
}
public void setLocation(Location location) {

73
www.activenetdindia.com Digital Book

this.location = location;
}
public void setSpeakers(Set speakers) {
this.speakers = speakers;
}

public Set getSpeakers() {


return speakers;
}
public Set getAttendees() {
return attendees;
}
public void setAttendees(Set attendees) {
this.attendees = attendees;
}
}

<hibernate-mapping>
<class name="Event" table="events">
<id name="id" column="uid" type="long" unsaved-value="null">
<generator class="increment"/>
</id>
<property name="name" type="string" length="100"/>
<property name="startDate" column="start_date"
type="date"/>
<property name="duration" type="integer"/>
<many-to-one name="location" column="location_id" class="Location"/>
<set name="speakers" cascade="all">
<key column="event_id"/>
<one-to-many class="Speaker"/>
</set>
<set name="attendees" cascade="all">
<key column="event_id"/>
<one-to-many class="Attendee"/>
</set>
</class>
</hibernate-mapping>

// SimpleRetrieveTest.java
import java.util.*;
import org.hibernate.*;
import org.hibernate.criterion.*;
public class SimpleRetrieveTest {
public static void main(String[] args) {
Session session = config.openSession();
Transaction tx = session.beginTransaction();

Event event = new Event();


event.setName("One-to-many test");
event.setSpeakers(new HashSet());
event.getSpeakers().add(new Speaker("John", "Smith")); // one-many
event.getSpeakers().add(new Speaker("Dave", "Smith")); // one-many
event.getSpeakers().add(new Speaker("Joan", "Smith")); // one-many
Location loc=(Location)session.load(Location.class, new Integer(1));
event.setLocation(loc); // many-one
session.flush();

74
www.activenetdindia.com Digital Book

session.saveOrUpdate(event);
tx.commit();
session.close ();
}
}
Example on Many-to-Many element Mapping
Employee

1
*
Emp_Benefit Benefit
1
1

create table employee (id int,name varchar);

create table benefit (id int,cost int);

create table employee_benefit (parent_id int,benefit_name varchar,benefit_id int);

<hibernate-configuration>
<session-factory>

<!-- Mapping files -->


<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>

// Benefit.java
public class Benefit {
private int id;
private int cost;

public Benefit() {
}
public Benefit(int c) {
cost = c;
}
public void setId(int i) {
id = i;
}

75
www.activenetdindia.com Digital Book

public int getId() {


return id;
}
public void setCost(int i) {
cost = i;
}

public int getCost() {


return cost;
}
}

// Employee.java
import java.util.*;
public class Employee {
private int id;
private String name;
private Map benefits;

public Employee() {
}
public void setId(int i) {
id = i;
}
public int getId() {
return id;
}
public void setName(String s) {
name = s;
}
public String getName() {
return name;
}

public void setBenefits(Map m) {


benefits = m;
}

public Map getBenefits() {


return benefits;
}
}

<hibernate-mapping>
<class name="Employee" table="employee">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>

<map name="benefits" table="employee_benefit" cascade="all">


<key column="parent_id"/>
<index column="benefit_name" type="string"/>
<many-to-many column="benefit_id" class="Benefit"/>
</map>
<property name="name" type="string"/>
</class>

76
www.activenetdindia.com Digital Book

<class name="Benefit" table="benefit">


<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="cost" type="int"/>
</class>
</hibernate-mapping>

// Main.java
import java.io.Serializable;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.criterion.*;
import org.hibernate.event.*;
import org.hibernate.event.def.*;
public class Main {
public static void main(String[] args) throws Exception {
Session session = config.openSession();
Employee sp = new Employee();
Employee sp3 = new Employee();

sp.setName("Joe");
HashMap p = new HashMap();
p.put("health", new Benefit(200));
p.put("dental", new Benefit(300));
sp.setBenefits(p);
sp3.setName("Jim");
sp3.setBenefits(p);

session.save(sp);
session.save(sp3);
session.flush();

session.close ();

Employee sp2 = (Employee)session.load(Employee.class, new Integer(sp.getId()));


Map p2 = sp2.getBenefits();
System.out.println(((Benefit)p2.get("health")).getCost());
System.out.println(((Benefit)p2.get("dental")).getCost());

session.flush();
session.close();
}
}

PK Generation
<generator> element

This is the optional element under <id> element. The <generator> element is used to specify the
class name to be used to generate the primary key for new record while saving a new record. The
<param> element is used to pass the parameter (s) to the class. Here is the example of generator
element from our first application:

77
www.activenetdindia.com Digital Book

<generator class="assigned"/>

In this case <generator> element do not generate the primary key and it is required to set the
primary key value before calling save() method.

Here are the list of some commonly used generators in hibernate:

• 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.

create table hibernate_unique_key (next_value number);


insert into hibernate_unique_key values(100);

<generator class=”hilo”>
<param name=”table”>hilo</param>
<param name=”column”>next</param>
<param name=”max to”>500</param>
</generator>

• seqhilo Combines the sequence and hilo generator. It 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 Query Language

78
www.activenetdindia.com Digital Book

Hibernate Query Language or HQL for short is extremely powerful query language. HQL is much
like SQL and are case-insensitive, except for the names of the Java Classes and properties.
Hibernate Query Language is used to execute queries against database. Hibernate automatically
generates the SQL query and execute it against underlying database if HQL is used in the
application. HQL is based on the relational object models and makes the SQL object oriented.
Hibernate Query Language uses Classes and properties instead of tables and columns.
Hibernate Query Language is extremely powerful and it supports Polymorphism, Associations,
much less verbose than SQL.

There are other options that can be used while using Hibernate. These are Query By Criteria
(QBC).

Why to use HQL?


Full support for relational operations: HQL allows representing SQL queries in the form of
objects. Hibernate Query Language uses Classes and properties instead of tables and columns.

Return result as Object: The HQL queries return the query result(s) in the form of object(s),
which is easy to use. This eliminates the need of creating the object and populate the data from
result set.

Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results
the query results along with all the child objects if any.

Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the
applications.

Support for Advance features: HQL contains many advance features such as pagination, fetch
join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection,
Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls.

Database independent: Queries written in HQL are database independent (If database supports
the underlying feature).

Understanding HQL Syntax


Any Hibernate Query Language may consist of following elements:
• Clauses
• Aggregate functions
• Subqueries

Clauses in the HQL are:


• from
• select
• where
• order by
• group by

Aggregate functions are:


avg(...), sum(...), min(...), max(...)
count(*)
count(...), count(distinct ...), count(all...)

Subqueries
Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the
underlying database supports it.

Preparing table for HQL

79
www.activenetdindia.com Digital Book

drop table if exists insurance;

CREATE TABLE insurance (ID int(11) NOT NULL default 0, insurance_name varchar(50) default
NULL, invested_amount int(11) default NULL, investement_date datetime default NULL,
PRIMARY KEY (ID) ) TYPE=MyISAM;

D insurance_name invested_amount investement_date


1 Car Insurance 1000 2005-01-05 00:00:00
2 Life Insurance 100 2005-10-01 00:00:00
3 Life Insurance 500 2005-10-15 00:00:00
4 Car Insurance 2500 2005-01-01 00:00:00
5 Dental Insurance 500 2004-01-01 00:00:00
6 Life Insurance 900 2003-01-01 00:00:00
7 Travel Insurance 2000 2005-02-02 00:00:00
8 Travel Insurance 600 2005-03-03 00:00:00
9 Medical Insurance 700 2005-04-04 00:00:00
10 Medical Insurance 900 2005-03-03 00:00:00
11 Home Insurance 800 2005-02-02 00:00:00
12 Home Insurance 750 2004-09-09 00:00:00
13 Motorcycle Insurance 900 2004-06-06 00:00:00
14 Motorcycle Insurance 780 2005-03-03 00:00:00

Preparing POJO for HQL


// Insurance.java
package unitedindia;
import java.util.Date;
public class Insurance {
private long lngInsuranceId;
private String insuranceName;
private int investementAmount;
private Date investementDate;

public String getInsuranceName() {


return insuranceName;
}
public void setInsuranceName(String insuranceName) {
this.insuranceName = insuranceName;
}

public int getInvestementAmount() {


return investementAmount;
}
public void setInvestementAmount(int investementAmount) {
this.investementAmount = investementAmount;
}
public Date getInvestementDate() {
return investementDate;
}

80
www.activenetdindia.com Digital Book

public void setInvestementDate(Date investementDate) {


this.investementDate = investementDate;
}

public long getLngInsuranceId() {


return lngInsuranceId;
}

public void setLngInsuranceId(long lngInsuranceId) {


this.lngInsuranceId = lngInsuranceId;
}
}

<class name=“unitedindia.Insurance" table="insurance">


<id name="lngInsuranceId" type="long" column="ID" > <generator class="increment"/>
</id>
<property name="insuranceName">
<column name="insurance_name" />
</property>
<property name="investementAmount">
<column name="invested_amount" />
</property>
<property name="investementDate">
<column name="investement_date" />
</property>
</class>

HQL FROM clause


// SelectHQLExample.java
package unitedindia;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;

public class SelectHQLExample {


public static void main(String[] args) {
Session session = null;

try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
//Using from Clause
String SQL_QUERY ="from Insurance insurance";
Query query = session.createQuery(SQL_QUERY);
for(Iterator it=query.iterate();it.hasNext();){
Insurance insurance=(Insurance)it.next();
System.out.println("ID: " + insurance.getLngInsuranceId());
System.out.println("First Name: " + insurance.getInsuranceName());
}
session.close();
}catch(Exception e){
System.out.println(e.getMessage());
}

81
www.activenetdindia.com Digital Book

finally{}
}
}

HQL SELECT clause


package unitedindia;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
public class SelectClauseExample {
public static void main(String[] args) {
Session session = null;
try{
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
session =sessionFactory.openSession();

//Create Select Clause HQL


String SQL_QUERY ="Select insurance.lngInsuranceId,insurance.insuranceName," +
"insurance.investementAmount,insurance.investementDate from Insurance insurance";
Query query = session.createQuery(SQL_QUERY);
for(Iterator it=query.iterate();it.hasNext();){
Object[] row = (Object[]) it.next();
System.out.println("ID: " + row[0]);
System.out.println("Name: " + row[1]);
System.out.println("Amount: " + row[2]);
}

session.close();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
}
}
}

HQL WHERE clause


package unitedindia;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
public class WhereClauseExample {
public static void main(String[] args) {
Session session = null;

try{
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();

//Query using Hibernate Query Language


String SQL_QUERY =" from Insurance as insurance where insurance.lngInsuranceId='
1'";
Query query = session.createQuery(SQL_QUERY);
for(Iterator it=query.iterate();it.hasNext();){
Insurance insurance=(Insurance)it.next();

82
www.activenetdindia.com Digital Book

System.out.println("ID: " + insurance.getLngInsuranceId());


System.out.println("Name: " + insurance.getInsuranceName());
}
//Where Clause With Select Clause
SQL_QUERY ="Select insurance.lngInsuranceId,insurance.insuranceName," +
"insurance.investementAmount,insurance.investementDate from Insurance insurance "+
" where insurance.lngInsuranceId=' 1'
";
query = session.createQuery(SQL_QUERY);
for(Iterator it=query.iterate();it.hasNext();){
Object[] row = (Object[]) it.next();
System.out.println("ID: " + row[0]);
System.out.println("Name: " + row[1]);

}
session.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
finally{}
}
}

HQL GROUP BY clause


Group by clause is used to return the aggregate values by grouping on returned component. HQL
supports Group By Clause. In our example we will calculate the sum of invested amount in each
insurance type. Here is the java code for calculating the invested amount insurance wise:

package unitedindia;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
public class HQLGroupByExample {
public static void main(String[] args) {
Session session = null;
try {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();

//Group By Clause Example


String SQL_QUERY = "select sum(insurance.investementAmount),insurance.insuranceName
"
+ "from Insurance insurance group by insurance.insuranceName";
Query query = session.createQuery(SQL_QUERY);
for (Iterator it = query.iterate(); it.hasNext();) {
Object[] row = (Object[]) it.next();
System.out.println("Invested Amount: " + row[0]);
System.out.println("Insurance Name: " + row[1]);
}
session.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
finally {}
}
}

83
www.activenetdindia.com Digital Book

HQL ORDER BY clause


Order by clause is used to retrieve the data from database in the sorted order by any property of
returned class or components. HQL supports Order By Clause. In our example we will retrieve
the data sorted on the insurance type. Here is the java example code:

package unitedindia;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
public class HQLOrderByExample {
public static void main(String[] args) {
Session session = null;
try {
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
session = sessionFactory.openSession();
//Order By Example
String SQL_QUERY = " from Insurance as insurance order by insurance.insuranceName";
Query query = session.createQuery(SQL_QUERY);
for (Iterator it = query.iterate(); it.hasNext();) {
Insurance insurance = (Insurance) it.next();
System.out.println("ID: " + insurance.getLngInsuranceId());
System.out.println("Name: " + insurance.getInsuranceName());
}
session.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
}
}
}

QBC [Query By Criteria]


The Criteria interface allows to create and execute object-oriented queries. It is powerful
alternative to the HQL but has own limitations. Criteria Query is used mostly in case of multi
criteria search screens, where HQL is not very effective.

The interface org.hibernate.Criteria is used to create the criterion for the search. The
org.hibernate.Criteria interface represents a query against a persistent class. The Session is a
factory for Criteria instances. Here is a simple example of Hibernate Criteria Query:

package unitedindia;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
public class HibernateCriteriaQueryExample {
public static void main(String[] args) {
Session session = null;
try {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
//Criteria Query Example
// VVImp

84
www.activenetdindia.com Digital Book

Criteria crit = session.createCriteria(Insurance.class);


List insurances = crit.list(); // VVImp
for(Iterator it = insurances.iterator();it.hasNext();){
Insurance insurance = (Insurance) it.next();
System.out.println("ID: " + insurance.getLngInsuranceId());
System.out.println("Name: " + insurance.getInsuranceName());
}
session.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
}
}
}

Apply Restrict on QBC [Query By Criteria]


In the last lesson we learnt how to use Criteria Query to select all the records from Insurance
table. In this lesson we will learn how to restrict the results returned from the database. Different
method provided by Criteria interface can be used with the help of Restrictions to restrict the
records fetched from database.

Criteria Interface provides the following methods:


Description
Method

Add The Add method adds a Criterion to constrain the results to be retrieved.

addOrder Add an Order to the result set.

createAlias Join an association, assigning an alias to the joined entity

This method is used to create a new Criteria, "rooted" at the associated


createCriteria
entity.

setFetchSize This method is used to set a fetch size for the underlying JDBC query.

setFirstResult This method is used to set the first result to be retrieved.

setMaxResults This method is used to set a limit upon the number of objects to be retrieved.

uniqueResult This method is used to instruct the Hibernate to fetch and return the unique
records from database.

Class Restriction provides built-in criterion via static factory methods. Important
methods of the Restriction class are:
Description
Method

Restriction.allEq This is used to apply an "equals" constraint to each property in the key set
of a Map

85
www.activenetdindia.com Digital Book

Restriction.between
This is used to apply a "between" constraint to the named property

Restriction.eq
This is used to apply an "equal" constraint to the named property

Restriction.ge This is used to apply a "greater than or equal" constraint to the named
property
Restriction.gt
This is used to apply a "greater than" constraint to the named property

Restriction.idEq This is used to apply an "equal" constraint to the identifier property

Restriction.ilike
This is case-insensitive "like", similar to Postgres ilike operator

Restriction.in This is used to apply an "in" constraint to the named property

Restriction.isNotNull This is used to apply an "is not null" constraint to the named property

Restriction.isNull This is used to apply an "is null" constraint to the named property

This is used to apply a "less than or equal" constraint to the named


Restriction.le
property

Restriction.like This is used to apply a "like" constraint to the named property

Restriction.lt This is used to apply a "less than" constraint to the named property

Restriction.ltProperty This is used to apply a "less than" constraint to two properties

Restriction.ne This is used to apply a "not equal" constraint to the named property

Restriction.neProperty This is used to apply a "not equal" constraint to two properties

Restriction.not This returns the negation of an expression

Restriction.or This returns the disjuction of two expressions

package unitedindia;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.cfg.*;
import java.util.*;
public class HibernateCriteriaQueryExample2 {
public static void main(String[] args) {
Session session = null;

86
www.activenetdindia.com Digital Book

try {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
//Criteria Query Example
Criteria crit = session.createCriteria(Insurance.class);
crit.add(Restrictions.like("insuranceName", "%a%")); //Like condition
crit.setMaxResults(5); //Restricts the max rows to 5

List insurances = crit.list();


for(Iterator it = insurances.iterator();it.hasNext();){
Insurance insurance = (Insurance) it.next();
System.out.println("ID: " + insurance.getLngInsuranceId());
System.out.println("Name: " + insurance.getInsuranceName());
}
session.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
}
}
}

87

You might also like