Java Persistence with Hibernate - Capstone Courseware

flutheronioneyedSoftware and s/w Development

Dec 13, 2013 (3 years and 8 months ago)

209 views


Java Persistence
with Hibernate


Ken Kousen
Version 3.2.1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
ii
118. Java Persistence with Hibernate
Version 3.2.1



Information in this document is subject to change without notice. Companies, names
and data used in examples herein are fictitious unless otherwise noted. No part of this
document may be reproduced or transmitted in any form or by any means, electronic or
mechanical, for any purpose, without the express written permission of the author.

A publication of Capstone Courseware, LLC.
877-227-2477
www.capstonecourseware.com

© 2006 Ken Kousen. All rights reserved.
Published in the United States.

This book is printed on 100% recycled paper.
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
iii
Course Overview

Chapter 1 Introduction to Hibernate
Chapter 2 Configuring Hibernate
Chapter 3 Hibernate Persistence
Chapter 4 Object/Relational Mapping
Chapter 5 The Criteria Query API
Chapter 6 The Hibernate Query Language

Appendix A Learning Resources
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
iv
Prerequisites
• Students will need a solid background in Java programming to
use Hibernate.
• Familiarity with relational database concepts is assumed.
• SQL knowledge is helpful as well.
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
v
Labs
• The course relies on hands-on experience in various topics and
techniques.
• All lab code is 100% Pure Java, written to build and run on the
Java Standard Edition JDK, version 5.0.
• Labs for this course have been installed to the hard drive on
each student machine.
• Lab files will be usually be found under:
− c:/Capstone for Windows systems
− $HOME/Capstone for Linux systems
• This is Capstone Courseware’s root directory, shared by this
course along with others from the Capstone curriculum.
• In some cases your instructor may have chosen a different root
location.
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
vi
Directory Structure for the Course
• The course will install to a combination of this shared course
root and its own
module root
directory
c:/Capstone/Hibernate
.
− Under this root, the Examples directory holds code examples,
including all the starting, intermediate and answer versions of all
the labs.
− The Demos directory is home to files that relate to in-class
demonstrations. Demonstrations creating files from scratch
should also use this directory.
− The Labs directory holds one subdirectory for each lab in the
course, named for the lab number. This is where you will do the
bulk of your lab work, with some reference to code in the
Examples directory.
− The Ant directory holds common build files for web projects.
• Throughout the rest of this student guide, we will refer to
directories by relative paths from the module root, as in:
− Examples/JDBC/Step1
− Demos/UsersRoles
− Labs/Lab5
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
vii
Table of Contents
Chapter 1. Introduction to Hibernate.....................................................1
Introducing Hibernate............................................................................................................3
The Object/Relational Mapping Problem............................................................................4
The “Impedance Mismatch”..................................................................................................5
JDBC.........................................................................................................................................6
The Users-Roles Schema........................................................................................................9
Tools and Environment Setup............................................................................................12
Creating the Database..........................................................................................................13
The Role Class.......................................................................................................................14
Example: A JDBC Query.....................................................................................................16
The Hibernate Alternative..................................................................................................20
Example: Using Hibernate..................................................................................................22
XML Tools.............................................................................................................................30
Lab1: Mapping the USERS Table.......................................................................................31
Chapter 2. Configuring Hibernate........................................................35
Hibernate Distributions.......................................................................................................37
The Hibernate Distribution................................................................................................39
Required Libraries................................................................................................................41
Configuration Files..............................................................................................................42
hibernate.properties.............................................................................................................43
hibernate.cfg.xml..................................................................................................................44
XML Configuration Model.................................................................................................45
Programmatic Configuration.............................................................................................46
Lab2: Hibernate Configuration..........................................................................................49
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
viii
Chapter 3. Hibernate Persistence.........................................................55
The Hibernate Architecture................................................................................................57
Interface Model.....................................................................................................................58
SessionFactory......................................................................................................................59
Example: A Hibernate Utility Class...................................................................................60
SessionFactory Methods......................................................................................................62
Hibernate Sessions...............................................................................................................63
Object States..........................................................................................................................64
State Transitions...................................................................................................................65
Session Methods...................................................................................................................66
Object States, Again.............................................................................................................69
Transactions..........................................................................................................................70
Session-Per-Operation.........................................................................................................71
Session-Per-Request.............................................................................................................72
The Data Access Object Pattern.........................................................................................74
Demo: Building A UserDAO Class....................................................................................75
Lab3: Creating a RoleDAO Class.......................................................................................81
Chapter 4. Object/Relational Mapping.................................................87
Object-Oriented Design......................................................................................................89
Relational Mapping..............................................................................................................91
Demo: Mapping Users to Roles..........................................................................................93
Bidirectional Association....................................................................................................98
Lab4A: Mapping Roles to Users.......................................................................................100
O/R Mapping Techniques.................................................................................................101
The Mapping Document...................................................................................................102
The Mapping XML Model................................................................................................103
Primary Keys and Identity................................................................................................104
Generating Identifiers........................................................................................................105
The <property> element....................................................................................................106
Other Mapping Elements..................................................................................................107
Earthlings Schema..............................................................................................................108
Earthlings Relationships....................................................................................................109
Earthlings UML..................................................................................................................110
Components........................................................................................................................111
Example: Employee Mapping...........................................................................................112
Lab4B: Basic Mapping of Earthlings................................................................................119
Mapping Associations.......................................................................................................120
The Mapping XML Model for Associations...................................................................122
Unidirectional Many-to-One............................................................................................123
Demo: Mapping Departments to Locations...................................................................124
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
ix
Eager Fetching....................................................................................................................126
Bidirectional One-To-Many.............................................................................................127
Demo: Adding Employees to Departments....................................................................128
Bidirectional One-To-One................................................................................................132
Example: Managing Departments....................................................................................133
Lab4C: Mapping Employees to Jobs................................................................................135
Mapping Inheritance.........................................................................................................136
Inheritance and Databases................................................................................................138
Single-Table Inheritance...................................................................................................139
Mapping Single-Table Inheritance..................................................................................140
Example: Employee Inheritance.......................................................................................141
Table-Per-Subclass.............................................................................................................146
Table-Per-Subclass Mapping............................................................................................147
Table-Per-Concrete-Class.................................................................................................148
Chapter 5. The Criteria Query API.......................................................157
Criteria Queries..................................................................................................................159
The Criteria Interface........................................................................................................160
The Criteria API.................................................................................................................161
The Restriction Class Utility.............................................................................................162
Other Restrictions..............................................................................................................165
Example: Conjunction and Disjunction..........................................................................166
Windowing Results............................................................................................................168
Example: Printing Employees in Windows....................................................................169
Sorting Query Results........................................................................................................170
Example: Associations.......................................................................................................171
Projections and Aggregates...............................................................................................172
The Projections Class Utility............................................................................................173
The ProjectionList Class....................................................................................................174
Example: Multiple Projections.........................................................................................175
Example: Property Projections.........................................................................................176
Example: Group By............................................................................................................177
Query By Example..............................................................................................................178
Example: Employees in Massachusetts............................................................................179
Example: QBE and Associations......................................................................................180
Lab5: Criteria Queries........................................................................................................181
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
x
Chapter 6. The Hibernate Query Language.......................................185
The Hibernate Query Language.......................................................................................187
Fundamentals.....................................................................................................................188
Example: Executing an HQL Query.................................................................................189
HQL Queries.......................................................................................................................191
Polymorphism....................................................................................................................192
Example: The Select Clause...............................................................................................193
Example: The Where Clause.............................................................................................194
Named Parameters.............................................................................................................195
Entity Parameters...............................................................................................................196
Example: Entity Parameters..............................................................................................197
Example: Ordering.............................................................................................................198
Joining on Associations.....................................................................................................199
Example: Joining on Associations....................................................................................200
Example: Traversing Associations...................................................................................201
Aggregate Methods............................................................................................................204
Updates and Deletes...........................................................................................................205
Lab6: Hibernate Queries....................................................................................................206
Named Queries...................................................................................................................207
Example: A Named Query................................................................................................208
Using Native SQL...............................................................................................................209
Example: Native SQL Queries..........................................................................................210
Appendix A. Learning Resources........................................................213
C
HAPTER
1
I
NTRODUCTION TO
H
IBERNATE

Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
2
OBJECTIVES
After completing “Introduction to Hibernate,” you will be able to:
• Understand Hibernate as an open source project.
• Relate Hibernate to the standard JDBC persistence model.
• Discuss issues related to persistence of “plain old java
objects” (“POJOs”).
• Identify the goals of Object/Relational Mapping tools.
• Demonstrate a "Hello, World" example.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
3
Introducing Hibernate

