Presented By: Digital Book
Presented By: Digital Book
Presented by
1
www.activenetdindia.com Digital Book
Gavin King
Inventor of Hibernate
Distribution given from
sourceforge.net
Working at JBoss on EJB 3.0
Rod Johnson
Inventor of Spring
CEO of Interface 21
Craig McClanahan
Inventor of Struts
Licensing from Apache
Working at Sun
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
•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
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
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
JSP
EJB
DAO
CORBA
6
www.activenetdindia.com Digital Book
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
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.
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.
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">,
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.
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.
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.
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
16
www.activenetdindia.com Digital Book
Hibernate Components
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)
•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)
refresh(Object o) clear()
lock(Object o, LockModel mode) close()
setFlushMode(FlushMode mode) connection()
19
www.activenetdindia.com Digital Book
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).
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.
20
www.activenetdindia.com Digital Book
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>
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.
•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
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
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
22
www.activenetdindia.com Digital Book
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
23
www.activenetdindia.com Digital Book
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
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.
25
www.activenetdindia.com Digital Book
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.
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
27
www.activenetdindia.com Digital Book
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.
28
www.activenetdindia.com Digital Book
</set>
</class>
</hibernate-mapping>
Figure. The Database Schema The demo uses a simple database design.
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
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>
30
www.activenetdindia.com Digital Book
net.sf.hibernate.transaction.JRun4TransactionManagerLookup JRun4
net.sf.hibernate.transaction.BESTransactionManagerLookup Borland ES
31
www.activenetdindia.com Digital Book
32
www.activenetdindia.com Digital Book
33
www.activenetdindia.com Digital Book
34
www.activenetdindia.com Digital Book
35
www.activenetdindia.com Digital Book
36
www.activenetdindia.com Digital Book
hibernate.cfg.xml
<hibernate-configuration>
Contains DB driver information
or
DataSource information
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
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
38
www.activenetdindia.com Digital Book
CLASSPATH
set
HYB_HOME=G:\Digital\RefMaterial\2005Workshops\Hibernate\Hibernate2
.1.6\hibernate-2.1
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
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;}
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
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);
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
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
API
DB
Java Bean
API
DB
Java Bean
45
www.activenetdindia.com Digital Book
API
DB
Java Bean
SessionFactory factory=c.buildSessionFactory();
Session session=factory.openSession();
Loads all bean.hbm.xml files and
their mapping to DB
API
DB
Java Bean
46
www.activenetdindia.com Digital Book
API
DB
Java
Bean
Domain
modeling
diagram
47
www.activenetdindia.com Digital Book
<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"
/>
<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
<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"/>
/>
<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.
• 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
(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).
(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.
<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
<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.)
Inheritance in Hibernate
Example on Table per Class
// Book.java
package cart;
import java.io.*;
public class Book implements Serializable
{
private int id;
private String name, type;
private double price;
public Book(){}
// SpecialEditionBook.java
54
www.activenetdindia.com Digital Book
package cart;
public class SpecialEditionBook extends Book
{
private int cds;
public SpecialEditionBook(){}
// AnnEditionBook.java
package cart;
public class AnnEditionBook extends Book
{
private int discount;
public AnnEditionBook(){}
// 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();
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>
<hibernate-mapping package="cart">
<class name="Book" table="book" discriminator-value="book">
56
www.activenetdindia.com Digital Book
</hibernate-mapping>
57
www.activenetdindia.com Digital Book
ab.setId(2);
ab.setName("Digital Hibernate");
ab.setType("Hibernate");
ab.setPrice(350.00);
ab.setDiscount(50);
session.save(ab);
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");
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
create table book(id number, name varchar2(20), type varchar2(20), price number(10,2));
<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" />
59
www.activenetdindia.com Digital Book
</joined-subclass>
</class>
</hibernate-mapping>
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>
60
www.activenetdindia.com Digital Book
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;}
// 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
// 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");
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">
</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>
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”/>
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(){}
// Story.java
import java.util.*;
public class Story {
private int id;
private String info;
public Story(){}
// 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);
// GameScore.java
public class GameScore {
private int id;
private String name;
private int score;
public GameScore() {}
65
www.activenetdindia.com Digital Book
return true;
}
return false;
}
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>
// HighScores.java
import java.util.*;
public class HighScores {
private int id;
private String name;
private Set games;
public HighScores() {
}
66
www.activenetdindia.com Digital Book
// Instructions.java
public class Instructions {
private int id;
private String info;
public Instructions() {
}
// 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
session.flush();
session.close();
}
}
// SupportProperty.java
import java.util.*;
public class SupportProperty {
private int id;
private String name;
private Map properties;
public SupportProperty() {
}
68
www.activenetdindia.com Digital Book
<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.*;
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();
}
}
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);
<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
public Attendee() {
}
public Attendee(String firstName, String lastName) {
setFirstName(firstName);
setLastName(lastName);
}
public Long getId() {
return id;
}
// Speaker.java
public class Speaker {
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
<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;
73
www.activenetdindia.com Digital Book
this.location = location;
}
public void setSpeakers(Set speakers) {
this.speakers = speakers;
}
<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();
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
<hibernate-configuration>
<session-factory>
// 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
// 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;
}
<hibernate-mapping>
<class name="Employee" table="employee">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
76
www.activenetdindia.com Digital Book
// 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 ();
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.
• 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.
<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.
• 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).
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).
Subqueries
Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the
underlying database supports it.
79
www.activenetdindia.com Digital Book
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;
80
www.activenetdindia.com Digital Book
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{}
}
}
session.close();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
}
}
}
try{
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
82
www.activenetdindia.com Digital Book
}
session.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
finally{}
}
}
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();
83
www.activenetdindia.com Digital Book
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 {
}
}
}
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
Add The Add method adds a Criterion to constrain the results to be retrieved.
setFetchSize This method is used to set a fetch size for the underlying JDBC query.
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.ilike
This is case-insensitive "like", similar to Postgres ilike operator
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
Restriction.lt This is used to apply a "less than" constraint to the named property
Restriction.ne This is used to apply a "not equal" constraint to the named property
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
87