Hibernate
is an open source project whose purpose is to make
it easy to integrate relational data into Java programs.
• This is done through the use of XML mapping files, which
associate Java classes with database tables.
• Hibernate provides basic mapping capabilities. It also includes
several other
object/relational mapping
(
ORM
) capabilities,
including:
− An enhanced, object-based SQL variant for retrieving data, known
as Hibernate Query Language (HQL).
− Automated processes to synchronize objects with their database
equivalents.
− Built-in database connection pooling, including three open-
source variants.
− Transactional capabilities that can work both stand-alone or
with existing Java Transaction API (JTA) implementations.
• The goal of Hibernate is to allow object-oriented developers to
incorporate persistence into their programs with a minimum of
effort.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
4
The Object/Relational Mapping Problem
• In general, enterprise-level programs are built using object-
oriented programming languages, like Java, C#, VB.NET, Ruby,
and so on.
• Object-oriented programming techniques have several
advantages over procedural methodologies, all based in some
way on maintainability and extensibility.
− OO programs tend to scale better, due to the absence of global
variables and the use of clean interfaces between modules.
− Maintenance is enhanced partly by modularity and partly by
hiding the details of internal data structures inside classes.
− Extending existing systems is relatively easy both by composition
and by inheritance.
• The vast majority of persistence implementations use relational
databases, like IBM DB2, Microsoft SQL Server, Oracle’s
various offerings, and even open-source alternatives like
Apache Derby, Hypersonic SQL, and MySQL.

Relational database management systems
(
RDBMS
) have
their own set of advantages.
− Relational theory is an established body of mathematical body of
knowledge that assists in effective design and implementation,
− RDBMS have been optimized for speed and data integrity.
− Scaling experience has grown to the point that terabyte-sized
systems are no longer uncommon.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
5
The “Impedance Mismatch”
• In most systems with a significant amount of business logic and
data in relational databases, there is an impedance mismatch.
− The business logic is normally written in an object-oriented
(OO) language, because OO systems are generally easier to revise
and extend. The primary design criterion for them is
maintainability.
− Database systems are almost always relational. The primary
design criterion for them is speed and data integrity.
• Both sides do their jobs quite well, but differ fundamentally at
the boundary.
• Good object-oriented design practices suggest that where there
is a boundary, it is prudent to add a layer.
− Rather than access database structures throughout an OO
program, build a set of classes that map the tabular data to objects
and back again.
− A transformation layer isolates changes into a relatively small
number of classes, so that when either the classes or the tables
change, only a small portion of the code needs to be revised.
− Another benefit of a layer is that it provides a single area where
SQL statements can be intermixed with the OO language.
− Even if the database structures do not change fundamentally, the
SQL code that accesses them is often revised and refined.
− The design patterns literature refers to this layer as the Data
Access Object design pattern, which is discussed later in this
course.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
6
JDBC
• Every OO program that accesses a database performs its own
object/relational mapping.
• The simplest ORM tool in Java is provided by the
JDBC
API,
which is part of the standard edition libraries.
− The classes and interfaces in the java.sql and javax.sql packages
allow Java programs to interact with database data.
− JDBC uses drivers to isolate vendor-specific features and adapt
any RDBMS to the JDBC API:

RDBMS
Java Application
JDBC Driver Manager
RDBMS
Pure-Java
Driver
JDBC/ODBC
Brid
g
e Driver
ODBC Driver
RDBMS
RDBMS
Partial or Full
Java Driver
DB Client
Library
Pure-Java
Driver
DB
MIddleware
Local host
Network
Type 1 Type 2 Type 3 Type 4
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
7
JDBC
• The JDBC library forms a thin layer between the OO classes and
the database tables.
• The following UML diagram summarizes the JDBC driver
interfaces most useful to application code:

Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
8
JDBC
• Java classes manage the connection to the database as well as
passing SQL statements to it.
− The Connection interface represents a DB connection, a scarce
resource normally managed by a connection pool.
− The various Statement interfaces pass SQL commands to the
database.
− The ResultSet interface provides access to the virtual table
resulting from a SELECT statement.
− Characteristics of the ResultSet, like number of columns and data
types, can be found from the ResultSetMetaData interface.
• Any mapping between database tables and the middleware
classes is provided by Java code.
− Values are extracted from the ResultSet and used to populate
instances of Java classes.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
9
The Users-Roles Schema
• As a simple example, consider a typical authentication system
for a web site.
− The site uses a simple username/password combination to
authenticate users.
• Security is applied in terms of standard roles.
− Users are assigned to roles.
− Roles determine which pages a user may access.
• A typical database schema modeling users and roles is given
below.
• The schema consists of three tables:
− ROLES, which has an ID column of type int and a role_name
column of type varchar.
− USERS, which has an ID column of type int, a user_name column
of type varchar and a user_pass column of type varchar.
− USERS_ROLES, a linking table with two columns, user_id and
role_id, which are foreign keys to the other two tables.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
10
The Users-Roles Schema
• An entity/relationship diagram for this model is given below.

• Contrast this with the likely object-oriented model of the same
information:



Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
11
The Users-Roles Schema
• A SQL DDL script to build the tables is as follows:
CREATE TABLE USERS (
ID INT not null auto_increment,
user_name VARCHAR(50),
user_pass VARCHAR(50),
primary key(id)
);

CREATE TABLE ROLES (
ID INT not null auto_increment,
role_name VARCHAR(50),
primary key(id)
);

CREATE TABLE USERS_ROLES (
USER_ID INT,
ROLE_ID INT,
constraint fk_user_id
foreign key (user_id) references users(id),
constraint fk_role_id
foreign key (role_id) references roles(id)
);

• The
USERS
and
ROLES
tables are very simple, consisting only
of a primary key column and strings.
• The
USERS_ROLES
table is a link table, used to represent a
many-to-many relationship between
USERS
and
ROLES
.
• In this example, only the
ROLES
table will be examined. Later,
the many-to-many relationship will be modeled.
• The
createdb.sql
script in the actual code also inserts data
into the three tables.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
12
Tools and Environment Setup
• For exercises in this course, we’ll rely on four primary tools:
− The Java 5.0 SDK
− The Ant build utility, version 1.6
− Hibernate, of course
− The MySQL RDBMS, version 5.0
• These have all been installed on your machine.
− Ant, Hibernate, and MySQL are found bundled with the lab
software, in subdirectories of c:/Capstone/Tools.
• To support the prepared Ant build files, you will need to assure
two things about your build environment:
− The executable path must include the Java SDK’s bin directory and
also Ant’s own bin directory. A typical setting is
path=c:\Windows;c:\Windows\System32;
c:\j2sesdk5.0\bin;c:\Capstone\Tools\Ant1.6\bin

− An environment variable CC_MODULE must be defined to the
root of the lab tree; for default installations of the labs this is
CC_MODULE=c:\Capstone\Hibernate

Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
13
Creating the Database
• Start the MySQL database server:
− Open a command console and set the working directory to
c:\Capstone\Tools\MySQL5.0\bin

− From there, simply type
mysqld

− You will see no output, the process just appears to hang. It is now
listening for connections on a local network port.
• To shut down the server – though you can potentially leave it
running for the whole class – use the prepared script:
shutdown

− You’ll need a separate console for this. After it runs you’ll see the
mysqld process quietly terminate and return you to a command
prompt.
• To create the
UsersRoles
schema, open a console in
Examples/UsersRoles/JDBC
, and run
createdb
, which
launches the
mysql
terminal and feed it commands from the
prepared SQL script
createdb.sql
shown earlier.
createdb

• Particulars are encoded in the Ant build files.
− Database URLs are of the form jdbc:mysql://localhost/db_name.
− We use a default installation of MySQL in which the user root has
no password.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
14
The Role Class
• In Java, connected result sets are not passed from the database
layer to other application layers. Instead, each row is converted
to an object and the collection of objects is returned.
• For this case, to demonstrate querying the database for all the
roles in the database, we need a
Role
class.
package cc.db.beans.Role;

public class Role implements java.io.Serializable {
private Integer id;
private String name;

public Role() {}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String roleName) {
this.name = roleName;
}
}
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
15
The Role Class
• The
Role
class uses an
id
attribute of type
java.lang.Integer

rather than the
int
primitive.
− This is not required, but has advantages later when dealing with
Hibernate.
• The class implements the
java.io.Serializable
interface, which
is also not required but typical. It implies that instances of the
Role
class will be passed by value from one layer to another.
• Hibernate will use the “get” and “set” methods to populate
instances of this class for each row in the database.
− Without Hibernate, this is normally done in code, as shown in the
sample below.
• The
toString
method has been overridden to make it easy to
print objects of this class.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
16
A JDBC Query
• This example will show how to access all the rows in the ROLES
table, convert them to instances of the Role class, and print
them. The code can be found in
Examples/UsersRoles/JDBC
.
• Connecting to the database using JDBC involves
1. Loading the appropriate database driver.
2. Opening a connection using a JDBC URL.
3. Creating a java.sql.Statement, or its subinterfaces
PreparedStatement or CallableStatement.
4. Using the Statement to pass SQL to the database.
5. Processing the returned java.sql.ResultSet (if the SQL was a
query) or checking the update count (if the SQL was an INSERT,
UPDATE, or DELETE).
6. Closing everything.
• Nearly everything in JDBC can throw a
SQLException
, so the
code must be wrapped in all the needed
try/catch
blocks.
EXAMPLE
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
17
A JDBC Query
import java.sql.*;
import cc.db.beans.Role;

public class PrintRolesJDBC {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost/authdb",
"admin",
"password");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
"SELECT * FROM ROLES");
while (rs.next()) {
Role role = new Role();
role.setId(rs.getInt("id"));
role.setName(rs.getString("role_name"));
System.out.println(role);
}
rs.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}


EXAMPLE
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
18
A JDBC Query
• Test the application now with the following commands:
ant
run cc.db.jdbc.PrintRolesJDBC
(1,user)
(2,admin)

• Immediate issues related to this code:
− The name of the driver class, the JDBC URL, the username and the
password are all hard-wired into the code.
− A try/catch block is required for loading the driver, in case it isn’t
found in the classpath of the application.
• By moving to a
DataSource
, the driver, URL, username and
password can all be removed, but this requires an application
server or some other mechanism that supports JNDI.
• Alternative, light-weight approaches exist (such as the Spring
framework), but they, too, require properties files, datasources,
and additional configuration.
• In the
while
loop that processes the
ResultSet
,
− The value of each column in the ResultSet is extracted using the
proper “get” method (here, getInt and getString)
− The data for each row is then assigned to a property of the Role
class using the corresponding “set” methods, setId and setName
− Printing the object is done by putting the Role reference inside
System.out.println. This invokes the toString method on the
Role object, so this method should be overridden appropriately
EXAMPLE
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
19
A JDBC Query
• Since database connections are considered scarce resources, all
connected elements must be closed as soon as possible.
− ResultSet is closed in the try block here.
− Statement and Connection are closed in the finally block to
guarantee that they are closed whether an exception is thrown or
not.
− The calls to close in the finally block must be guarded by an if
statement to ensure that a NullPointerException isn’t thrown
accidentally.
− Since even the close method of both Statement and Connection
can throw a SQLException, they too require try/catch blocks.
• Exception handling considerably increases the amount of code
required.
− Only the stack trace of any exceptions is being printed here.
− In a real system, logging would likely be done and the SQL
exceptions might be rethrown as application exceptions.
− For debugging purposes it would probably be better to close the
Statement and Connection in separate try/catch blocks.
• Note also that object/relational mapping is being done
manually here by extracting data from the
ROLES
table and
assigning it to properties of the
Role
class.
EXAMPLE
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
20
The Hibernate Alternative
• Hibernate uses an API that encapsulates the details of the
database connection, as well as the mapping between Java
classes and database tables.
• The database connection details are normally configured in an
external file.
− A hibernate.properties file can be used, which is a simple text file
containing keys and values.
− An XML alternative is available whose default name is
hibernate.cfg.xml. The XML file covers the same properties, but
allows some additional configuration to be done. This is the most
common approach.
− The connection can also be configured purely in code, but this is
rare.
− Each option is discussed in the next chapter.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
21
The Hibernate Alternative
• The mappings between database tables and Java classes are
defined using XML configuration files.
− Each Java class requires its own customizable mapping file. The
correspondence between Java classes and database tables is not
necessarily one-to-one, however.
− Multiple classes can be mapped to a single table. This is typically
done where a Java class model would naturally separate two
concepts, like Employee and Address, but the relational model
would store all the information together to minimize the number
of joins required.
− All sorts of exotic relationships can be modeled.
− Cardinality relationships (one-to-one, one-to-many, many-to-
many) can be defined.
− Navigability can be established.
• Transactions are a fundamental part of every Hibernate
program.
− Even in a read-only program like the example below, access to the
database is done between a beginTransaction call and a commit
statement.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
22
Using Hibernate
• The code in
Examples/UsersRoles/Hibernate
illustrates how
Hibernate can be used to solve the same problem.
• Hibernate reduces the required Java coding considerably, but
the trade-off is the number of XML files that must be defined.
− An overall Hibernate configuration file is created for each
database.
− Individual mapping files need to be defined for each class.
• The Hibernate configuration file consists of a series of keys and
values, which either form a properties file or are specified in
XML. Some defined values include:
− Dialect (specified for each database vendor)
− URL, driver class, username, password
− Other helpful properties, like show_sql
− Location of mapping files for individual classes
EXAMPLE
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
23
Using Hibernate
• Here is the XML configuration file,
src/hibernate.cfg.xml
:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration … details below >

<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost/authdb
</property>
<property name="connection.username">
admin
</property>
<property name="connection.password">
password
</property>
<property name="hibernate.cache.provider_class">
org.hibernate.cache.HashtableCacheProvider
</property>
<property name="show_sql">true</property>
<mapping resource =
"com/capcourse/db/Role.hbm.xml" />
</session-factory>

</hibernate-configuration>
EXAMPLE
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
24
Using Hibernate
• The above file looks more complicated than it is. The
Hibernate configuration consists of a series of properties, each
of which is identified as an attribute of the
<property>

element.
• This configuration file holds all the connection details, such as
username, password, database driver, and URL. It also
specifies the Hibernate
dialect
, which is used to identify the
particular flavor of SQL needed for this vendor.
− A list of supported dialects is contained in the
hibernate.properties file, which is discussed in the next chapter.
• The mapping file also allows other interesting properties to be
specified, such as
show_sql
. This property tells Hibernate to
output the generated SQL code to the console.
• Finally, the file includes a
<mapping>
tag which specifies the
location of the specific XML mapping file for the Role class.
• The XML file requires a
DOCTYPE
declaration which is as
follows:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-
configuration-3.0.dtd">

• The DOCTYPE declares
− The root element of the XML file,
<hibernate-configuration>

− Information about the owner of the language and its version
− The URL where the DTD could be downloaded, if necessary
EXAMPLE
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
25
Using Hibernate
• The mapping file for the Role class specifies:
− The Java class being mapped, as well as its package
− The database table associated with this class
− The primary key column for the table
− Specific property mappings (the String data type here is inferred)
• The mapping file for the Role class is as follows:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-
mapping-3.0.dtd">

<hibernate-mapping package="cc.db.beans">
<class name="Role" table="roles"
catalog="authdb">
<id name="id">
<generator class="native" />
</id>
<property name="name" column="role_name" />
</class>
</hibernate-mapping>
EXAMPLE
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
26
Using Hibernate
• The mapping file has a different DOCTYPE declaration,
meaning that the mapping files are from a different XML
vocabulary than the configuration file.
− Its presence is required by Hibernate.
• The mapping file tells Hibernate what it needs to know in order
to manage persistence for the role type:
− There is only one class, cc.db.beans.Role.
− There is only one table, ROLES.
− The ROLES table is part of the authdb database, here identified by
the catalog attribute.
− The
<id>
element states that the primary key value is generated by
the database when rows are inserted. The various options for this
are discussed in a later chapter.
− The single
<property>
element maps the name attribute of the
Role class to the role_name column of the ROLES table. Since no
data type is identified, Hibernate assumes that the same data type
is used for both the class and the table. By reflection, this is
identified as a java.lang.String.
EXAMPLE
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
27
Using Hibernate
• With these files in the application classpath, the Java code
becomes:
import java.util.*
import org.hibernate.*;
import org.hibernate.cfg.Configuration;

import cc.db.beans.Role;

public class PrintRoles {

@SuppressWarnings("unchecked")
public static void main(String[] args) {
SessionFactory factory = new Configuration()
.configure().buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Criteria crit =
session.createCriteria(Role.class);
List<Role> roles = crit.list();
tx.commit();
for (Role r : roles) {
System.out.println(r);
}
session.close();
factory.close();
}
}
EXAMPLE
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
28
Using Hibernate
• The application uses a Hibernate
SessionFactory
class to
represent all the connection information.
− The SessionFactory reads the configuration file, generates any
required connections, and pools them.
− Normally the SessionFactory instance is created only once in a
given application and cached.
• The
Session
class represents a single interaction with the
database (to be discussed in depth later).
• The
Transaction
class represents a database transaction.
• The
Criteria
interface is used as a simplified API for retrieving
instances and will be discussed in its own chapter.
− Its createCriteria method selects all rows mapped to the class.
− The list method retrieves the populated instances of the Role class
objects as a java.util.List collection.
• The contents of the list are already
Role
objects. Hibernate
automatically populates
Role
instances for each row of the
table and adds them to the list.
− While Hibernate does not yet use Java-5.0 generics, the code
supports their use.
− The list method returns an unchecked java.util.List, which is
stored in a List<Role>.
− The Java-5 attribute @SuppressWarnings is then added to the
method signature.
EXAMPLE
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
29
Using Hibernate
• Build and test; the output is the same as from the JDBC version:
ant
run cc.db.hibernate.PrintRoles
(1,user)
(2,admin)

• Here, the application is only reading the database.
• If modifications are made and something goes wrong, the
transaction would need to be rolled back.
• To handle that, the code would be wrapped in a
try/catch

block that catches
HibernateException
, which is a runtime
(i.e., unchecked) exception.
− The transaction would be committed at the end of the try block,
and if necessary rolled back in the catch block.
− The session would be closed in a finally block.
• Hibernate reduces the required coding compared to JDBC.
• The differences become more dramatic as the number of classes
and tables increases.
EXAMPLE
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
30
XML Tools
• To support XML authoring in the classroom, a few simple tools
have been included with the course software.
• One is the Crimson text editor – run this from
c:/Capstone/Tools/Crimson3.70/cedit.exe

− You might also create a desktop shortcut to this file, or associate it
with text and XML files on your system.
• Another is the XML Validator, which will
− parse an XML file for well-formedness
− validate a file for correctness against a DTD or XML Schema
• Crimson has been primed with hotkeys that link to these two
functions, so that if you edit Spring configurations in Crimson,
you can press
F9
to parse the file or
F10
to validate it against its
DTD.
− Beware that either of these actions will save the file to disk before
running the command – usually a good thing.
− Also note that the DTD references are to public URLs; if your
machine is not connected to the Internet, F10 validation will fail.
− In this case you can replace the public URL with the appropriate
local path starting with c:/Capstone/Tools/Hibernate3.2/dtd.
• When working through the exercises in this and the next few
chapters, you may find that frequently validating with
F10
will
help you catch small syntax and grammar errors as you work.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
31
Mapping the USERS Table
Suggested time: 30 minutes
In this lab you will create the mapping document for the USERS
table in the example authentication system, building on the
existing files. The goal is to build a User class to model the USERS
table, configure Hibernate to use it, and print all the instances of
this class.
Detailed instructions are found at the end of the chapter.
LAB 1
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
32
SUMMARY
• Object-oriented programming languages and relational
databases view their data in very different ways.
• Any system using both object-oriented languages and
relational databases needs to map the classes to the database
tables.
• Java provides the JDBC API to enable Java programs to
connect to databases, pass SQL statements to them, and
process the results.
• JDBC programs map classes to tables using SQL statements
in a manner that can get tedious and repetitive.
• Hibernate describes required mappings in XML documents.
• Java programs using Hibernate make conversions from
relational data to objects and back again automatic, thus
reducing the required Java code considerably.
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
33
Mapping the USERS Table
In this lab you will create the mapping document for the USERS table in the example
authentication system, building on the existing files.
Lab workspace: Labs/Lab1
Backup of starter code: Examples/UsersRoles/Step1
Answer folder(s): Examples/UsersRoles/Step2
Files: src/cc/db/beans/User.java (to be created)
src/cc/db/beans/User.hbm.xml (to be created)
src/hibernate.cfg.xml
src/cc/db/hibernate/PrintUsers.java (to be created)
Instructions:
1. The starter code in the lab directory includes the cc.db.beans.Role class and the
cc.db.hibernate.PrintRoles class from the example. It also contains the mapping
file for the Role class, Role.hbm.xml, located in the src/cc/db/beans directory, and
the overall Hibernate XML configuration file, hibernate.cfg.xml, located in the src
directory. Examine these files and see how they interact.
2. Create a class called cc.db.beans.User. Private attributes and public accessors and
mutators are required for each column name. The names of the attributes are
arbitrary, as long as they appear correctly in the mapping file. For simplicity in this
case, use an attribute id of type Integer, and attributes name and password of type
String, then add the corresponding getter and setter methods. As a reminder, the
USERS table was created from the following SQL DDL statement:
CREATE TABLE USERS (
ID INT not null auto_increment,
user_name VARCHAR(50),
user_pass VARCHAR(50),
primary key(id)
);

3. To make it easy to print an instance of the User class, add an override for the
toString method:
public String toString() {
return "(" + id + "," + name + "," + password + ")";
}

4. Create a Hibernate mapping file for the User class. Start by copying the file
Role.hbm.xml file into User.hbm.xml in the same directory. This ensures that the
DOCTYPE declaration in the file is correct.
LAB 1
Java Persistence with Hibernate Chapter 1
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
34
Mapping the USERS Table LAB 1
5. The root element of the XML file is
<hibernate-mapping>
. It should have an
attribute called package with the value cc.db.beans. Please ensure that this is the
case.
6. Inside this element, place an element named
<class>
. It should have an attribute
name with the value User, an attribute table with the value USERS, and an attribute
catalog with the value authdb. This maps the User class to the USERS table in the
authdb schema.
7. The
<class>
element should have three child elements. The first is
<id>
, which has
an attribute named id of type java.lang.Integer and a child element
<generator>

with an attribute class with value native.
8. The other two child elements of
<class>
are both
<property>
elements. One
<property>
element should have a name attribute with the value name and the
other should have a name attribute with the value password. In light of the DDL
CREATE statement, each
<property>
element should also have an attribute called
column with the values user_name and user_pass, respectively.
9. Finally, the Hibernate configuration file needs to be updated to include the new User
mapping file. Open the file hibernate.cfg.xml and note the
<mapping>
element for
Role already exists. Add another
<mapping>
element below that, with a resource
attribute whose value is src/cc/db/beans/User.hbm.xml. In this example, the
mapping files are all being stored in the directory src/cc/db/beans. This is, of
course, arbitrary, as long as the proper paths are in the Hibernate mapping file.
10. Now that Hibernate has been configured to use the new class, we need a client class to
test it. Create a class called PrintUsers in the cc.db.hibernate package by copying
the existing class PrintRoles in the same package.
11. The PrintUsers class already has all the code necessary to read all the User instances
from the database and print them. All that has to be modified is the call to
createCriteria. Change its argument from Role.class to User.class. The rest –
building the SessionFactory, getting a Session, beginning a transaction, creating the
Criteria query and executing it, printing the results, and shutting everything down,
should all be fine.
12. Run the PrintUsers class as a Java application. You should get an output similar to
the following:
ant
run cc.db.hibernate.PrintUsers
(1,buffy,slayer)
(2,willow,witch)

In a later lab, the many-to-many relationship between User and Role instances will be
modeled as well by building on these results.
C
HAPTER
2
C
ONFIGURING
H
IBERNATE

Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
36
OBJECTIVES
After completing “Configuring Hibernate,” you will be able to:
• List the required libraries for Hibernate.
• Use the Hibernate properties files.
• Create an XML configuration file.
• Examine the methods involved in programmatic
configuration.
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
37
Hibernate Distributions
• In the previous chapter, Hibernate was used to examine the
data in a particular database table.
• The configuration files for Hibernate were already created and
customized.
• In this chapter, the structure and content of the overall
configuration file is examined in some detail.
• The required and optional tags are identified and discussed.
• In the next chapter, mapping issues for specific situations will
be examined.
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
38
Hibernate Distributions
• The Hibernate project is located at
http://www.hibernate.org

• This site always has the latest information on Hibernate.
• In addition to the distribution downloads, the site also
contains:
− A user forum with an archive for historical items
− A wiki area for questions and answers
− Information about email lists
− Links to postings about design patterns, Hibernate Tools, and
more
• The current version of Hibernate is 3.2.
− Version 3.2 is compatible with the EJB 3.0 specification, part of
Java EE 5.
• We will work with version 3.2 in these materials.
− Code in practice is normally from versions 2.1 (old), 3.0, and 3.1.
− None of the 3.x versions are dramatic variations from each other.
− Code using version 2.x is a good candidate to be ported to 3.x.
• Find our Hibernate file set in
c:/Capstone/Tools/Hibernate3.2
.
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
39
The Hibernate Distribution
• The Hibernate distribution comes as a zipped file which
includes the libraries, documentation, and source code.
Unzipping the distribution reveals the following directory
structure.

− Note that, to keep downloads to a reasonable size and classroom
setup simple, our local version is just a subset of this distribution;
some of the folders shown above will not appear locally.
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
40
The Hibernate Distribution
• The distribution contains the following directories:
− doc, which includes the JavaDoc API reference, the Hibernate
tutorial, and a PDF file with a Quick Reference guide
− eg, which contains a limited version of the Caveat Emptor online
auction application that Hibernate uses as its primary
demonstration app – we will examine parts of this application in
this course
− etc, which has configuration-file samples
− grammar, which contains files defining the Hibernate Query
Language grammar
− lib, containing the required and optional JAR files (discussed
below)
− src, which contains the Hibernate source code
1

− test, which has the JUnit test cases for validation
• The root directory also has several files:
− An Ant build file used to compile and test the distribution
− The hibernate3.jar file, which is needed in every Hibernate
application
− A readme.txt file and a license file – Hibernate is distributed
under the GNU Lesser General Public License


1
Since Hibernate is an open-source project, the latest source code can always be examined, either in the
distribution or using the Hibernate Subversion repository. See the Hibernate home page for details.
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
41
Required Libraries
• In addition to
hibernate3.jar
, the
lib
directory contains a
wide selection of JAR files.
• The file
_README.txt
in this directory indicates which are
required and which are optional.
• Some of the libraries are used only to build the distribution,
while others are needed at runtime.
• The required libraries are:
− hibernate3.jar, found in the root directory
− antlr.jar
− asm.jar
− asm-attrs.jar
− cglib.jar
− commons-collections.jar
− commons-logging.jar
− dom4j.jar
− ehcache.jar, required if no other cache provider is used
− jta.jar, required for running outside a J2EE container
− log4j.jar, not strictly required but recommended
• Also required is the JDBC driver for your database, which must
be added for each project.
• Note that all library names also contain version numbers.
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
42
Configuration Files
• Two types of configuration files are needed:
− One to manage Hibernate itself, meaning the database
connections, caching and fetching strategies, and more
− One for each of the Java classes in the system – the
object/relational mappings for each class
• The basic Hibernate configuration can be done either using a
standard properties file or an XML configuration file.
• By default, the properties file is
hibernate.properties
.
• A sample version of this file is located in the
etc
directory and
can be customized for individual projects.
• A list of available properties is given in the JavaDoc API page
for the
org.hibernate.cfg.Environment
class.
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
43
hibernate.properties
• The
hibernate.properties
file is divided into several sections,
including those listed below.
• Query Language
− Constraints on HQL, the Hibernate Query Language discussed
below
• Platforms
− This is where the individual database JDBC driver is configured.
− Username, password, and URL properties for many different
vendor databases are included in comments.
• Hibernate, C3P0, Proxool, and custom connection pools
• Transaction API
• Miscellaneous Settings
− Examples such as show_sql, format_sql, auto schema export,
and others
• JDBC Settings
− Isolation levels, fetch depth, autocommit settings, batch updates,
and more
• Second-level Cache
− Several built-in cache providers are available.
• JNDI
− Specifies URL and class for JNDI provider
− Used for managed JDBC connection pools
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
44
hibernate.cfg.xml
• Hibernate can also be configured with an XML file, normally
called
hibernate.cfg.xml
.
• The format is essentially the same as the properties file, where
property names become attributes of the
<property>
elements
and property values become their text contents.
• As an example, consider the database configuration properties
for MySQL, as listed in the sample
hibernate.properties
file
in the Hibernate distribution:
hibernate.connection.driver_class
com.mysql.jdbc.Driver
hibernate.connection.url jdbc:mysql:///test
hibernate.connection.username gavin
hibernate.connection.password

• In the sample XML file, this becomes:
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url>
jdbc:mysql:///test
</property>
<property name=”connection.username>
gavin
</property>
<property name="connection.password"></property>

• Note that in the XML file, the word “hibernate” is not
prepended to the property names.
• One advantage of the XML configuration is that individual
mapping files can be declared using the
<mapping>
element.
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
45
XML Configuration Model
• The DTD for the Hibernate configuration file is
hibernate-
configuration-3.0.dtd
.
− In the standard distribution it is distributed with the source code,
and found in src/org/hibernate.
− With this courseware it is found in
c:/Capstone/Tools/Hibernate3.2/dtd

• A summary diagram is shown here:

< hibernate-configuration >
< session-factory >
< property
name
>
< mapping
class
resource
file
jar
package
>
Text
< security >
< property
name
>
< mapping
class
resource
file
jar
package
>
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
46
Programmatic Configuration
• Hibernate comes with a class called
Configuration
which can
be used to specify configuration properties at run time.
• This class may be instantiated directly, as in:
Configuration cfg = new Configuration();

• Once the configuration instance has been obtained, properties
can be assigned using the
setProperty
method.
• In general, methods in Hibernate return a reference to the
current object, so method calls can be chained – for example:
Configuration cfg = new Configuration()
.setProperty("hibernate.dialect",
"org.hibernate.dialect.MySQLDialect")
.setProperty("hibernate.show_sql","true");

Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
47
Programmatic Configuration
• A key element of the configuration is specifying the location of
the individual mapping files for each class.
• If the mapping files are in the classpath of the application, use
the
addResource
method:
cfg.addResource("User.hbm.xml")
.addResource("Role.hbm.xml");

• Or, the class itself can be specified, as in:
cfg.addClass(cc.db.beans.User.class)
.addClass(cc.db.beans.Role.class);

− In this case, Hibernate will look for the mapping files named
src/cc/db/beans/User.hbm.xml and
src/cc/db/beans/Role.hbm.xml in the classpath.
• Since the method calls can be chained, the entire sequence can
be written in one extended line:
Configuration cfg = new Configuration()
.setProperty("hibernate.dialect",
"org.hibernate.dialect.MySQLDialect")
.setProperty("hibernate.show_sql","true")
.addClass(cc.db.beans.User.class)
.addClass(cc.db.beans.Role.class);

Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
48
Programmatic Configuration
• Pass an instance of the
java.util.Properties
class to
Configuration.setProperties()
.
− This way, properties can be placed in a standard file structure that
can be accessed using the load method in the Properties class.
• Set
System
properties using the
–D
flag in the java command,
as in
java –Dproperty=value
.
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
49
Hibernate Configuration
Suggested time: 30 minutes.
In this lab you will convert a Hibernate XML configuration file into
a standard hibernate.properties file. Then you will experiment
with various settings in the file to see how they affect the results.
Detailed instructions are found at the end of the chapter.
LAB 2
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
50
SUMMARY
• Configuring Hibernate can be done through several
mechanisms.
• There is a standard properties file known as
hibernate.properties
. This file must be found on the
application’s class path.
• The XML configuration file by default is called
hibernate.cfg.xml
. This file replaces the
hibernate.properties
file.
• The XML file also has tags that show the location of each
individual mapping file.
• The Hibernate API includes a
Configuration
class which, in
addition to reading the configuration files, also has methods
that allow programmatic configuration.
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
51
Hibernate Configuration
In this lab you will convert a Hibernate XML configuration file into a standard
hibernate.properties file. Then you will experiment with various settings in the file to
see how they affect the results.
Lab workspace: Labs/Lab2
Backup of starter code: Examples/UsersRoles/Step2
Answer folder(s): Examples/UsersRoles/Step3 (intermediate)
Examples/UsersRoles/Step4 (final)
Files: src/cc/db/hibernate/PrintUsers.java
src/hibernate.properties
src/hibernate.cfg.xml
Instructions:
1. The working directory has the same UsersRoles application from the conclusion of
Lab 1. Make sure the PrintUsers application runs correctly.
2. The application currently uses an XML configuration file to set the needed Hibernate
properties. To switch to using a properties file instead, copy the sample
hibernate.properties file from the Hibernate distribution into the src directory.
You’ll find the sample file in c:/Capstone/Tools/Hibernate3.2/etc.
3. The application uses the MySQL database, so locate the MySQL section of the
hibernate.properties file in the Platforms section.
4. By default, the hibernate.properties file is set to use HypersonicSQL. The section
for this database is immediately above the MySQL section. Use # signs to comment
out all the Hypersonic SQL properties.
5. In the MySQL section, uncomment the dialect, driver_class, url, username, and
password properties. The driver_class value should already be
com.mysql.jdbc.Driver, but if not, set it to that value. Likewise, set the value of the
url to jdbc:mysql://localhost/authdb, the value of the username to admin, and
the value of the password to password.
6. Note that there are three different MySQL dialects. In general, you will use the
MySQLInnoDBDialect, because MySQL uses its internal InnoDB type to support
transactional behavior. In this case, it isn’t strictly necessary. Uncomment the dialect
property for the MySQLDialect, though the others would work just as well.
LAB 2
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
52
Hibernate Configuration LAB 2
1. Near the bottom of the file (roughly line 460), there is a section to choose a cache
implementation. To be consistent with the XML configuration file, make sure that
the provider_class assigned to org.hibernate.cache.HashtableCacheProvider is
uncommented.
2. Open the PrintUsers class in your editor. The part of this class affected by the
change in configuration files is the construction of the SessionFactory. In the
command to create it, remove the call to the configure method. Instantiating the
Configuration class will automatically search for a file named
hibernate.properties along the class path, which is fine, but the call to the
configure method will then try to load the XML configuration file that we are not
using.
3. Unlike the XML file, the hibernate.properties file can’t be configured to load the
mapping files. This has to be done programmatically. This can be done either by
using the methods addResource or addClass in the Configuration class. In this
case, add the addClass method calls as shown. Note that the addition of the Role
class is not necessary here, but the technique is typical.
SessionFactory factory = new Configuration()
.addClass(User.class)
.addClass(Role.class)
.buildSessionFactory();

4. When using the addClass method in this manner, Hibernate will assume that the
mapping files for the classes are located in the same directory as the Java classes
themselves. Therefore, the files Role.hbm.xml and User.hbm.xml should be in the
src/cc/db/beans directory.
5. Finally, to make it easier to see what Hibernate is doing under the hood, copy the
sample log4j.properties file from c:/Capstone/Tools/Hibernate3.2/etc into the
src directory. This file is already set up to use a console appender that will log info
messages to standard output.
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
53
Hibernate Configuration LAB 2
6. Build and run the application. Near the top of the output, there should be an INFO
message from the Environment stating that properties are being loaded from
resource hibernate.properties. In curly braces, that line will list all the property
names and values from the file. Verify that these are what you want them to be.
ant
run cc.db.hibernate.PrintUsers
INFO Environment:500 - Hibernate 3.2.0
INFO Environment:518 - loaded properties from resource
hibernate.properties: {...}
...
INFO Configuration:535 - Reading mappings from resource:
src/cc/db/beans/User.hbm.xml
INFO HbmBinder:300 - Mapping class: cc.db.beans.User -> USERS
INFO Configuration:535 - Reading mappings from resource:
src/cc/db/beans/Role.hbm.xml
INFO HbmBinder:300 - Mapping class: cc.db.beans.Role -> ROLES
...
(1,buffy,slayer)
(2,willow,witch)
...

Soon after that, check that there are INFO messages from Configuration indicating
that mappings are being read from the User.hbm.xml and Role.hbm.xml resource
files. The output of the application – a list of users and their roles –appears near the
bottom of the output, just before the SessionFactory shuts down.
7. To see what SQL statements Hibernate is executing, search in the
hibernate.properties file for the Miscellaneous Settings section around line 300.
Uncomment the line for the show_sql properties, which assigns it to true, and run
the application again.
8. The output now shows the SQL SELECT statement that Hibernate is using to retrieve
the User instances. Since the format_sql property is currently set to true, the output
is spread over several lines. It should like something like:
Hibernate:
select
this_.id as id0_0_,
this_.user_name as user2_0_0_,
this_.user_pass as user3_0_0_
from
authdb.USERS this_

This is the intermediate answer shown in Step3.
Java Persistence with Hibernate Chapter 2
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
54
Hibernate Configuration LAB 2
9. To illustrate the use of one of the built-in database connection pools, search for the
section in the hibernate.properties file marked C3P0 Connection Pool (roughly
line 220). Uncomment all seven lines in that section.
10. Rerun the application and check the output of the logger. There should be three
INFO lines from the C3P0ConnectionProvider indicating the connection pool start
up and configuration.
ant
run cc.db.hibernate.PrintUsers
...
INFO C3P0ConnectionProvider:50 - C3P0 using driver:
com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/authdb
INFO C3P0ConnectionProvider:51 - Connection properties: {user=root,
password=****}
INFO C3P0ConnectionProvider:54 - autocommit mode: false
...

This is the final answer shown in Step4.
C
HAPTER
3
H
IBERNATE
P
ERSISTENCE

Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
56
OBJECTIVES
After completing “Hibernate Persistence,” you will be able to:
• Demonstrate how to build the
SessionFactory
object.
• Create and work with
Session
objects.
• Use transactions in Hibernate.
• Implement CRUD methods.
• Illustrate the
Data Access Object
design pattern.
Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
57
The Hibernate Architecture
• The Hibernate API includes about 1000 classes and interfaces.
• According to the JavaDoc documentation, these classes are
divided into the
Core API
, the
Extension API
, a
Miscellaneous API
, an
Internal Implementation
, and so-
called
Other Packages
.
• Fortunately, a developer intending to use Hibernate only needs
to learn a relatively small number of them in order to make
progress; the following interfaces are all from
org.hibernate
:
− SessionFactory
− Session
− Transaction
− Query
− Criteria
− ScrollableResults
• For backward compatibility with versions prior to 3.0, the 3.2
distribution includes the
org.hibernate.classic
package, now
deprecated.
• Finally, the
org.hibernate.usertype
package includes
interfaces for user-defined types.
Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
58
Interface Model
• The top-level interfaces used by most Hibernate code are shown
in the following UML diagram:

− Every Hibernate client will use a SessionFactory to create one or
more Sessions, which wrap JDBC Connections and can associate
Hibernate’s own Transaction abstraction.
− Not shown is org.hibernate.cfg.Configuration, used in the
previous chapter for programmatic configuration.
− We’ll see that there are a number of “second-level” interfaces
involved with Criteria and HQL queries.
Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
59
SessionFactory
• All Hibernate programs start by acquiring a
SessionFactory

instance.
• Earlier examples illustrated that the way to build a
SessionFactory
differs depending on whether one uses a
hibernate.properties
file or a
hibernate.cfg.xml
file.
− When using the hibernate.properties file, the code is:
SessionFactory factory =
new Configuration().buildSessionFactory();

− When using an XML configuration file, the process is slightly
different:
SessionFactory factory =
new Configuration().configure()
.buildSessionFactory();

• Building a
SessionFactory
is an expensive operation.
− It involves processing all the input properties files – both the basic
configuration file and the individual mapping files.
− A SessionFactory should therefore be instantiated only once and
cached for later access.
• The Hibernate tutorial built into the documentation in the
distribution shows a typical idiom, which is to use a utility class
to store the
SessionFactory
and acquire
Session
instances.
We’ll examine that idea next.
Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
60
A Hibernate Utility Class
• Here is the class
HibernateUtil
from the tutorial. This file is in
the Hibernate distribution in the following directory:
c:/Capstone/Tools/Hibernate3.2
/doc/reference/tutorial/src/util

− The “util” token means that we’re working with the util package.
− The only difference between that file and the listing below is that
the code here has been formatted for readability.
import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {

private static final SessionFactory factory;

static {
try {
factory = new Configuration()
.configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println(
"Initial SessionFactory creation failed."
+ ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory()
{
return factory;
}
}
EXAMPLE
Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
61
A Hibernate Utility Class
• The
SessionFactory
is created in a
static initialization
block
, which ensures that it is available as soon as the utility
class is loaded.
• The factory itself is stored in a
static
attribute of the class.
• This class assumes that the default XML configuration file
hibernate.cfg.xml
is being used; this is the most common
option.
• If creation fails, the exception is printed and rethrown.
• This example assumes that the application is self-contained.
− If an application server is available, the SessionFactory instance
can be stored in a JNDI registry under a particular look-up string.
− The utility class would then do the JNDI look-up, but would
otherwise be the same.
EXAMPLE
Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
62
SessionFactory Methods
• The Hibernate API documentation shows 25 different methods
in the
SessionFactory
class, counting all overloads.
• Nevertheless, the vast majority of programs use only the
following methods:
− The openSession method, which creates a database connection
and instantiates an internal Session on it.
public Session openSession()
throws HibernateException

− The getCurrentSession method, which retrieves the current
session, if some form of session context management has been
enabled (to be discussed later).
public Session getCurrentSession()
throws HibernateException

− The close method, which destroys the SessionFactory and
releases all resources associated with it.
public void close() throws HibernateException

• Recall that
HibernateException
is a runtime (i.e. unchecked)
exception and therefore does not require a
try/catch
block.
Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
63
Hibernate Sessions
• A Hibernate
Session
is a single-threaded, non-shared object
that represents a particular unit of work with the database.
− It also has the API methods, like save, delete, update and get,
used to interact with the database.
• Each interaction with the database takes place in a session.
• The main function of the
Session
is to manage persistence for
entity
classes.
− An entity is an object associated with a unique row in the
database, identified by a primary key.
− This is in contrast to a value object, which is dependent on an
entity.
− The distinction will be discussed further in the next chapter.
• The Session class therefore contains the so-called
CRUD

methods:
Create
,
Retrieve
,
Update
, and
Delete
.
− Create is done with save.
− Retrieve is done with get, or the various other querying APIs.
− Update is done with update.
− Delete is done with delete.
• Later we’ll consider the
Data Access Object
design pattern as
a way to encapsulate all interactions with the persistent store.
Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
64
Object States
• Java objects are populated in
Sessions
, but an object’s lifecycle
may extend beyond that of the session.
• Any Hibernate-mapped object may exist in one of three states:
− Transient, implying the object is not associated with any Session
− Persistent, meaning associated with a unique Session
− Detached, which implies that the object was previously persistent
but no longer associated with any Session
• Detached objects replace the so-called
Value Object
or
Data
Transfer Object (DTO)
design pattern often used in J2EE web
applications.
− An instance is populated from the database but is no longer
connected to it. The instance is then used wherever necessary in
the middleware or view layer.
− Since it is unconnected, there is a risk the data will become
outdated (stale). In many cases, this is considered better than
leaving open database connections longer than strictly necessary.
Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
65
State Transitions
• An object may move from one of these three states to the other,
as follows:

• From the JavaDoc API for the
Session
class:
− “Transient instances may be made persistent by calling save,
persist, or saveOrUpdate. Persistent instances may be made
transient by calling delete. Any instance returned by a get or load
method is persistent. Detached instances may be made persistent by
calling update, saveOrUpdate, lock, or replicate. The state of a
transient or detached instance may also be made persistent as a new
persistent instance by calling merge.”
Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
66
Session Methods
• The
save
method persists a transient instance of an entity after
assigning it a generated identifier, or the current value of the
identifier if the
assigned
generator is used.
public Serializable save(Object o)
throws HibernateException

− The operation returns the generated identifier as a Serializable
reference.
− It also saves associated instances if the association is mapped with
the attribute cascade = “save-update”.
− ID generators are discussed in the next chapter.
• Objects are retrieved using the
get
or
load
method. While
there are several overloaded versions of each, the basic
structure is:
public Object get(Class c, Serializable id)
throws HibernateException

public Object load(Class c, Serializable id)
throws HibernateException

• Each method returns the persistent instance of the given entity
class with the given identifier, assuming the instance exists.
• The
load
method throws an exception if the instance does not
exist; the
get
method returns null.
• If an instance is already associated with the current
Session
,
the
get
method will return it.
Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
67
Session Methods
• Hibernate offers other means of reading and managing data,
including a rich API for building
Criteria
queries and for using
Hibernate Query Language
.
• An example of a
Criteria
query has already been shown above.
To repeat:
Criteria crit = session.createCriteria(Role.class);
List roles = crit.list();

− The Criteria API allows queries to be constructed in an object-
oriented fashion without worrying about SQL details.
− The Criteria API is discussed later, in it own chapter.
• A
Hibernate Query Language
(
HQL
) example is:
Query q = session.createQuery(
"from Role where id = :id");
Role r = (Role) q.uniqueResult();

− HQL is an object-based SQL variant that has named parameters
(the id parameter above) among other capabilities.
− HQL is also discussed in its own chapter, later in the course.
Java Persistence with Hibernate Chapter 3
© 2006 Ken Kousen.
All rights reserved by Capstone Courseware, LLC.
68
Session Methods
• The
update
method is used to update the persistent instance
with the identifier of the given detached instance:
public void update(Object o)
throws HibernateException

− It is therefore assumed that the argument is a detached instance
containing the updated state.
• A valuable alternative is the