You are on page 1of 232

Hibernate Reference Documentation

Version: 3.2.7

Table of Contents
Preface ............................................................................................................................................ ix
1. Introduction to Hibernate ........................................................................................................... 1
1.1. Preface .............................................................................................................................. 1
1.2. Part 1 - The first Hibernate Application ............................................................................... 1
1.2.1. The first class .......................................................................................................... 1
1.2.2. The mapping file ..................................................................................................... 3
1.2.3. Hibernate configuration ........................................................................................... 4
1.2.4. Building with Ant .................................................................................................... 6
1.2.5. Startup and helpers .................................................................................................. 6
1.2.6. Loading and storing objects ...................................................................................... 8
1.3. Part 2 - Mapping associations ............................................................................................ 10
1.3.1. Mapping the Person class ....................................................................................... 10
1.3.2. A unidirectional Set-based association .................................................................... 11
1.3.3. Working the association ......................................................................................... 12
1.3.4. Collection of values ............................................................................................... 13
1.3.5. Bi-directional associations ..................................................................................... 14
1.3.6. Working bi-directional links ................................................................................... 15
1.4. Part 3 - The EventManager web application ....................................................................... 16
1.4.1. Writing the basic servlet ........................................................................................ 16
1.4.2. Processing and rendering ....................................................................................... 17
1.4.3. Deploying and testing ............................................................................................ 18
1.5. Summary ......................................................................................................................... 19
2. Architecture .............................................................................................................................. 20
2.1. Overview ......................................................................................................................... 20
2.2. Instance states .................................................................................................................. 22
2.3. JMX Integration ............................................................................................................... 22
2.4. JCA Support .................................................................................................................... 23
2.5. Contextual Sessions .......................................................................................................... 23
3. Configuration ............................................................................................................................ 25
3.1. Programmatic configuration .............................................................................................. 25
3.2. Obtaining a SessionFactory ............................................................................................... 25
3.3. JDBC connections ............................................................................................................ 26
3.4. Optional configuration properties ...................................................................................... 27
3.4.1. SQL Dialects ......................................................................................................... 33
3.4.2. Outer Join Fetching ............................................................................................... 34
3.4.3. Binary Streams ...................................................................................................... 34
3.4.4. Second-level and query cache ................................................................................. 34
3.4.5. Query Language Substitution ................................................................................. 34
3.4.6. Hibernate statistics ................................................................................................ 34
3.5. Logging ........................................................................................................................... 34
3.6. Implementing a NamingStrategy ....................................................................................... 35
3.7. XML configuration file ..................................................................................................... 36
3.8. J2EE Application Server integration .................................................................................. 37
3.8.1. Transaction strategy configuration .......................................................................... 37
3.8.2. JNDI-bound SessionFactory ................................................................................... 38
3.8.3. Current Session context management with JTA ....................................................... 39
3.8.4. JMX deployment ................................................................................................... 39
4. Persistent Classes ...................................................................................................................... 41

Hibernate 3.2.7 ii

HIBERNATE - Relational Persistence for Idiomatic Java

4.1. A simple POJO example ................................................................................................... 41
4.1.1. Implement a no-argument constructor ..................................................................... 42
4.1.2. Provide an identifier property (optional) .................................................................. 42
4.1.3. Prefer non-final classes (optional) ........................................................................... 42
4.1.4. Declare accessors and mutators for persistent fields (optional) .................................. 43
4.2. Implementing inheritance ................................................................................................. 43
4.3. Implementing equals() and hashCode() .............................................................................. 43
4.4. Dynamic models .............................................................................................................. 44
4.5. Tuplizers ......................................................................................................................... 46
4.6. EntityNameResolvers ....................................................................................................... 47
5. Basic O/R Mapping ................................................................................................................... 50
5.1. Mapping declaration ......................................................................................................... 50
5.1.1. Doctype ................................................................................................................ 51
5.1.1.1. EntityResolver ............................................................................................ 51
5.1.2. hibernate-mapping ................................................................................................. 52
5.1.3. class ..................................................................................................................... 52
5.1.4. id .......................................................................................................................... 55
5.1.4.1. Generator ................................................................................................... 55
5.1.4.2. Hi/lo algorithm ........................................................................................... 56
5.1.4.3. UUID algorithm ......................................................................................... 57
5.1.4.4. Identity columns and sequences ................................................................... 57
5.1.4.5. Assigned identifiers .................................................................................... 57
5.1.4.6. Primary keys assigned by triggers ................................................................ 58
5.1.5. Enhanced identifier generators ............................................................................... 58
5.1.6. Identifier generator optimization ............................................................................. 59
5.1.7. composite-id ......................................................................................................... 59
5.1.8. discriminator ......................................................................................................... 60
5.1.9. version (optional) .................................................................................................. 61
5.1.10. timestamp (optional) ............................................................................................ 61
5.1.11. property .............................................................................................................. 62
5.1.12. many-to-one ........................................................................................................ 64
5.1.13. one-to-one ........................................................................................................... 65
5.1.14. natural-id ............................................................................................................ 67
5.1.15. component, dynamic-component .......................................................................... 67
5.1.16. properties ............................................................................................................ 68
5.1.17. subclass .............................................................................................................. 69
5.1.18. joined-subclass .................................................................................................... 69
5.1.19. union-subclass ..................................................................................................... 70
5.1.20. join ..................................................................................................................... 71
5.1.21. key ..................................................................................................................... 72
5.1.22. column and formula elements ............................................................................... 72
5.1.23. import ................................................................................................................. 73
5.1.24. any ..................................................................................................................... 73
5.2. Hibernate Types ............................................................................................................... 74
5.2.1. Entities and values ................................................................................................. 74
5.2.2. Basic value types ................................................................................................... 75
5.2.3. Custom value types ............................................................................................... 76
5.3. Mapping a class more than once ........................................................................................ 77
5.4. SQL quoted identifiers ...................................................................................................... 77
5.5. Metadata alternatives ........................................................................................................ 78
5.5.1. Using XDoclet markup .......................................................................................... 78
5.5.2. Using JDK 5.0 Annotations .................................................................................... 79

Hibernate 3.2.7 iii

HIBERNATE - Relational Persistence for Idiomatic Java

5.6. Generated Properties ........................................................................................................ 80
5.7. Auxiliary Database Objects ............................................................................................... 80
6. Collection Mapping ................................................................................................................... 82
6.1. Persistent collections ........................................................................................................ 82
6.2. Collection mappings ......................................................................................................... 82
6.2.1. Collection foreign keys .......................................................................................... 84
6.2.2. Collection elements ............................................................................................... 84
6.2.3. Indexed collections ................................................................................................ 84
6.2.4. Collections of values and many-to-many associations .............................................. 85
6.2.5. One-to-many associations ...................................................................................... 87
6.3. Advanced collection mappings .......................................................................................... 87
6.3.1. Sorted collections .................................................................................................. 87
6.3.2. Bidirectional associations ....................................................................................... 88
6.3.3. Bidirectional associations with indexed collections .................................................. 89
6.3.4. Ternary associations .............................................................................................. 90
6.3.5. Using an <idbag> .................................................................................................. 91
6.4. Collection examples ......................................................................................................... 91
7. Association Mappings ............................................................................................................... 94
7.1. Introduction ..................................................................................................................... 94
7.2. Unidirectional associations ............................................................................................... 94
7.2.1. many to one .......................................................................................................... 94
7.2.2. one to one ............................................................................................................. 94
7.2.3. one to many .......................................................................................................... 95
7.3. Unidirectional associations with join tables ........................................................................ 96
7.3.1. one to many .......................................................................................................... 96
7.3.2. many to one .......................................................................................................... 96
7.3.3. one to one ............................................................................................................. 97
7.3.4. many to many ....................................................................................................... 97
7.4. Bidirectional associations ................................................................................................. 97
7.4.1. one to many / many to one ..................................................................................... 98
7.4.2. one to one ............................................................................................................. 98
7.5. Bidirectional associations with join tables .......................................................................... 99
7.5.1. one to many / many to one ..................................................................................... 99
7.5.2. one to one ........................................................................................................... 100
7.5.3. many to many ..................................................................................................... 101
7.6. More complex association mappings ............................................................................... 101
8. Component Mapping .............................................................................................................. 103
8.1. Dependent objects .......................................................................................................... 103
8.2. Collections of dependent objects ..................................................................................... 104
8.3. Components as Map indices ............................................................................................ 105
8.4. Components as composite identifiers ............................................................................... 105
8.5. Dynamic components ..................................................................................................... 107
9. Inheritance Mapping ............................................................................................................... 108
9.1. The Three Strategies ....................................................................................................... 108
9.1.1. Table per class hierarchy ...................................................................................... 108
9.1.2. Table per subclass ............................................................................................... 109
9.1.3. Table per subclass, using a discriminator ............................................................... 109
9.1.4. Mixing table per class hierarchy with table per subclass ......................................... 110
9.1.5. Table per concrete class ....................................................................................... 110
9.1.6. Table per concrete class, using implicit polymorphism ........................................... 111
9.1.7. Mixing implicit polymorphism with other inheritance mappings ............................. 112
9.2. Limitations .................................................................................................................... 112

Hibernate 3.2.7 iv

....................................................................................... 132 11.............................................................................1...............2............................. 133 11.......................5............... Hibernate object states ..................2..........................................1......................................................7....................................................9.............. Replicating object between two different datastores ....4.............................................................................1............2..... Criteria queries ....................................... DML-style operations .................................4... 122 10....... Optimistic concurrency control ........2....4...... Loading an object ................4........6.......................................... 116 10...............8.............................................................. 136 11. Hibernate declarative security .................................2......................... 135 11..............1........................6........ Session and transaction scopes ......................................................................... Using JTA .................. Querying .........1...................................... Scalar results ............. 124 10... Connection Release Modes ...................................1... Interceptors ... 130 11.... Customizing automatic versioning ................... 121 10....................................................................................4.............................................................................3.................................................. 117 10...............................Relational Persistence for Idiomatic Java 10........ 114 10.........4............................................................ HQL: The Hibernate Query Language ........................3.................................................2..... Queries that return tuples ......3...................10.....................1.......................................3................ 144 13.............................. 140 12.....4.4.. 131 11........................4..... 135 11............ HIBERNATE .................................................3........................................3...... 136 11......5...4..... Pagination .................................................................................1.........................................4............................................................................... 134 11............... 117 10........ Automatic state detection .................................................4..............3...................... 143 13.........4..........12.. Bind parameters .............................. Making objects persistent ....................................... 127 11........2............................................... 139 12.......1........... Pessimistic Locking .......................................................5......... 147 Hibernate 3......4......................................................................................................... Exception handling .................4.............................. Batch updates ...1.......................... 119 10............. Executing queries .... 120 10... Deleting persistent objects ................................................3. Batch processing ................................................. 127 11.....................2........................ 137 12..........................................................4....................................... 122 10..................................... 134 11.................................................. 143 13..................................3................................ 120 10.......................... 125 11...................................4............ Long conversations ... Modifying detached objects .......4........ 123 10.................. 117 10....................................................... Event system ..........1..................................................................................1........................................... 118 10........................... Modifying persistent objects ...................... Flushing the Session ............... 144 14.........................................................3............................................................................................................................................................1........ 130 11.....1...................2.................................2....... 128 11................................................... Externalizing named queries ..3.................................. Batch inserts ............................. 119 10.............. 127 11...................................1.....................................................7 v ... Application version checking .................................... 118 10......................................... 139 12........... Database transaction demarcation .................................................................................................... Non-managed environment ...................... The StatelessSession interface ..................................2......1.. Transaction timeout ....................... 114 10........... Filtering collections ........... Working with objects ............. Interceptors and events ..... 117 10. 116 10........................ 133 11.........................................2........4. Using metadata ................... 141 13................................................................1...........1...........3............... Considering object identity ......... Iterating results ............................... Queries in native SQL ...................3.......................................... Detached objects and automatic versioning ................................................................2............2.................................................. 120 10.............. 115 10.............11...................................................1.......... Unit of work .................7.................................. Extended session and automatic versioning ............. Transitive persistence ............... 123 10.................1.................... 143 13........................................... 114 10........... Scrollable iteration .... Transactions And Concurrency .. 129 11................................................................................................ Common issues ..................

..... 164 15............................................................................................6............................................11............. 163 15..................2............1.........................12................. 161 15.............. Components .....2................ 173 16.......................... Filtering data ... Using stored procedures for querying ........... 174 16.............................. 160 15........................................................................2...................................................................................5.... Forms of join syntax ............13...................... The select clause ...........................1...... Custom SQL for loading ........8..... Using return-property to explicitly specify column/alias names ......................... 162 15..........................................................................3......................... 161 15............................................................................................15....................................... Bulk update and delete ............................... Detached queries and subqueries ...... Scalar queries ..................................4.....4......................5..............2......... Queries by natural identifier ...........................2........ 175 17...2.................................................................. 158 14............4.........................................................2............................................6.................. Creating a Criteria instance ......................................................... 165 16........................................................ update and delete ...................... 179 18............................................................... XML mapping metadata ..............3....................................................6....................................... Refering to identifier property ... 163 15............... 156 14............................1...............9...................................... 180 Hibernate 3................. 147 14............. 167 16..............1..................................... Projections..........9...... 176 17............................................. 172 16........................................................ 178 18...................7 vi . The order by clause ..2.......................................................................................18.........7.................1............................................................. Specifying XML and class mapping together ............................................................................. 149 14............ 170 16.....................................................................1.................................................................... 178 18......2........................ Hibernate filters ....................................................................................................1........ 161 15........................ 159 14..................................... 147 14......................................................................................................... Subqueries ............ 152 14..................................... 155 14........ 170 16......... XML Mapping .................... Custom SQL for create...............1...............1.................. 178 18....................................................................................................................................................................... Dynamic association fetching ............... Criteria Queries .......................................1............... 171 16.3....................... 156 14.................................16....... Native SQL .................................................................................... Handling associations and collections ......................... Narrowing the result set ....................... Rules/limitations for using stored procedures ................... Case Sensitivity .............................................................................17........................................................................................................................... 165 15.................................... Working with XML data .... Specifying only an XML mapping .. 168 16.................................................. The where clause ............10............. 168 16........................ 178 18.............................1....................... 149 14...8....3... Alias and property references ................................. Returning non-managed entities ...................................... 176 18............. HQL examples ................... The group by clause ...........................................................................1..........Relational Persistence for Idiomatic Java 14...........................................1.......................................3...................................... Associations ............................ Ordering the results .. Expressions ....... HIBERNATE ..................................................................... 170 16....... Returning multiple entities .. 150 14.................5........................................ 147 14............4....................................................................14.......................1. Named SQL queries ....................2.............. Manipulating XML data ......... 155 14...........................1................................. 151 14............................... 162 15.................... 167 16.............. Aggregate functions ...................................................................... Tips & Tricks .........1............................................ Row value constructor syntax ... 149 14........................................... Using a SQLQuery ............1........... 167 16..... aggregation and grouping ................ Handling inheritance .......................................................................................................................................................... 173 16......................2.................................1. The from clause .......... 169 16................ Entity queries .......7...........................4.............. 151 14.................. Example queries ............................................. 158 14....... Parameters .......2................ Polymorphic queries ............................ 168 16............7........................................1............1....................... Associations and joins .................................................

........ One shot delete ...............................................................2......5.................... 192 19................... idbags and sets are the most efficient collections to update ........6....... 195 20............... 183 19...... 193 19..........5................................................................................................................................ HIBERNATE .................. Single-ended association proxies ............3........................................ 185 19..............................5............. Example: Weblog Application .......................................................................... Author/Work ..................... Miscellaneous example mappings . 188 19.................................. 202 21...5..........................3...3........................................................7............................................................ 189 19..............1........................................................... The Query Cache ............................................... Working with lazy associations ............................ 198 20.............. maps.........5. 186 19.................................. Strategy: read only .............. Monitoring a SessionFactory .......................................................1....2.............................................4......................................................... Initializing collections and proxies ..........1..........................................................................................1...............1....................................................................... 215 23.....................6. Customer/Order/Product .... 184 19.................................................... 203 21..... Strategy: read/write ......... Using Ant for incremental schema updates ................2....1.............. Using Ant ................. 191 19............................ Bidirectional one-to-many ............................ Cascades and unsaved-value ........................... "Typed" one-to-one association ................................................ 202 21................... Bags and lists are the most efficient inverse collections ..........2................................................. 189 19............................................................... Employer/Employee ................................................................................................................................................................................ Understanding Collection performance ........ 192 19.. Tuning fetch strategies .................................. 205 22......................... 189 19........................................... 193 19................................... 196 20................................................................................................................ Customizing the schema ...............................................................1........ 217 Hibernate 3............2...........5.......................................................................................................................................................................................... 194 19.............1...............................3....................................................1.........................................4...........1... 217 23............. Strategy: nonstrict read/write .2.............................................................. Metrics .....1............................2..................................... 190 19......2..................... Automatic schema generation ............................ Schema validation ...............2...........1.....1.................... Managing the caches .................. Cascading lifecycle .................6.................................3................... 199 20.............. 212 23....................... Running the tool ......... 204 21.....................4..............4..................1.................... 189 19.................................... 187 19............................................... 207 22............... Using lazy property fetching ......... Example: Parent/Child ............................. 201 21................. Using subselect fetching .................................1....... Fetching strategies ....8............... 196 20....................................5........................1... Using batch fetching ....................... 200 20....................... 194 19................. 193 19............... 187 19............................................................................................................. Monitoring performance ..........................................1.3......... Lists........................ The Second Level Cache . 199 20..........................................................6...7............4.......... Incremental schema updates ...................................... 190 19..........................1...................................................................... Properties ....................................4.......................................4.................................. 182 19..............................................................................................1.......... 182 19............ 208 23........ 213 23..... 183 19..2.. 206 22............ Example: Various Mappings .Relational Persistence for Idiomatic Java 19.................................1.....................................5.................................................... A note about collections .....................7 vii ........2.. Composite key example ............ Strategy: transactional .......................................4.. Improving performance .......... Cache mappings ........6.................................4........ Conclusion ....................1...............2...................................................2........................................ 206 22..........................................1............................. 200 20..1..... Hibernate Code ..... 212 23......3.................................. 196 20...........................2....... 200 20... Toolset Guide ..... Persistent Classes ................. 217 23............5........... 202 21.................................2...................... Using Ant for schema validation .................................. Hibernate Mappings .............................................................2............3...1................................................1............ Taxonomy .1.

................................. Associations on alternate keys ..........................................................4.....3.4................. Many-to-many with shared composite key attribute ..... 220 23.................... 219 23...............5..............7 viii .... Content based discrimination ....2............... 222 Hibernate 3...................... 220 24...............4..................... Best Practices .......Relational Persistence for Idiomatic Java 23............................................4.. HIBERNATE ...............................

Hibernate can certainly help you to remove or encapsulate vendor-specific SQL code and will help with the common task of result set translation from a tabular represent- ation to a graph of objects. The Community Area on the Hibernate website is a good resource for design patterns and various integra- tion solutions (Tomcat. 4. If you are interested in the development of Hibernate. type build eg. We also provide a JIRA issue track- ings system for bug reports and feature requests. please follow these steps: 1. Consider reading Hibernate in Action (http://www. Read Chapter 2. However.Preface Working with object-oriented software and a relational database can be cumbersome and time consuming in today's enterprise environments. 7.2. Hibernate is a Professional Open Source project and a critical component of the JBoss Enterprise Middleware System (JEMS) suite of products.hibernate.7 ix . EJB. Copy your JDBC driver to the lib/ directory and edit etc/hibernate. 6. JBoss AS. join the developer mailing list. 5. Hibernate may not be the best solution for data-centric applications that only use stored-procedures to implement the business logic in the database. Hibernate is an object/relational mapping tool for Java environments. specifying correct val- ues for your database. it contains a simple standalone application. examples.org and download the example application for Hibernate in Action. Hibernate 3. If you are interested in translating this documentation into your language. Introduction to Hibernate for a tutorial with step-by-step instructions. From a command prompt in the distribution directory.properties. Architecture to understand the environments where Hibernate can be used. Have a look at the eg/ directory in the Hibernate distribution. Commercial development support. Third party demos. If you have questions. 2.). Also visit http://caveatemptor. etc. use the user forum linked on the Hibernate website. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types). The source code for the tutorial is included in the distribution in the doc/reference/tutorial/ directory. but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC. production support. FAQs are answered on the Hibernate website. 3. or under Windows. contact us on the developer mailing list. Read Chapter 1. it is most useful with object-oriented domain models and business logic in the Java-based middle-tier. type ant eg (using Ant). Struts.com/bauer) if you need more help with application design or if you prefer a step-by-step tutorial.manning. and tutorials are linked on the Hibernate website. Hibernates goal is to relieve the developer from 95 percent of common data persistence related programming tasks.hibernate. If you are new to Hibernate and Object/Relational Mapping or even Java. and training for Hibernate is available through JBoss Inc. Use this reference documentation as your primary source of information. The term object/relational mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model with a SQL-based schema.org/SupportTraining/). (see http://www.

Chapter 1. Introduction to Hibernate

1.1. Preface
This chapter is an introductory tutorial for new users of Hibernate. We start with a simple command line applic-
ation using an in-memory database and develop it in easy to understand steps.

This tutorial is intended for new users of Hibernate but requires Java and SQL knowledge. It is based on a tu-
torial by Michael Gloegl, the third-party libraries we name are for JDK 1.4 and 5.0. You might need others for
JDK 1.3.

The source code for the tutorial is included in the distribution in the doc/reference/tutorial/ directory.

1.2. Part 1 - The first Hibernate Application
First, we'll create a simple console-based Hibernate application. We use an Java database (HSQL DB), so we
do not have to install any database server.

Let's assume we need a small database application that can store events we want to attend, and information
about the hosts of these events.

The first thing we do, is set up our development directory and put all the Java libraries we need into it. Down-
load the Hibernate distribution from the Hibernate website. Extract the package and place all required libraries
found in /lib into into the /lib directory of your new development working directory. It should look like this:

.
+lib
antlr.jar
cglib.jar
asm.jar
asm-attrs.jars
commons-collections.jar
commons-logging.jar
hibernate3.jar
jta.jar
dom4j.jar
log4j.jar

This is the minimum set of required libraries (note that we also copied hibernate3.jar, the main archive) for Hi-
bernate at the time of writing. The Hibernate release you are using might require more or less libraries. See the
README.txt file in the lib/ directory of the Hibernate distribution for more information about required and op-
tional third-party libraries. (Actually, Log4j is not required but preferred by many developers.)

Next we create a class that represents the event we want to store in database.

1.2.1. The first class

Our first persistent class is a simple JavaBean class with some properties:

package events;

import java.util.Date;

public class Event {

Hibernate 3.2.7 1

Introduction to Hibernate

private Long id;

private String title;
private Date date;

public Event() {}

public Long getId() {
return id;
}

private void setId(Long id) {
this.id = id;
}

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
}

You can see that this class uses standard JavaBean naming conventions for property getter and setter methods,
as well as private visibility for the fields. This is a recommended design - but not required. Hibernate can also
access fields directly, the benefit of accessor methods is robustness for refactoring. The no-argument construct-
or is required to instantiate an object of this class through reflection.

The id property holds a unique identifier value for a particular event. All persistent entity classes (there are less
important dependent classes as well) will need such an identifier property if we want to use the full feature set
of Hibernate. In fact, most applications (esp. web applications) need to distinguish objects by identifier, so you
should consider this a feature rather than a limitation. However, we usually don't manipulate the identity of an
object, hence the setter method should be private. Only Hibernate will assign identifiers when an object is
saved. You can see that Hibernate can access public, private, and protected accessor methods, as well as
(public, private, protected) fields directly. The choice is up to you and you can match it to fit your application
design.

The no-argument constructor is a requirement for all persistent classes; Hibernate has to create objects for you,
using Java Reflection. The constructor can be private, however, package visibility is required for runtime proxy
generation and efficient data retrieval without bytecode instrumentation.

Place this Java source file in a directory called src in the development folder, and in its correct package. The
directory should now look like this:

.
+lib
<Hibernate and third-party libraries>
+src
+events
Event.java

In the next step, we tell Hibernate about this persistent class.

Hibernate 3.2.7 2

Introduction to Hibernate

1.2.2. The mapping file

Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate map-
ping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what
columns in that table it should use.

The basic structure of a mapping file looks like this:

<?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>
[...]
</hibernate-mapping>

Note that the Hibernate DTD is very sophisticated. You can use it for auto-completion of XML mapping ele-
ments and attributes in your editor or IDE. You also should open up the DTD file in your text editor - it's the
easiest way to get an overview of all elements and attributes and to see the defaults, as well as some comments.
Note that Hibernate will not load the DTD file from the web, but first look it up from the classpath of the ap-
plication. The DTD file is included in hibernate3.jar as well as in the src/ directory of the Hibernate distri-
bution.

We will omit the DTD declaration in future examples to shorten the code. It is of course not optional.

Between the two hibernate-mapping tags, include a class element. All persistent entity classes (again, there
might be dependent classes later on, which are not first-class entities) need such a mapping, to a table in the
SQL database:

<hibernate-mapping>

<class name="events.Event" table="EVENTS">

</class>

</hibernate-mapping>

So far we told Hibernate how to persist and load object of class Event to the table EVENTS, each instance repres-
ented by a row in that table. Now we continue with a mapping of the unique identifier property to the tables
primary key. In addition, as we don't want to care about handling this identifier, we configure Hibernate's iden-
tifier generation strategy for a surrogate primary key column:

<hibernate-mapping>

<class name="events.Event" table="EVENTS">
<id name="id" column="EVENT_ID">
<generator class="native"/>
</id>
</class>

</hibernate-mapping>

The id element is the declaration of the identifer property, name="id" declares the name of the Java property -
Hibernate will use the getter and setter methods to access the property. The column attribute tells Hibernate
which column of the EVENTS table we use for this primary key. The nested generator element specifies the
identifier generation strategy, in this case we used native, which picks the best strategy depending on the con-
figured database (dialect). Hibernate supports database generated, globally unique, as well as application as-
signed identifiers (or any strategy you have written an extension for).

Hibernate 3.2.7 3

Introduction to Hibernate

Finally we include declarations for the persistent properties of the class in the mapping file. By default, no
properties of the class are considered persistent:

<hibernate-mapping>

<class name="events.Event" table="EVENTS">
<id name="id" column="EVENT_ID">
<generator class="native"/>
</id>
<property name="date" type="timestamp" column="EVENT_DATE"/>
<property name="title"/>
</class>

</hibernate-mapping>

Just as with the id element, the name attribute of the property element tells Hibernate which getter and setter
methods to use. So, in this case, Hibernate will look for getDate()/setDate(), as well as get-
Title()/setTitle().

Why does the date property mapping include the column attribute, but the title doesn't? Without the column
attribute Hibernate by default uses the property name as the column name. This works fine for title. However,
date is a reserved keyword in most database, so we better map it to a different name.

The next interesting thing is that the title mapping also lacks a type attribute. The types we declare and use in
the mapping files are not, as you might expect, Java data types. They are also not SQL database types. These
types are so called Hibernate mapping types, converters which can translate from Java to SQL data types and
vice versa. Again, Hibernate will try to determine the correct conversion and mapping type itself if the type at-
tribute is not present in the mapping. In some cases this automatic detection (using Reflection on the Java class)
might not have the default you expect or need. This is the case with the date property. Hibernate can't know if
the property (which is of java.util.Date) should map to a SQL date, timestamp, or time column. We pre-
serve full date and time information by mapping the property with a timestamp converter.

This mapping file should be saved as Event.hbm.xml, right in the directory next to the Event Java class source
file. The naming of mapping files can be arbitrary, however the hbm.xml suffix is a convention in the Hibernate
developer community. The directory structure should now look like this:

.
+lib
<Hibernate and third-party libraries>
+src
+events
Event.java
Event.hbm.xml

We continue with the main configuration of Hibernate.

1.2.3. Hibernate configuration

We now have a persistent class and its mapping file in place. It is time to configure Hibernate. Before we do
this, we will need a database. HSQL DB, a java-based SQL DBMS, can be downloaded from the HSQL DB
website. Actually, you only need the hsqldb.jar from this download. Place this file in the lib/ directory of the
development folder.

Create a directory called data in the root of the development directory - this is where HSQL DB will store its
data files. Now start the database by running java -classpath ../lib/hsqldb.jar org.hsqldb.Server in
this data directory. You can see it start up and bind to a TCP/IP socket, this is where our application will con-

Hibernate 3.2.7 4

username">sa</property> <property name="connection. The hbm2ddl.auto">create</property> <mapping resource="events/Event. The first four property elements contain the necessary configuration for the JDBC connection.sourceforge.Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-.dtd"> <hibernate-configuration> <session-factory> <!-.HSQLDialect</property> <!-. For Hibernate's configuration.NoCacheProvider</property> <!-.hbm.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3. The connections are made through a JDBC connection pool. Introduction to Hibernate nect later. we add the mapping file(s) for persistent classes to the configuration.7 5 . Most users prefer the XML configuration file: <?xml version='1.0.properties file. Hibernate is the layer in your application which connects to this database.provider_class">org.auto option turns on automatic generation of database schemas . we can use a simple hibernate. The Hibernate distribution contains several open source JDBC connection pooling tools.password"></property> <!-.Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-. and start HSQL DB again.cache. use several <session-factory> configurations. The dialect property element specifies the particular SQL variant Hibernate generates.pool_size">1</property> <!-.driver_class">org.jdbcDriver</property> <property name="connection. delete all files in the data/ directory.Drop and re-create the database schema on startup --> <property name="hbm2ddl. or even complete programmatic setup. usually in several configuration files (for easier startup). which we also have to configure.Disable the second-level cache --> <property name="cache.hibernate.2.directly into the database.net/hibernate-configuration-3.xml"/> </session-factory> </hibernate-configuration> Note that this XML configuration uses a different DTD. so it will end up in the root of the classpath.a global factory responsible for a particular database.cfg. Copy this file into the source directory. a slightly more sophisticated hibernate. If you want to start with a fresh database during this tutorial.JDBC connection pool (use the built-in) --> <property name="connection. Hibernate's automatic session man- agement for persistence contexts will come in handy as you will soon see.dialect.xml file. so it needs connection information. Note that you have to copy the required library into your classpath and use dif- ferent connection pooling settings if you want to use a production-quality third party JDBC pooling software.Database connection settings --> <property name="connection. Hibernate automatically Hibernate 3. We configure Hibernate's SessionFactory . Finally. This can of course also be turned off (by removing the config option) or redirected to a file with the help of the SchemaExport Ant task. but will use the Hibernate built-in connection pool for this tutorial.0//EN" "http://hibernate. If you have several databases. shutdown HSQL DB (press CTRL + C in the window).hibernate.url">jdbc:hsqldb:hsql://localhost</property> <property name="connection.hsqldb.SQL dialect --> <property name="dialect">org.

apache. A basic build file looks like this: <project name="hibernate-tutorial" default="compile"> <property name="sourcedir" value="${basedir}/src"/> <property name="targetdir" value="${basedir}/bin"/> <property name="librarydir" value="${basedir}/lib"/> <path id="libraries"> <fileset dir="${librarydir}"> <include name="*.cfg. You will need to have Ant installed . After you have installed Ant. Please refer to the Ant manual [http://ant.4.xml in the root of the classpath. 1.org/bindownload. Startup and helpers Hibernate 3.2.g. you should get this output: C:\hibernateTutorial\>ant Buildfile: build.org/manual/index.2.get it from the Ant download page [http://ant. on startup. It will be called build. copy-resources"> <javac srcdir="${sourcedir}" destdir="${targetdir}" classpathref="libraries"/> </target> <target name="copy-resources"> <copy todir="${targetdir}"> <fileset dir="${sourcedir}"> <exclude name="**/*.2. It will also copy all non-Java source files to the target directory.5.7 6 .jar to the classpath used for compilation. configuration and Hibernate mapping files.xml copy-resources: [copy] Copying 2 files to C:\hibernateTutorial\bin compile: [javac] Compiling 1 source file to C:\hibernateTutorial\bin BUILD SUCCESSFUL Total time: 1 second 1.java"/> </fileset> </copy> </target> </project> This will tell Ant to add all files in the lib directory ending with . we can start to create the build- file. How to install Ant will not be covered here.xml and placed directly in the development directory. e.jar"/> </fileset> </path> <target name="clean"> <delete dir="${targetdir}"/> <mkdir dir="${targetdir}"/> </target> <target name="compile" depends="clean. Building with Ant We'll now build the tutorial with Ant.apache. Introduction to Hibernate looks for a file called hibernate.cgi].html]. If you now run Ant.

throw new ExceptionInInitializerError(ex). A SessionFactory can open up new Session's.java hibernate.2. } catch (Throwable ex) { // Make sure you log the exception.xml +util HibernateUtil.println("Initial SessionFactory creation failed. Let's have a look at the implementation: package util.Hibernate uses commons logging and leaves you the choice between Log4j and JDK 1.xml." + ex).cfg.hibernate. the SessionFactory is a thread-safe global object. If you give the SessionFactory a name in your configuration file.hibernate. +lib <Hibernate and third-party libraries> +src +events Event.cfg. To avoid this code completely you could also use JMX deployment and let the JMX- capable container instantiate and bind a HibernateService to JNDI.xml sessionFactory = new Configuration().*. Hibernate will in fact try to bind it to JNDI after it has been built. These advanced options are discussed in the Hibernate reference documentation.err. } } public static SessionFactory getSessionFactory() { return sessionFactory.configure(). We have to startup Hibernate. Introduction to Hibernate It's time to load and store some Event objects. static { try { // Create the SessionFactory from hibernate. but first we have to complete the setup with some infrastructure code. This startup includes building a global SessionFactory object and to store it somewhere for easy access in application code. } } This class does not only produce the global SessionFactory in its static initializer (called once by the JVM when the class is loaded). public class HibernateUtil { private static final SessionFactory sessionFactory. in a package next to events: .cfg. We finally need to configure a logging system . A Session represents a single-threaded unit of work.xml This should again compile without problems. import org. Place HibernateUtil. next to hibernate.*.java Event.buildSessionFactory(). We'll create a HibernateUtil helper class which takes care of startup and makes accessing a SessionFactory convenient. It might as well lookup the Ses- sionFactory from JNDI in an application server.java in the development source directory.properties from the Hibernate distribution (it's in the etc/ directory) to your src direct- ory.4 logging. Have a look at the example configuration and change the settings if you like Hibernate 3.7 7 . import org.xml +data build.hbm. Most developers prefer Log4j: copy log4j. instantiated once. but also hides the fact that it uses a static singleton.cfg. as it might be swallowed System.

What does sessionFactory. when a unit of work begins and when it ends.getCurrentSession().createAndStoreEvent("My Event". However. Let's have a look at the Session and Transaction-handling code before we run this. } HibernateUtil. The getCurrentSession() method always returns the "current" unit of work. For now we'll keep things simple and assume a one-to-one granularity between a Hibernate Session and a database transaction. 1. session. once you get hold of your SessionFactory (easy thanks to HibernateUtil). import util.6.Session. if (args[0]. when the first call to getCurrentSession() is made.commit().setTitle(title).util.7 8 .getSessionFactory().xml? Hence.close(). A Session begins when it is first needed.beginTransaction(). } private void createAndStoreEvent(String title. theEvent. The tutorial infrastructure is complete .2. It is then bound Hibernate 3. By default. Introduction to Hibernate to have more verbose output. Remember that we switched the configuration option for this mechanism to "thread" in hibernate. We write an EventManager class with a main() meth- od: package events.hibernate. and hand it over to Hibernate.getCurrentSession() do? First. public class EventManager { public static void main(String[] args) { EventManager mgr = new EventManager().Date. you can call it as many times and anywhere you like. import java. theEvent. Date theDate) { Session session = HibernateUtil.save(theEvent). To shield our code from the actual underlying transac- tion system (in this case plain JDBC.getTransaction(). Hibernate now takes care of the SQL and ex- ecutes INSERTs on the database. Event theEvent = new Event().and we are ready to do some real work with Hibernate. } } We create a new Event object.2.cfg. but it could also run with JTA) we use the Transaction API that is avail- able on the Hibernate Session. session.getSessionFactory(). new Date()). only Hibernate startup message are shown on stdout. Loading and storing objects Finally. session. we can use Hibernate to load and store objects.setDate(theDate). this is not the full picture. import org.HibernateUtil. A Session is a single unit of work.equals("store")) { mgr. you also have to consider scope. the current unit of work is bound to the current Java thread that executes our application.

check your log4j. To run this first routine we have to add a callable target to the Ant build file: <target name="run" depends="compile"> <java fork="true" classname="events. Hibernate 3. i < events. Have a look at Chapter 11. ?. after compilation. We also skipped any error handling and rollback in the previous example. When the transaction ends. At the end you will find the following line: [java] Hibernate: insert into EVENTS (EVENT_DATE. we'll do this later in this tutorial).get(i). i++) { Event theEvent = (Event) events.equals("list")) { List events = mgr. you get a new Session and can start a new unit of work. The scope of a Hibernate Session is flexible but you should never design your application to use a new Hibernate Session for every database operation.properties. new Date()). This thread-bound programming model is the most popular way of using Hibernate. as it allows flexible layering of your code (transaction demarcation code can be separated from data access code.list(). Related to the unit of work scope.equals("store")) { mgr. List result = session.println("Event: " + theEvent.createQuery("from Event"). session.7 9 .getCurrentSession().size().listEvents().2.createAndStoreEvent("My Event". So even if you see it a few more times in the following (very trivial) examples.getTitle() + " Time: " + theEvent.EventManager" classpathref="libraries"> <classpath path="${targetdir}"/> <arg value="${action}"/> </java> </target> The value of the action argument is set on the command line when calling the target: C:\hibernateTutorial\>ant run -Daction=store You should see.getDate()). } } We also add a new listEvents() method: private List listEvents() { Session session = HibernateUtil. so we add an option to the main method: if (args[0]. Now we'd like to list stored events as well. should the Hibernate Session be used to execute one or several database op- erations? The above example uses one Session for one operation. for (int i = 0. either through commit or rollback. Transactions And Concurrency for more information about transaction handling and demarcation. } else if (args[0]. Hibernate starting up and. To see the val- ues bound as arguments. title.out. the question marks represent JDBC bind parameters. depending on your configuration.getSessionFactory(). the example is just not complex enough to show any other approach. lots of log out- put. or to reduce the verbosity of the log. consider session-per-operation an anti-pattern. System.beginTransaction(). This is pure coincidence. ?) This is the INSERT executed by Hibernate. Hibernate automatically unbinds the Session from the thread and closes it for you. EVENT_ID) values (?. Introduction to Hibernate by Hibernate to the current thread. A real (web) application is shown later in this tutorial. If you call getCurrentSession() again.

First we'll add people to our application. If you now call Ant with -Daction=list. of course.cfg.3. If you change the mapping and/or database schema. and subsequent application restarts will use this schema. public class Person { private Long id.2. You can create more complex queries with HQL. follow these steps: • Run ant run -Daction=store to store something into the database and.xml (don't forget the DTD reference at the top): <hibernate-mapping> <class name="events. • Now disable hbm2ddl by commenting out the property in your hibernate. private String firstname.3. private String lastname. then re- create all tables. public Person() {} // Accessor methods for all properties.Mapping associations We mapped a persistent entity class to a table.getTransaction(). 1. } What we do here is use an HQL (Hibernate Query Language) query to load all existing Event objects from the database. private int age. Note: Most new Hibernate users fail at this point and we see questions about Table not found error messages regularly. to generate the database schema before through hbm2ddl. to execute and test all of this. However. Hibernate will generate the appropriate SQL.xml file. but another run of hbm2ddl would drop everything you have stored . you should see the events you have stored so far.Person" table="PERSON"> Hibernate 3. return result. you have to re-enable hbm2ddl once again. if you follow the steps outlined above you will not have this problem. You can of course also call the store action a few times more.commit(). Introduction to Hibernate session. as hbm2ddl creates the database schema on the first run. of course. send it to the database and populate Event objects with the data.hbm.1. Mapping the Person class The first cut of the Person class is simple: package events. Usually you only leave it turned on in continous unit testing. when the SessionFactory is build". Now.7 10 . 1. private setter for 'id' } Create a new mapping file called Person.the create configuration setting actually translates into "drop all tables from the schema. and store a list of events they participate in. Part 2 . Let's build on this and add some class associations.

A unidirectional Set-based association We'll add a collection of events to the Person class. That way we can easily navigate to the events for a particu- lar person. a Set. Introduction to Hibernate <id name="id" column="PERSON_ID"> <generator class="native"/> </id> <property name="age"/> <property name="firstname"/> <property name="lastname"/> </class> </hibernate-mapping> Finally. } } Before we map this association. we call this a many-to-many association. multiplicity.3. We need a unidirectional. implemented with a Set.Event"/> </set> Hibernate 3.e. Hence. } public void setEvents(Set events) { this. persons can participate in events. You could always execute an explicit query to retrieve the participants for a particular event. and events have participants.hbm. The design questions we have to deal with are: directionality. 1. an- Event.getParticipants(). we could create another collection on the Event.2. because the collection will not contain duplicate elements and the ordering is not relevant for us. i. many-valued associations.xml"/> We'll now create an association between these two entities.events = events. add the new mapping to Hibernate's configuration: <mapping resource="events/Event. This is not necessary. Clearly. but what is clear from this discussion is the multiplicity of the association: "many" valued on both sides. This is a design choice left to you. We use a Java collection.xml"/> <mapping resource="events/Person.getEvents(). and collec- tion behavior. from a functional perspective.7 11 . Obviously. without executing an explicit query .Person" table="PERSON"> <id name="id" column="PERSON_ID"> <generator class="native"/> </id> <property name="age"/> <property name="firstname"/> <property name="lastname"/> <set name="events" table="PERSON_EVENT"> <key column="PERSON_ID"/> <many-to-many column="EVENT_ID" class="events.by calling aPerson. we use Hibernate's many-to-many mapping: <class name="events.hbm. Let's write the code for this in the Java classes and then map it: public class Person { private Set events = new HashSet(). think about the other side. if we want to be able to navigate it bi-directional. Or. public Set getEvents() { return events. we could just keep this unidirectional.2.

Working the association Let's bring some people and events together in a new method in EventManager: private void addPersonToEvent(Long personId. Introduction to Hibernate </class> Hibernate supports all kinds of collection mappings. eventId). session. when it is not in persistent state (if it was persistent before. This is called automatic dirty checking. For a many-to-many associ- ation (or n:m entity relationship).add(anEvent). is defined with the <key> element. Hibernate automatically detects that the collection has been modified and needs to be updated.getSessionFactory(). You also have to tell Hibernate the class of the objects in your collection (correct: the class on the other side of the collection of references). and you can also try it by modifying the name or the date property of any of your objects. usually only at the end of a unit of work.class. As long as they are in persistent state. Event anEvent = (Event) session. You might of course load person and event in different units of work. simply modify the collection using the normal collection methods.class.getCurrentSession(). a <set> being most common. As you can see. the unit of work ends with a commit (or rollback) of the database transaction .as defined by the thread configuration option for the CurrentSessionContext class. The identifier column name in the association. is called flushing. You can even modify a collection when it is detached: private void addPersonToEvent(Long personId.2. for the person's side. The process of synchronizing the memory state with the database. Person aPerson = (Person) session.commit(). Or you modify an object outside of a Session. The table name is configured with the table attribute of the set element. Hibernate 3.getEvents(). Long eventId) { Session session = HibernateUtil. that is. session. Long eventId) { Session session = HibernateUtil. aPerson.7 12 .getSessionFactory().e. Each row in this table represents a link between a person and an event. an association table is needed. The database schema for this mapping is therefore: _____________ __________________ | | | | _____________ | EVENTS | | PERSON_EVENT | | | |_____________| |__________________| | PERSON | | | | | |_____________| | *EVENT_ID | <--> | *EVENT_ID | | | | EVENT_DATE | | *PERSON_ID | <--> | *PERSON_ID | | TITLE | |__________________| | AGE | |_____________| | FIRSTNAME | | LASTNAME | |_____________| 1. personId).load(Event. In our code.getCurrentSession().3.load(Person.beginTransaction(). there is no explicit call to update() or save(). bound to a particular Hibernate Session (i. Hibernate monitors any changes and executes SQL in a write-behind fashion.3. } After loading a Person and an Event.getTransaction(). we call this state detached). they have been just loaded or saved in a unit of work). the column name for the event's side with the column attribute of the <many-to-many>.

mgr. session2.addPersonToEvent(personId.getSessionFactory(). session2.beginTransaction(). but it's an important concept you can design into your own application. In- stances of these types don't have their own identity. two entities. 1. Person aPerson = (Person) session .id = :pid") .createAndStorePerson("Foo".commit(). You can also design a collection of value types. complete this exercise by adding a new action to the EventManager's main method and call it from the command line. Well. and their instances depend on a particular entity. Address or MonetaryAmount.beginTransaction().println("Added person " + personId + " to event " + eventId).out. // Reattachment of aPerson session2. System. there are other classes and types in a typical model. nor are they shared between entities (two persons don't ref- erence the same firstname object. new Date()). like an int or a String.commit().class. // End of first unit of work aPerson. We want to store email addresses.createAndStoreEvent("My Event". so any modifications you made to it while detached can be saved to the database. eventId).7 13 .4. This includes any modifications (additions/deletions) you made to a collection of that entity object.createQuery("select p from Person p left join fetch p.load(Event. public Set getEmailAddresses() { return emailAddresses. and the collection is again a Set: private Set emailAddresses = new HashSet(). you could say it binds it to a new unit of work. but you can also write dependent classes yourself. this is not much use in our current situation. We call these classes value types. If you need the identifiers of a person and an event . even if they have the same first name).setParameter("pid". Some you have already seen. usually "less important". for example.update(aPerson).equals("addpersontoevent")) { Long eventId = mgr. Collection of values We add a collection of value typed objects to the Person entity. but looks almost the same in Java. // Eager fetch the collection so we can use it detached Event anEvent = (Event) session. session. As mentioned earli- er.2. so the type we use is String. // aPerson (and its collection) is detached // Begin second unit of work Session session2 = HibernateUtil. value types can not only be found in the JDK (in fact.add(anEvent). Introduction to Hibernate session.uniqueResult(). This is conceptually very different from a collection of refer- ences to other entities.getTransaction(). eventId).events where p. in a Hibernate application all JDK classes are considered value types). For now.getCurrentSession().getTransaction(). } Hibernate 3. Long personId = mgr. } The call to update makes a detached object persistent again.the save() method returns it (you might have to modify some of the previous methods to return that identifier): else if (args[0]. This was an example of an association between two equally important classes.getEvents(). "Bar"). Of course.3. personId) .

The column attribute in the element element defines the column name where the String values will actu- ally be stored. session.add(emailAddress).3.getTransaction().load(Person. } The mapping of this Set: <set name="emailAddresses" table="PERSON_EMAIL_ADDR"> <key column="PERSON_ID"/> <element type="string" column="EMAIL_ADDR"/> </set> The difference compared with the earlier mapping is the element part. Once again. personId). just like we did before by linking persons and events.2. You can now try and add elements to this collection.beginTransaction(). session. This also implies that there can't be duplicate email addresses per person.class. // The getEmailAddresses() might trigger a lazy load of the collection aPerson. Bi-directional associations Hibernate 3. } This time we didnt' use a fetch query to initialize the collection. using both columns.getEmailAddresses(). but a collection of elements of type String (the lowercase name tells you it's a Hibernate mapping type/converter). String emailAddress) { Session session = HibernateUtil. the call to its getter method will trigger an additional select to initialize it. Hence.7 14 . 1. Have a look at the updated schema: _____________ __________________ | | | | _____________ | EVENTS | | PERSON_EVENT | | | ___________________ |_____________| |__________________| | PERSON | | | | | | | |_____________| | PERSON_EMAIL_ADDR | | *EVENT_ID | <--> | *EVENT_ID | | | |___________________| | EVENT_DATE | | *PERSON_ID | <--> | *PERSON_ID | <--> | *PERSON_ID | | TITLE | |__________________| | AGE | | *EMAIL_ADDR | |_____________| | FIRSTNAME | |___________________| | LASTNAME | |_____________| You can see that the primary key of the collection table is in fact a composite key. which is exactly the semantics we need for a set in Java.emailAddresses = emailAddresses.5. It's the same code in Java: private void addEmailToPerson(Long personId.getSessionFactory(). so we can add an element to it. Person aPerson = (Person) session. which tells Hibernate that the collection does not contain references to another entity. Monitor the SQL log and try to optimize this with an eager fetch.commit().getCurrentSession(). the table attribute of the set element determ- ines the table name for the collection. The key element defines the foreign-key column name in the collection table. Introduction to Hibernate public void setEmailAddresses(Set emailAddresses) { this.

Working bi-directional links First. What this means is that Hibernate should take the other side .g. The most important addition here is the in- verse="true" attribute in the set element of the Event's collection mapping. Of course.data can be viewed and retrieved in any possible way. keep in mind that Hibernate does not affect normal Java semantics.3. } public void removeFromEvent(Event event) { this. } protected void setEvents(Set events) { this. } public void addToEvent(Event event) { this.add(event).Person"/> </set> As you see. if we want to make this link working bi-directional.remove(event).hbm. in Person: protected Set getEvents() { return events. the database schema doesn't change. we have to do the same on the other side .events = events. 1. obviously.participants = participants. This will be a lot easier to understand once you see how the bi- directional link between our two entities is created . add a collection of participants to the Event Event class: private Set participants = new HashSet(). This "setting the link on both sides" is absolutely necessary and you should never forget doing it. So. we still have many-to-many multipli- city. } public void setParticipants(Set participants) { this. e.adding a Person reference to the collection in an Event.6. <set name="participants" table="PERSON_EVENT" inverse="true"> <key column="EVENT_ID"/> <many-to-many column="PERSON_ID" class="events.remove(this).2. } Now map this side of the association too. so it doesn't need anything like a navigation direction .getEvents(). these are normal set mappings in both mapping documents. } Hibernate 3. How did we create a link between a Person and an Event in the unidirectional example? We added an instance of Event to the collection of event references.add(this). Many developers program defensive and create a link management methods to correctly set both sides.getParticipants().7 15 .making the association between person and event work from both sides in Java.xml. event. First. A relational database is more flexible than a network programming language. of an instance of Person.getEvents().getParticipants(). in Event. public Set getParticipants() { return participants. Introduction to Hibernate Next we are going to map a bi-directional association . Notice that the column names in key and many-to-many are swapped in both mapping documents.the Person class .when it needs to find out in- formation about the link between the two. event.

We now write an EventManagerServlet. This servlet can list all events stored in the database. and for Java. 1.commit().4. What about the inverse mapping attribute? For you. but prevents everybody else from messing with the collections directly (well. try { // Begin unit of work HibernateUtil. Let's turn this into a small web application. in the events package: package events.7 16 .getSessionFactory() . Making one side of the association inverse tells Hibernate to basically ignore it. Hibernate however doesn't have enough information to correctly ar- range SQL INSERT and UPDATE statements (to avoid constraint violations).this allows classes in the same pack- age and subclasses to still access the methods.getTransaction(). // Process request and render page. Writing the basic servlet Create a new class in your source directory. IOException { SimpleDateFormat dateFormatter = new SimpleDateFormat("dd. Introduction to Hibernate Notice that the get and set methods for the collection are now protected . However. some common patterns are useful. In a one-to-many association it has to be the many-side. hence.getCurrentSession(). } catch (Exception ex) { HibernateUtil. You should probably do the same with the collection on the other side. Part 3 .getTransaction(). the method we implement is doGet(): protected void doGet(HttpServletRequest request..1. 1.2. } Hibernate 3. there is no difference. throw new ServletException(ex).getCurrentSession(). and needs some help to handle bi- directional associations properly. // End unit of work HibernateUtil. and it provides an HTML form to enter new events.yyyy"). That's all that is necessary for Hibernate to work out all of the issues when transformation a directional navigation model to a SQL database schema. to consider it a mirror of the other side.beginTransaction().. // Imports public class EventManagerServlet extends HttpServlet { // Servlet code } The servlet handles HTTP GET requests only.4. HttpServletResponse response) throws ServletException.MM.getSessionFactory() .getSessionFactory() . The rules you have to remem- ber are straightforward: All bi-directional associations need one side as inverse. in many-to-many association you can pick either side. almost).rollback(). a bi-directional link is simply a matter of set- ting the references on both sides correctly.getCurrentSession().The EventManager web application A Hibernate web application uses Session and Transaction almost like a standalone application.

equals(request.getParameter("eventDate"). called Open Session in View—you'll need it as soon as you consider rendering your view in JSP. this coding style with a mix of Java and HTML would not scale in a more complex application—keep in mind that we are only illustrating basic Hibernate concepts in this tutorial. dateFormatter). out. Introduction to Hibernate } The pattern we are applying here is called session-per-request.parse(eventDate)).flush(). // Write HTML footer out.println("<html><head><title>Event Manager</title></head><body>"). Granted. Do not use a new Hibernate Session for every database operation. Use one Hibernate Session that is scoped to the whole request. an HTML form for event entry and a list of all events in the database are printed.12. Inside this page.</i></b>"). The first method is trivial and only outputs HTML: private void printEventForm(PrintWriter out) { out. so that it is automatically bound to the current Java thread. If any problem occured during pro- cessing or rendering. Use getCurrentSession().2009): <input name='eventDate' length='10'/><br/>"). not in a servlet.println("<b><i>Added event. the possible actions of the request are processed and the response HTML is rendered. out. Then a database transaction is started—all data access as to occur inside a transaction.println("<b><i>Please enter event title and date. Processing and rendering Let's implement the processing of the request and rendering of the page. dateFormatter.2. if ( "". This completes the session-per-request pattern. // Handle actions if ( "store". out.equals(eventDate) ) { out.println("</body></html>").println("Title: <input name='eventTitle' length='50'/><br/>"). out.getParameter("eventTitle").println("Date (e. no matter if data is read or written (we don't use the auto-commit mode in applications). 24. } else { createAndStoreEvent(eventTitle.println("<form>").println("<input type='submit' name='action' value='store'/>").g. out. out.7 17 .</i></b>"). The code prints an HTML header and a footer. } } // Print page printEventForm(out).getWriter().2. Finally.close().getParameter("action")) ) { String eventTitle = request. 1. When a request hits the servlet. the unit of work ends when processing and rendering is complete. out. See the Hibernate website and Wiki for more information about this pattern. Next. out. an exception will be thrown and the database transaction rolled back. String eventDate = request.4.println("<h2>Add new event:</h2>").equals(eventTitle) || "". a new Hibernate Session is opened through the first call to getCurrentSession() on the SessionFactory. We'll get to that part soon. Hibernate 3. listEvents(out. // Write HTML header PrintWriter out = response. Instead of the transaction demarcation code in every servlet you could also write a servlet filter.

println("</table>"). See the Hibernate Wiki for more examples. the store action is dispatched to the createAndStoreEvent() method.createCriteria(Event. This gives you the freedom to layer your code and access the SessionFactory in any way you like.iterator(). HibernateUtil.) { Event event = (Event) it.xml"> <lib dir="${librarydir}"> <exclude name="jsdk*.class).getDate()) + "</td>"). 1. which also uses the Session of the current thread: protected void createAndStoreEvent(String title. out.getCurrentSession(). As earlier in the standalone application. Add the following Ant target to your build. out. Hibernate can automatically bind these ojects to the current thread of execution.println("</form>"). It packages all libraries and Hibernate 3.println("<th>Event date</th>"). theEvent.jar"/> </lib> <classes dir="${targetdir}"/> </war> </target> This target creates a file called hibernate-tutorial.4.2. out. out. Date theDate) { Event theEvent = new Event().getCurrentSession(). the servlet is complete.7 18 .3. } out. for (Iterator it = result.format(event.println("<h2>Events in database:</h2>"). out. Usually you'd use a more sophisticated design and move the data access code into data access objects (the DAO pattern). } } Finally. Introduction to Hibernate out.setDate(theDate).println("<table border='1'>").println("<th>Event title</th>"). a WAR.setTitle(title). A request to the servlet will be processed in a single Session and Transac- tion. out. } That's it.size() > 0) { out.println("</tr>"). theEvent.getTitle() + "</td>").println("</tr>").println("<td>" + event.getSessionFactory() .hasNext().save(theEvent).next().list(). Deploying and testing To deploy this application you have to create a web archive. it.getSessionFactory() . out. out. out. if (result.println("<td>" + dateFormatter.println("<tr>"). SimpleDateFormat dateFormatter) { List result = HibernateUtil.println("<tr>").war in your project directory. } The listEvents() method uses the Hibernate Session bound to the current thread to execute a query: private void listEvents(PrintWriter out.war" webxml="web.xml: <target name="war" depends="compile"> <war destfile="hibernate-tutorial.

fetch performance (Chapter 19.war file into your Tomcat webapp directory. Introduction to Hibernate the web.com/xml/ns/j2ee/web-app_2_4. 1. Summary This tutorial covered the basics of writing a simple standalone Hibernate application and a small web applica- tion. Make sure you watch the Tomcat log to see Hi- bernate initialize when the first request hits your servlet (the static initializer in HibernateUtil is called) and to get the detailed output if any exceptions occurs.sun. Transactions And Concurrency).sun.w3.0" encoding="UTF-8"?> <web-app version="2.5. If you don't have Tomcat installed. This is the Java servlet development kit. “Querying”).sun. get it from the Sun website and copy it to your library directory.most asked are transactional processing (Chapter 11. Don't forget to check the Hibernate website for more (specialized) tutorials.EventManagerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Event Manager</servlet-name> <url-pattern>/eventmanager</url-pattern> </servlet-mapping> </web-app> Before you compile and deploy the web application. Once deployed and Tomcat is running. If you already feel confident with Hibernate. if you don't have this library already. Hibernate 3. download it and follow the installation in- structions.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java. which is expected in the base directory of your project: <?xml version="1. continue browsing through the reference documentation table of contents for topics you find interesting . Working with objects) and the query features (Section 10. note that an additional library is required: jsdk. You don't have to change any Tomcat configuration to deploy this application though. it will be only used for compliation and excluded from the WAR package.4" xmlns="http://java.com/xml/ns/j2ee" xmlns:xsi="http://www. Improving performance). or the usage of the API (Chapter 10.7 19 . access the application at ht- tp://localhost:8080/hibernate-tutorial/eventmanager.xs <servlet> <servlet-name>Event Manager</servlet-name> <servlet-class>events.xml descriptor.com/xml/ns/j2ee http://java.2. To build and deploy call ant war in your project directory and copy the hibernate-tutorial.jar. However.4.

Overview A (very) high-level view of the Hibernate architecture: This diagram shows Hibernate using the database and configuration data to provide persistence services (and persistent objects) to the application. Architecture 2. The "lite" architecture has the application provide its own JDBC connections and manage its own transactions.Chapter 2. Unfortunately. Hibernate is flexible and supports several approaches.7 20 . We will show the two extremes. We would like to show a more detailed view of the runtime architecture.2. This approach uses a minimal subset of Hibernate's APIs: The "full cream" architecture abstracts the application away from the underlying JDBC/JTA APIs and lets Hi- Hibernate 3.1.

Transient and detached objects and collections Instances of persistent classes that are not currently associated with a Session. They may have been instan- tiated by the application and not (yet) persisted or they may have been instantiated by a closed Session.g.or cluster-level. However. Abstracts application from underlying JDBC. Factory for Transaction.hibernate. short-lived object used by the application to specify atomic units of work. Persistent objects and collections Short-lived.SessionFactory) A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider. at a process. A Session might span several Transactions in some cases.hibernate. single threaded objects containing persistent state and business function. either using the underlying API or Trans- action. Architecture bernate take care of the details. JTA or CORBA transaction. the only special thing about them is that they are currently associated with (exactly one) Session.2. Session (org. directly as data transfer objects to and from presentation). transaction demarcation. is never optional! Hibernate 3. Wraps a JDBC connection. short-lived object representing a conversation between the application and the persistent store. Might hold an optional (second-level) cache of data that is reusable between transactions. These might be ordin- ary JavaBeans/POJOs.7 21 . Holds a mandatory (first-level) cache of per- sistent objects. As soon as the Session is closed. Transaction (org.hibernate. Heres some definitions of the objects in the diagrams: SessionFactory (org.Session) A single-threaded. they will be detached and free to use in any application layer (e.Transaction) (Optional) A single-threaded. used when navigating the object graph or looking up objects by identifier.

Hibernate guarantees that persistent identity is equivalent to Java identity (in-memory location of the object). Hibernate makes no guarantees about the relationship between persistent identity and Java identity. this becomes the job of a JBoss EJB interceptor. a corresponding row in the database. You call the HibernateContext to access a Session.7 22 . On JBoss AS. 2. Given a "lite" architecture. You also don't have to worry about transaction demarcation in your code any- more (unless you'd like to write a portable persistence layer of course. org. perhaps. It has no persistent identity (primary key value). Architecture ConnectionProvider (org. JMX Integration JMX is the J2EE standard for management of Java components. which are defined with respect to a persistence context. detached The instance was once associated with a persistence context. but can be extended/implemented by the developer. Extension Interfaces Hibernate offers many optional extension interfaces you can implement to customize the behavior of your persistence layer. See the API documentation for details.2. or the instance was serialized to another process. Instance states An instance of a persistent classes may be in one of three different states. For an example how to deploy Hibernate as a JMX service on the JBoss Application Server. but that context was closed. We provide an MBean implementation in the distribution. please see the JBoss User Guide. 2. Hibernate 3. Not exposed to application.hibernate. Not exposed to the application.3. persistent The instance is currently associated with a persistence context.ConnectionProvider) (Optional) A factory for (and pool of) JDBC connections. The Hibernate Session object is the persistence context: transient The instance is not. you also get these benefits if you deploy using JMX: • Session Management: The Hibernate Session's lifecycle can be automatically bound to the scope of a JTA transaction.hibernate. but can be extended/ implemented by the developer. a corrsponding row in the data- base. and has never been associated with any persistence context. For detached instances. use the optional Hibernate Transac- tion API for this). For a particular persistence context. TransactionFactory (org.jmx. It has a persistent identity (primary key value) and.HibernateService. This means you no longer have to manually open and close the Session.2.TransactionFactory) (Optional) A factory for Transaction instances. the application bypasses the Transaction/TransactionFactory and/or Connec- tionProvider APIs to talk to JTA or JDBC directly. Hibernate may be managed via a JMX stand- ard service.connection.hibernate. perhaps. Abstracts application from underlying Data- source or DriverManager. It has a persistent identity and.

See Section 3. you are responsible to bind and unbind a Session instance with static methods on this class. JBoss will automatically detect all mapping files in your HAR file.2. you still have to name all your mapping files in the deployment descriptor. the JTA-based contextual sessions is all you should ever need to use. • org.4. JCA Support Hibernate may also be configured as a JCA connector. However. the processing behind SessionFactory. The processing here is exactly the same as in the older JTA-only approach.context. and different contexts define different scopes to the notion of current. it Hibernate 3. across applications the definition of what constitutes a con- text is typically different. Initially. It defines a single method. See the Javadocs for de- tails. • org.0. Contextual Sessions Most applications using Hibernate need some form of "contextual" sessions. • org. where a given session is in effect throughout the scope of a given context. Out-of-the-box. See the Javadocs for the org.1. it supports all the usual configuration options of a Hibernate Ses- sionFactory. However. “Hibernate stat- istics”.hibernate.JTASessionContext .context. To that end.getCurrentSession() method. Architecture • HAR deployment: Usually you deploy the Hibernate JMX service using a JBoss service deployment descriptor (in an EAR and/or SAR file). Starting with version 3. Hibernate added the SessionFactory. However. Again.current sessions are tracked by thread of execution. see the Javadocs for details. 2.getCurrentSession() is now pluggable. as of version 3.6.ManagedSessionContext .CurrentSessionContext) and a new config- uration parameter (hibernate. most (if not all) applications should be using JTA transaction management whether or not they are deployed into a J2EE container.hibernate.0 tended to utilize either home-grown ThreadLocal-based contextual ses- sions.1. Consult the JBoss AS user guide for more information about these options.context. 2. Please see the website for more details. Applications using Hibernate prior to version 3. given the maturity of the numerous stand-alone JTA Transaction- Manager implementations out there.hibernate.hibernate. Hibernate comes with three implementations of this in- terface.current sessions are tracked and scoped by a JTA transac- tion. Based on that.context. Please note that Hibernate JCA support is still considered experimental. where the JTA transaction defined both the scope and context of a current session.CurrentSessionContext interface for a detailed discussion of its contract. If you decide to use the optional HAR deployment.5.hibernate. or utilized third-party frameworks (such as Spring or Pico) which provided proxy/interception-based contextual sessions.4.current sessions are tracked by thread of execu- tion. currentSession().context. by which the implementation is responsible for tracking the current contextual session. However. helper classes such as HibernateUtil.ThreadLocalSessionContext . Another feature available as a JMX service are runtime Hibernate statistics. this assumed usage of JTA transactions. a new extension interface (org.7 23 . The Hibernate team maintains that.current_session_context_class) have been added to allow pluggability of the scope and context of defining current sessions.

"jta". there are two corresponding short names. Architecture does never open.current_session_context_class configuration parameter defines which org.transaction. If you execute in an EJB container that supports CMT. however.hibernate.JTASessionContext. Refer to Chapter 11. The first two implementations provide a "one session . The hibernate. or close a Session.2. transaction boundaries are defined declaratively and you don't need any transaction or session demarca- tion operations in your code. Hibernate will use the org. Typically. use the JTA interfaces to demarcate transactions. Hibernate 3.TransactionManagerLookup is configured. you are adviced to use the Hibernate Transaction API to hide the underlying transaction system from your code.context. Note that for backwards compatibility.hibernate.7 24 . If you use programatic transaction demarcation in plain JSE without JTA. "thread". the value of this parameter would just name the implementation class to use. also known and used as session-per-request. The beginning and end of a Hibernate session is defined by the dura- tion of a database transaction. Transactions And Concurrency for more information and code examples. flush. If you use JTA.one database transaction" programming model. if this config param is not set but a org.hibernate. for the three out-of-the-box implementations. and "managed".context.CurrentSessionContext implementation should be used.

hibernate.xml (discussed later).addClass(org. 4. If the mapping files are in the classpath.connection.Item.hibernate.Configuration represents an entire set of mappings of an application's Java types to an SQL database. "org. Set System properties using java -Dproperty=value.Bid. Configuration Because Hibernate is designed to operate in many different environments.xml").setProperty("hibernate.util. and let Hibernate find the mapping docu- ment for you: Configuration cfg = new Configuration() .class). This is not the only way to pass configuration properties to Hibernate.hibernate.Item.properties is the easiest approach if you want to get started quickly. most have sensible default values and Hibernate is distributed with an example hibernate.auction. The Configuration is used to build an (immutable) SessionFactory. This approach eliminates any hardcoded filenames.Chapter 3. Place hibernate.MySQLInnoDBDialect") . The map- pings are compiled from various XML mapping files.hibernate.hbm.dialect".dialect.setProperty("hibernate.properties in a root directory of the classpath. A Configuration also allows you to specify configuration properties: Configuration cfg = new Configuration() . Just put the example file in your classpath and customize it.auction. An alternative (sometimes better) way is to specify the mapped class.1.xml") .class) .setProperty("hibernate.cfg.Properties to Configuration.auction.hbm. Obtaining a SessionFactory When all mappings have been parsed by the Configuration.order_updates". use addResource(): Configuration cfg = new Configuration() . Include <property> elements in hibernate. Programmatic configuration An instance of org. 3. to be discarded once a SessionFactory is created.7 25 . the application must obtain a factory for Session Hibernate 3. Fortunately. The various options include: 1.Bid. You may obtain a Configuration instance by instantiating it directly and specifying XML mapping docu- ments. Then Hibernate will look for mapping files named /org/hibernate/auction/Item. 3.2.hibernate. there are a large number of configur- ation parameters. hibernate.auction. "true").2.addClass(org. 3. 2.class) .datasource".cfg.addClass(org.hbm. The Configuration is intended as a startup-time object.properties file in etc/ that shows the various options. "java:comp/env/jdbc/test") .hbm. Pass an instance of java.setProperties().xml in the classpath.xml and / org/hibernate/auction/Bid.addResource("Bid.class) .addClass(org.hibernate.addResource("Item.

Configuration

instances. This factory is intended to be shared by all application threads:

SessionFactory sessions = cfg.buildSessionFactory();

Hibernate does allow your application to instantiate more than one SessionFactory. This is useful if you are
using more than one database.

3.3. JDBC connections
Usually, you want to have the SessionFactory create and pool JDBC connections for you. If you take this ap-
proach, opening a Session is as simple as:

Session session = sessions.openSession(); // open a new Session

As soon as you do something that requires access to the database, a JDBC connection will be obtained from the
pool.

For this to work, we need to pass some JDBC connection properties to Hibernate. All Hibernate property names
and semantics are defined on the class org.hibernate.cfg.Environment. We will now describe the most im-
portant settings for JDBC connection configuration.

Hibernate will obtain (and pool) connections using java.sql.DriverManager if you set the following proper-
ties:

Table 3.1. Hibernate JDBC Properties

Property name Purpose

hibernate.connection.driver_class jdbc driver class

hibernate.connection.url jdbc URL

hibernate.connection.username database user

hibernate.connection.password database user password

hibernate.connection.pool_size maximum number of pooled connections

Hibernate's own connection pooling algorithm is however quite rudimentary. It is intended to help you get star-
ted and is not intended for use in a production system or even for performance testing. You should use a third
party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with
connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to
use C3P0.

C3P0 is an open source JDBC connection pool distributed along with Hibernate in the lib directory. Hibernate
will use its C3P0ConnectionProvider for connection pooling if you set hibernate.c3p0.* properties. If you'd
like to use Proxool refer to the packaged hibernate.properties and the Hibernate web site for more informa-
tion.

Here is an example hibernate.properties file for C3P0:

hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc:postgresql://localhost/mydatabase
hibernate.connection.username = myuser
hibernate.connection.password = secret

Hibernate 3.2.7 26

Configuration

hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

For use inside an application server, you should almost always configure Hibernate to obtain connections from
an application server Datasource registered in JNDI. You'll need to set at least one of the following properties:

Table 3.2. Hibernate Datasource Properties

Propery name Purpose

hibernate.connection.datasource datasource JNDI name

hibernate.jndi.url URL of the JNDI provider (optional)

hibernate.jndi.class class of the JNDI InitialContextFactory (optional)

hibernate.connection.username database user (optional)

hibernate.connection.password database user password (optional)

Here's an example hibernate.properties file for an application server provided JNDI datasource:

hibernate.connection.datasource = java:/comp/env/jdbc/test
hibernate.transaction.factory_class = \
org.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class = \
org.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

JDBC connections obtained from a JNDI datasource will automatically participate in the container-managed
transactions of the application server.

Arbitrary connection properties may be given by prepending "hibernate.connnection" to the property name.
For example, you may specify a charSet using hibernate.connection.charSet.

You may define your own plugin strategy for obtaining JDBC connections by implementing the interface
org.hibernate.connection.ConnectionProvider. You may select a custom implementation by setting hi-
bernate.connection.provider_class.

3.4. Optional configuration properties
There are a number of other properties that control the behaviour of Hibernate at runtime. All are optional and
have reasonable default values.

Warning: some of these properties are "system-level" only. System-level properties can be set only via java -
Dproperty=value or hibernate.properties. They may not be set by the other techniques described above.

Table 3.3. Hibernate Configuration Properties

Property name Purpose

hibernate.dialect The classname of a Hibernate Dialect which allows

Hibernate 3.2.7 27

Configuration

Property name Purpose

Hibernate to generate SQL optimized for a particular
relational database.

eg. full.classname.of.Dialect

hibernate.show_sql Write all SQL statements to console. This is an al-
ternative to setting the log category
org.hibernate.SQL to debug.

eg. true | false

hibernate.format_sql Pretty print the SQL in the log and console.

eg. true | false

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

eg. SCHEMA_NAME

hibernate.default_catalog Qualify unqualified tablenames with the given cata-
log in generated SQL.

eg. CATALOG_NAME

hibernate.session_factory_name The SessionFactory will be automatically bound to
this name in JNDI after it has been created.

eg. jndi/composite/name

hibernate.max_fetch_depth Set a maximum "depth" for the outer join fetch tree
for single-ended associations (one-to-one, many-
to-one). A 0 disables default outer join fetching.

eg. recommended values between 0 and 3

hibernate.default_batch_fetch_size Set a default size for Hibernate batch fetching of as-
sociations.

eg. recommended values 4, 8, 16

hibernate.default_entity_mode Set a default mode for entity representation for all
sessions opened from this SessionFactory

dynamic-map, dom4j, pojo

hibernate.order_updates Force Hibernate to order SQL updates by the primary
key value of the items being updated. This will result
in fewer transaction deadlocks in highly concurrent
systems.

eg. true | false

hibernate.generate_statistics If enabled, Hibernate will collect statistics useful for
performance tuning.

eg. true | false

Hibernate 3.2.7 28

Configuration

Property name Purpose

hibernate.use_identifer_rollback If enabled, generated identifier properties will be re-
set to default values when objects are deleted.

eg. true | false

hibernate.use_sql_comments If turned on, Hibernate will generate comments inside
the SQL, for easier debugging, defaults to false.

eg. true | false

Table 3.4. Hibernate JDBC and Connection Properties

Property name Purpose

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

hibernate.jdbc.batch_size A non-zero value enables use of JDBC2 batch up-
dates by Hibernate.

eg. recommended values between 5 and 30

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

eg. true | false

hibernate.jdbc.factory_class Select a custom Batcher. Most applications will not
need this configuration property.

eg. classname.of.Batcher

hibernate.jdbc.use_scrollable_resultset Enables use of JDBC2 scrollable resultsets by Hi-
bernate. This property is only necessary when using
user supplied JDBC connections, Hibernate uses con-
nection metadata otherwise.

eg. true | false

hibernate.jdbc.use_streams_for_binary Use streams when writing/reading binary or serial-
izable types to/from JDBC (system-level property).

eg. true | false

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

Hibernate 3.2.7 29

4.5. For a non-JTA connection. By default.provider_class The classname of a custom CacheProvider.isolation Set the JDBC transaction isolation level. true | false hibernate. hibernate.<propertyName> Pass the JDBC property propertyName to DriverMan- ager.connection.sql. a JDBC connection is held until the session is explicitly closed or disconnected. 2. “Contextual Sessions” hibernate.Connection for meaningful values but note that most databases do not support all isolation levels.5.7 30 . Check java.getCurrentSession. the CurrentSessionCon- text implementation configured for use controls the connection release mode for those Sessions. Hibernate 3. eg.<propertyName> Pass the property propertyName to the JNDI Ini- tialContextFactory.connection. Configuration Property name Purpose eg.connection. eg.release_mode Specify when Hibernate should release JDBC con- nections. See Sec- tion 2. you should use after_statement to aggressively release connections after every JDBC call.cache. it often makes sense to release the connection at the end of each transaction. 8 hibernate. auto (default) | on_close | after_transaction | after_statement Note that this setting only affects Sessions returned from SessionFactory. true|false hibernate. by using after_transaction.openSession. eg. Table 3.provider_class The classname of a custom ConnectionProvider which provides JDBC connections to Hibernate. Hibernate Cache Properties Property name Purpose hibernate.getConnection().connection.2.connection.of. 1.autocommit Enables autocommit for JDBC pooled connections (not recommended).ConnectionProvider hibernate. classname. For Sessions obtained through SessionFact- ory. eg.jndi. auto will choose after_statement for the JTA and CMT transaction strategies and after_transaction for the JDBC transaction strategy. For an application server JTA datasource.

use_structured_entries Forces Hibernate to store data in the second-level cache in a more human-friendly format. This setting is most useful for clustered caches and. true|false hibernate. de- faults to the built-in StandardQueryCache.query_cache_factory The classname of a custom QueryCache interface. eg. eg. classname.of.6.TransactionFactory jta.cache. classname.transaction. Hibernate Transaction Properties Property name Purpose hibernate. is enabled by default for clustered cache implementa- tions.use_query_cache Enable the query cache.re- quired when JVM-level caching is enabled or when using hilo generator in a JTA environment.cache.cache.cache.use_minimal_puts Optimize second-level cache operation to minimize writes. eg.use_second_level_cache May be used to completely disable the second level cache. prefix hibernate. true|false Table 3. eg.UserTransaction A JNDI name used by JTATransactionFactory to obtain the JTA UserTransaction from the applica- tion server. in Hibernate3.CacheProvider hibernate.region_prefix A prefix to use for second-level cache region names.of. classname. at the cost of more frequent reads. Configuration Property name Purpose eg.cache.cache.factory_class The classname of a TransactionFactory to use with Hibernate Transaction API (defaults to JDBCTrans- actionFactory). eg.of. jndi/composite/name hibernate. which is enabled by default for classes which specify a <cache> mapping.manager_lookup_class The classname of a TransactionManagerLookup . true|false hibernate. eg.transaction.2. Hibernate 3. eg. true|false hibernate.QueryCache hibernate. individual queries still have to be set cachable.7 31 . eg.

for example). With create-drop.ClassicQueryTransla torFactory hibernate.hibernate. eg.cglib.substitutions Mapping from tokens in Hibernate queries to SQL tokens (tokens might be function or literal names. “Contextual Sessions”.ASTQueryTranslatorFacto ry or org.5.hql.transaction. eg.classic. eg.hbm2ddl. Reflection can sometimes be useful when troubleshooting. eg.TransactionManagerLookup hibernate. Configuration Property name Purpose eg. validate | update | create | create-drop hibernate. Built-in and automatic session context management is preferred.5. true | false hibernate.hql. classname. see Section 2.7.auto_close_session If enabled. See Section 2.flush_before_completion If enabled.factory_class Chooses the HQL parser implementation. eg.query. Miscellaneous Properties Property name Purpose hibernate.current_session_context_class Supply a (custom) strategy for the scoping of the "cur- rent" Session.2. “Contextual Sessions”.query.use_reflection_optimizer Enables use of CGLIB instead of runtime reflection (System-level property).5.hibernate.ast. see Section 2. Built-in and utomatic session context management is preferred.7 32 . hqlLiteral=SQL_LITERAL. the database schema will be dropped when the SessionFactory is closed explicitly. note that Hibernate al- ways requires CGLIB even if you turn off the optim- Hibernate 3. jta | thread | managed | custom.transaction. eg. the session will be automatically closed during the after completion phase of the transaction.Class hibernate. org. true | false Table 3.auto Automatically validate or export schema DDL to the database when the SessionFactory is created. “Contextual Ses- sions” for more information about the built-in strategies.of. the session will be automatically flushed during the before completion phase of the transaction. hqlFunc- tion=SQLFUNC hibernate.

saving you the effort of specifying them manually.dialect.7 33 .MySQLDialect MySQL with InnoDB org.SQLServerDialect SAP DB org.hibernate. SQL Dialects You should always set the hibernate.2.hibernate.Oracle8iDialect Oracle 9i org.MckoiDialect Interbase org.dialect property to the correct org.dialect.SAPDBDialect Informix org.1.dialect. eg.hibernate.hibernate. Hibernate will use sensible defaults for some of the other prop- erties listed above.hibernate.4.hibernate.dialect.dialect.dialect.hibernate.hibernate.hibernate.hibernate.SybaseDialect Sybase Anywhere org.DB2390Dialect PostgreSQL org.dialect.ProgressDialect Mckoi SQL org.HSQLDialect Ingres org.dialect.DB2400Dialect DB2 OS390 org.dialect.hibernate.PostgreSQLDialect MySQL org.hibernate.hibernate.hibernate.PointbaseDialect FrontBase org.dialect.dialect.dialect.dialect.dialect.MySQLInnoDBDialect MySQL with MyISAM org.Oracle9iDialect Oracle 10g org.SybaseAnywhereDialect Microsoft SQL Server org. You can not set this property in hibern- ate.hibernate.Dialect sub- class for your database.MySQLMyISAMDialect Oracle 8i org.IngresDialect Progress org.dialect.dialect.dialect.hibernate.FrontbaseDialect Hibernate 3.hibernate.DB2Dialect DB2 AS/400 org.dialect.dialect) RDBMS Dialect DB2 org.dialect. true | false 3. If you specify a dialect. Table 3.hibernate.hibernate.hibernate. Configuration Property name Purpose izer.hibernate.dialect. Hibernate SQL Dialects (hibernate.dialect.xml.dialect.hibernate.InformixDialect HypersonicSQL org.cfg.Oracle10gDialect Sybase org.hibernate.8.dialect.InterbaseDialect Pointbase org.

See Section 19. Logging Hibernate 3.2.1. See the Section 19. you should enable hibernate.4.jdbc. Binary Streams Oracle limits the size of byte arrays that may be passed to/from its JDBC driver.3. 3.cache allow you to use a process or cluster scoped second-level cache system with Hibernate. Outer join fetching may be disabled globally by setting the property hibernate. This is a system-level setting only. Outer Join Fetching If your database supports ANSI.getStatistics(). Hibernate can even be configured to ex- pose these statistics via JMX.hibernate. If you wish to use large in- stances of binary or serializable type.query. Outer join fetching allows a whole graph of objects connected by many-to-one. Hibernate statistics If you enable hibernate.use_streams_for_binary.stats for more informa- tion.query. Hibernate will expose a number of metrics that are useful when tuning a running system via SessionFactory. 3. A set- ting of 1 or higher enables outer join fetching for one-to-one and many-to-one associations which have been mapped with fetch="join".4. Query Language Substitution You may define new Hibernate query tokens using hibernate. 3.FirebirdDialect 3. false=0 would cause the tokens true and false to be translated to integer literals in the generated SQL.5. hibernate.4.dialect.substitutions toLowercase=LOWER would allow you to rename the SQL LOWER function.7 34 . outer join fetching will often increase per- formance by limiting the number of round trips to and from the database (at the cost of possibly more work per- formed by the database itself).substitutions true=1. one-to-many. 3. Configuration RDBMS Dialect Firebird org.query. “Fetching strategies” for more information.substitutions.6.max_fetch_depth to 0.2.hibernate. Oracle or Sybase style outer joins. Second-level and query cache The properties prefixed by hibernate.4. “The Second Level Cache” for more details. many-to-many and one-to-one associations to be retrieved in a single SQL SELECT. 3.generate_statistics.2. For example: hibernate. Read the Javadoc of the interfaces in org.5.4.4.

We strongly recommend that you familiarize yourself with Hibernate's log messages.properties file in your classpath.hibernate.addFile("Item. The default strategy used by Hibernate is quite minimal.hibernate.AST Log HQL and SQL ASTs during query parsing org.hibernate. without making it unreadable.xml") Hibernate 3. alternatively. or.cache Log all second-level cache activity org.hibernate.hql.7 35 .secure Log all JAAS authorization requests org.SQL.org.cfg. To use Log4j you will need to place a log4j.apache. the property hibernate.hibernate.hbm2dd Log all SQL DDL statements as they are executed l org. A lot of work has been put into making the Hibernate log as detailed as possible. for ex- ample).hibernate.4 or above). It is an essential troubleshooting device.hibernate. Implementing a NamingStrategy The interface org.6. you should almost always work with debug enabled for the cat- egory org. You may provide rules for automatically generating database identifiers from Java identifiers or for processing "logical" column and table names given in the mapping file into "physical" table and column names.type Log all JDBC parameters org.SQL Log all SQL DML statements as they are executed org. The most interesting log categories are the following: Table 3. 3.tool.pretty Log the state of all entities (max 20 entities) associated with the session at flush time org.setNamingStrategy(ImprovedNamingStrategy. an example properties file is distributed with Hibernate in the src/ directory.INSTANCE) .NamingStrategy allows you to specify a "naming standard" for database ob- jects and schema elements. Hibernate Log Categories Category Function org.jdbc Log all JDBC resource acquisition org.hbm.show_sql enabled. You may download Log4j from ht- tp://jakarta. Configuration Hibernate logs various events using Apache commons-logging.hibernate.transaction Log transaction related activity org. You may specify a different strategy by calling Configuration.ast.hibernate. This fea- ture helps reduce the verbosity of the mapping document. eliminating repetitive noise (TBL_ prefixes.9.hibernate Log everything (a lot of information.hibernate.4 logging (if running under JDK1. but very useful for troubleshooting) When developing applications with Hibernate. The commons-logging service will direct output to either Apache Log4j (if you include log4j.jar in your classpath) or JDK1.setNamingStrategy() before adding map- pings: SessionFactory sf = new Configuration() .2.hibernate.

hibernate.sourceforge. The XML configuration file is by default expected to be in the root o your CLASSPATH.buildSessionFactory(). Hibernate 3. Configuration .0. the advantage of this approach is the externalization of the mapping file names to configura- tion.Bid" usage="read-only"/> <collection-cache collection="org. org.hbm.bids" usage="read-write"/> </session-factory> </hibernate-configuration> As you can see.hibernate.dialect.cfg.xml.cfg.auction. Note that is your choice to use either hibernate.dtd"> <hibernate-configuration> <!-.hibernate.Item" usage="read-write"/> <class-cache class="org.7 36 .hibernate.xml"/> <!-. starting Hibernate is then as simple as SessionFactory sf = new Configuration(). The hibernate.xml is also more convenient once you have to tune the Hibernate cache.cfg. except for the above mentioned benefits of using the XML syntax. both are equivalent. XML configuration file An alternative approach to configuration is to specify a full configuration in a file named hibernate.buildSessionFactory(). to override properties.xml") .0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.a SessionFactory instance listed as /jndi/name --> <session-factory name="java:hibernate/SessionFactory"> <!-.datasource">java:/comp/env/jdbc/MyDB</property> <property name="dialect">org.hibernate.2.mapping files --> <mapping resource="org/hibernate/auction/Item.xml. 3.hbm. Here is an example: <?xml version='1.xml"/> <mapping resource="org/hibernate/auction/Bid.configure(). This file can be used as a replacement for the hibernate.net/hibernate-configuration-3.transaction.xml") . You can pick a different XML configuration file using SessionFactory sf = new Configuration() .cfg.buildSessionFactory(). if both are present.properties --> <property name="connection.7.auction.properties file or.UserTransaction">java:comp/UserTransaction</property> <!-.configure("catdb.factory_class"> org. With the XML configuration.MySQLDialect</property> <property name="show_sql">false</property> <property name="transaction.addFile("Bid.Item.ImprovedNamingStrategy is a built-in strategy that might be a useful starting point for some applications.hbm.cache settings --> <class-cache class="org.JTATransactionFactory </property> <property name="jta.cfg.auction.hibernate.properties or hibernate.

Depending on your environment.JTATransactionFactory delegates to container-managed transaction if an existing transaction is underway in this context (e. To keep your code portable between these two (and other) environments we recommend the optional Hibernate Transaction API. distributed transaction handling across several datasources. Configuration 3. If you run in a J2EE application server.JDBCTransactionFactory delegates to database (JDBC) transactions (default) org. through a connection pool.transaction. The container will startup your HibernateService. You have to specify a factory class for Transaction instances by setting the Hibernate configuration property hibern- ate. Let Hibernate take care of flushing and closing the Session when your JTA transaction completes. you can chose to deploy Hibernate as a managed MBean. • JTA Session binding: The Hibernate Session may be automatically bound to the scope of JTA transactions. 3. and ideally also take care of service dependencies (Datasource has to be available before Hibernate starts. Usually. EJB session bean method).hibernate.g. otherwise a new transaction is started and bean-managed transaction are used. Simply lookup the SessionFactory from JNDI and get the current Session. etc).g.transaction. a JTA compatible TransactionManager and a ResourceManager take care of transaction management (CMT).hibernate. J2EE Application Server integration Hibernate has the following integration points for J2EE infrastructure: • Container-managed datasources: Hibernate can use JDBC connections managed by the container and provided through JNDI. you might want to use bean-managed transactions and call the JTA API and UserTransaction when needed.factory_class.transaction. which wraps and hides the underlying system.hibernate.1.8. You may of course also demarcate transaction boundaries programatically (BMT) or you might want to use the optional Hibernate Transaction API for this to keep your code portable.aggressive_release to true if your application server shows "connection containment" ex- ceptions.7 37 . • Automatic JNDI binding: Hibernate can bind its SessionFactory to JNDI after startup. esp.transaction. you might have to set the configuration option hibern- ate. you may begin and end your transactions by call- ing the JDBC API. There are three standard (built-in) choices: org.8.2.connection. org. If you let Hibernate use JDBC directly. JBoss AS).CMTTransactionFactory delegates to container-managed JTA transactions Hibernate 3. Transaction strategy configuration The Hibernate Session API is independent of any transaction demarcation system in your architecture. • JMX deployment: If you have a JMX capable application server (e. Transaction demarcation is either declarative (CMT) or programmatic (BMT/UserTransaction). This saves you the one line startup code to build your SessionFactory from a Configuration.

hibernate.hibernate.hibernate.transaction.g. hibern- ate.hibernate. We recommend that you bind the SessionFactory to JNDI in a managend environment and use a static singleton otherwise.hibernate.transaction.7 38 . Hibernate 3. Configuration You may also define your own transaction strategies (for a CORBA transaction service.e. e. etc.getSessionFactory(). an EJB or any other class may obtain the SessionFactory using a JNDI lookup. Hibernate will automatically place the SessionFactory in JNDI after you call cfg.transaction. the SessionFactory will not be bound to JNDI. If they are not specified.transaction.jndi.transaction. we also recommend to hide the actual lookup code for a SessionFactory in a helper class.WebSphereExtendedJTATransactionLookup WebSphere 6 org.2.) When binding the SessionFactory to JNDI. JNDI-bound SessionFactory A JNDI bound Hibernate SessionFactory can simplify the lookup of the factory and the creation of new Ses- sions. (This is especially useful in environments with a read- only JNDI default implementation.class to instantiate an initial context. the second level cache. both simply use the same registry! If you wish to have the SessionFactory bound to a JNDI namespace.transaction. Hibernate will use the values of hibernate.transaction.8.hibernate. If this property is omitted.JOnASTransactionManagerLookup JOnAS org. specify a name (eg.hibernate.WeblogicTransactionManagerLookup Weblogic org. since J2EE does not standardize a single mech- anism: Table 3.hibernate.2. the default InitialContext will be used.JBossTransactionManagerLookup JBoss org. for example).transaction.WebSphereTransactionManagerLookup WebSphere org.session_factory_name. In an application server you have to specify how Hi- bernate should obtain a reference to the TransactionManager. such as HibernateUtil.OrionTransactionManagerLookup Orion org.transaction. unless you use JMX deployment with the HibernateService (discussed later). This means you will at least have this call in some startup code (or utility class) in your application.jndi. Note that such a class is also a convenient way to startup Hibernate—see chapter 1.hibernate.buildSessionFactory().transaction.url. java:hibernate/SessionFactory) using the property hibernate. If you use a JNDI SessionFactory. Some features in Hibernate (i. JTA TransactionManagers Transaction Factory Application Server org.JRun4TransactionManagerLookup JRun4 org. Note that this is not related to a JNDI bound Datasource.hibernate. Contextual Sessions with JTA.JOTMTransactionManagerLookup JOTM org.10.BESTransactionManagerLookup Borland ES 3.ResinTransactionManagerLookup Resin org. To shield your application code from these details.) require access to the JTA TransactionManager in a managed environment. Tomcat.

Here is an example jboss-service.Bind the Hibernate service to JNDI --> <attribute name="JndiName">java:/hibernate/SessionFactory</attribute> <!-. and aggressively release JDBC connections after each statement.JBossTransactionManagerLookup</attribute> <attribute name="FlushBeforeCompletionEnabled">true</attribute> <attribute name="AutoCloseSessionEnabled">true</attribute> <!-.8.transaction.hibernate. JMX deployment The line cfg.Transaction integration --> <attribute name="TransactionStrategy"> org.8.Logging --> <attribute name="ShowSqlEnabled">true</attribute> <!-.7 39 .Required services --> <depends>jboss.0"?> <server> <mbean code="org.2.xml for JBoss 4.x: <?xml version="1. The actual deployment and configuration is vendor specific. or (recommended for portable code) use the Hibernate Transaction API to set transaction boundaries.hbm. Using the "jta" session context. You can do this either in a static initializer block (like the one in HibernateUtil) or you deploy Hibernate as a managed service.transaction.dialect. one will be started and associated with that JTA transaction the first time you call sessionFactory. This allows the Sessions to be managed by the lifecycle of the JTA transaction to which it is associated.getCurrentSession().hibernate.jmx.HibernateService" name="jboss. If you run in an EJB container. such as JBoss AS.Second-level caching --> <attribute name="SecondLevelCacheEnabled">true</attribute> <attribute name="CacheProviderClass">org.5. “Contextual Sessions”. 3.hibernate.4. keeping user code clean of such management concerns.JTATransactionFactory</attribute> <attribute name="TransactionManagerLookupStrategy"> org.name=HibernateFactory"> <!-.hbm.EhCacheProvider</attribute> <attribute name="QueryCacheEnabled">true</attribute> <!-. See the discussion of Section 2. declarative transaction demarcation with CMT is preferred.name=HsqlDS</depends> <!-.jca:service=LocalTxCM.xml. Configuration 3. if there is no Hi- bernate Session associated with the current JTA transaction.HSQLDialect</attribute> <!-.HibernateService for deployment on an application server with JMX capabilities.Fetching options --> <attribute name="MaximumFetchDepth">5</attribute> <!-.hibernate.jca:service=RARDeployer</depends> <depends>jboss.Datasource settings --> <attribute name="Datasource">java:HsqlDS</attribute> <attribute name="Dialect">org. close after the transaction completes. Current Session context management with JTA The easiest way to handle Sessions and transactions is Hibernates automatic "current" Session management.jmx.jca:service=HibernateFactory.cache.buildSessionFactory() still has to be executed somewhere to get a SessionFactory into JNDI.3. Hibernate is distributed with org.hibernate.hibernate.auction/Category.Mapping files --> <attribute name="MapResources">auction/Item.0.xml</attribute> </mbean> Hibernate 3. The Sessions retrieved via getCur- rentSession() in "jta" context will be set to automatically flush before the transaction completes. Your code can either use JTA programmatically through UserTransac- tion.

You also need to package Hibernate. Your enterprise beans (usually session beans) may be kept in their own JAR file. Consult the JBoss AS documentation for more information about JMX service and EJB deployment. your compiled persistent classes.sar (service archive). but you may include this EJB JAR file in the main service archive to get a single (hot-)deployable unit. its required third-party libraries. Hibernate 3. Configuration </server> This file is deployed in a directory called META-INF and packaged in a JAR file with the extension . as well as your mapping files in the same archive.2.7 40 .

also known as the Plain Old Java Object (POJO) programming model.util. Hibernate works best if these classes follow some simple rules. import java. package eg. for example.an instance may instead be transient or detached. 4.7 41 . However. Hibernate3 assumes very little about the nature of your persistent objects. import java.2.Chapter 4. } public Long getId() { return id. private Cat mother. } public Color getColor() { return color.sex=sex.weight = weight. A simple POJO example Most Java applications require a persistent class representing felines. Persistent Classes Persistent classes are classes in an application that implement the entities of the business problem (e. Hibernate 3. } public float getWeight() { return weight. none of these rules are hard requirements.id=id.util.g. You may express a domain model in other ways: using trees of Map instances.1. } void setBirthdate(Date date) { birthdate = date. } public char getSex() { return sex.Set. private void setId(Long id) { this. private Set kittens = new HashSet(). Not all instances of a persistent class are considered to be in the persistent state . } void setSex(char sex) { this.color = color. private float weight. // identifier private Date birthdate. } void setColor(Color color) { this. Indeed. private int litterId. private Color color.Date. } public Date getBirthdate() { return birthdate. } void setWeight(float weight) { this. public class Cat { private Long id. Custom- er and Order in an E-commerce application). private char sex.

kittens = kittens.see Section 10.1. You can leave them off and let Hibernate keep track of object identi- fiers internally.7 42 . Persistent Classes } void setLitterId(int id) { this. (If your legacy database table has composite keys.setLitterId( kittens.mother = mother.merge() We recommend you declare consistently-named identifier properties on persistent classes.util. however.Date. } public Cat getMother() { return mother. In fact. any primitive "wrapper" type. } // addKitten not needed by Hibernate public void addKitten(Cat kitten) { kitten.) The identifier property is strictly optional. } } There are four main rules to follow here: 4. some functionality is available only to classes which declare an identifier property: • Transitive reattachment for detached objects (cascade update or cascade merge) . 4. you can even use a user-defined class with properties of these types . The property might have been called anything. } void setKittens(Set kittens) { this. All persistent classes must have a default constructor (which may be non- public) so that Hibernate can instantiate them using Constructor.litterId = id.2.newInstance(). and its type might have been any primitive type. non-primitive) type. We strongly recommend having a default constructor with at least package visibility for runtime proxy generation in Hibernate. “Transitive persistence” • Session. Prefer non-final classes (optional) Hibernate 3. } public int getLitterId() { return litterId. This property maps to the primary key column of a database table.2.1. Implement a no-argument constructor Cat has a no-argument constructor. We do not recommend this.3. } void setMother(Cat mother) { this.see the section on composite identifiers later.size() ).saveOrUpdate() • Session.add(kitten). kitten.setMother(this).lang. We further recom- mend that you use a nullable (ie.1.1.11. 4. kittens. } public Set getKittens() { return kittens.String or java. Provide an identifier property (optional) Cat has a property called id. java.

You may switch to direct field access for particular properties. package eg. we can't use that approach with generated iden- tifiers! Hibernate will only assign identifier values to objects that are persistent. The most obvious way is to implement equals()/hashCode() by comparing the identifier value of both objects. and recognizes method names of the form getFoo. Unfortunately. Persistent Classes A central feature of Hibernate. } } 4. both must be the same database row. or the imple- mentation of an interface that declares all public methods.which will limit your options for performance tuning. It inherits its identifier property from the superclass. We believe it is better to provide an indirection between the relational schema and internal data structures of the class. proxies. isFoo and setFoo.7 43 .Hibernate can persist a property with a default. You can persist final classes that do not implement an interface with Hibernate.2. 4. 4. a newly created instance will Hibernate 3. So as soon as we mix instances retrieved in different sessions. You should also avoid declaring public final methods on the non-final classes. Implementing inheritance A subclass must also observe the first and second rules. By default. if needed.name=name. } protected void setName(String name) { this. Declare accessors and mutators for persistent fields (optional) Cat declares accessor methods for all its persistent fields. they are therefore equal (if both are added to a Set.3. Hibernate persists JavaBeans style properties.2. Many other ORM tools directly persist instance vari- ables. If you want to use a class with a public final method. you must explicitly disable proxying by setting lazy="false". public String getName() { return name. depends upon the persistent class being either non-final. If the value is the same. Cat. but you won't be able to use proxies for lazy association fetching . we will only have one element in the Set). protected or private get / set pair.4. we must implement equals() and hashCode() if we wish to have meaningful semantics for Sets. public class DomesticCat extends Cat { private String name. Implementing equals() and hashCode() You have to override the equals() and hashCode() methods if you • intend to put instances of persistent classes in a Set (the recommended way to represent many-valued asso- ciations) and • intend to use reattachment of detached instances Hibernate guarantees equivalence of persistent identity (database row) and Java identity only inside a particular session scope. Properties need not be declared public .1.

“Considering object identity”)..equals( getMother() ) ) return false. Immutable or unique properties are usually good candidates for a business key. if ( !cat. an entity-name has to be declared instead of (or in addition to) a class name: <hibernate-mapping> <class entity-name="Customer"> <id name="id" type="long" column="ID"> <generator class="sequence"/> </id> <property name="name" Hibernate 3. but normal Java semantics of object identity and equality.1.. Persistent entities don't necessarily have to be represented as POJO classes or as JavaBean objects at runtime. Dynamic models Note that the following features are currently considered experimental and may change in the near future.2. saving it will assign an identifier value to the object. Hibernate also supports dynamic models (using Maps of Maps at runtime) and the representation of entities as DOM4J trees. Note that this is not a Hibernate issue. 4. return result.4.hashCode(). breaking the contract of the Set.getLitterId(). } } Note that a business key does not have to be as solid as a database primary key candidate (see Section 11. The following examples demonstrates the representation using Maps. } public int hashCode() { int result. We recommend implementing equals() and hashCode() using Business key equality. in the mapping file. only mapping files. Persistent Classes not have any identifier value! Furthermore.equals( getLitterId() ) ) return false. First. If equals() and hashCode() are based on the identifier value. you don't write persistent classes. the hash code would change. Hibernate works in normal POJO mode. You may set a default entity representation mode for a par- ticular SessionFactory using the default_entity_mode configuration option (see Table 3. “Hibernate Con- figuration Properties”. final Cat cat = (Cat) other.3. With this approach. if ( !(other instanceof Cat) ) return false. return true.getMother(). public boolean equals(Object other) { if (this == other) return true.3. if ( !cat.7 44 . See the Hibernate website for a full discussion of this problem. By default. result = 29 * result + getLitterId(). result = getMother(). if an instance is unsaved and currently in a Set. Business key equality means that the equals() method compares only the properties that form the business key. a key that would identify our instance in the real world (a natural candidate key): public class Cat { .

foobar. "David").save("Organization".put("name". david). s..7 45 .put("name".. // Save both s. david). david.getSession(EntityMode. foobar). you lose compile-time type checking and will very likely deal with many ex- ceptions at runtime. david. "Foobar Inc.beginTransaction(). foobar). Session s = openSession(). Hibernate 3. "David"). After setting the default entity mode to dynamic-map for the SessionFactory. we can at runtime work with Maps of Maps: Session s = openSession(). // Create a customer Map david = new HashMap(). the database schema can easily be normalized and sound.put("organization". dynamicSession. dynamicSession. s.save("Customer". // Create an organization Map foobar = new HashMap(). . allowing to add a proper domain model implementation on top later on.save("Customer".flush(). The advantages of a dynamic mapping are quick turnaround time for prototyping without the need for entity class implementation.MAP). However."). Transaction tx = s. tx.commit(). the target type of an associations may also be a dynamic entity instead of a POJO. // Link both david.put("name".close(). // Create a customer Map david = new HashMap(). Persistent Classes column="NAME" type="string"/> <property name="address" column="ADDRESS" type="string"/> <many-to-one name="organization" column="ORGANIZATION_ID" class="Organization"/> <bag name="orders" inverse="true" lazy="false" cascade="all"> <key column="CUSTOMER_ID"/> <one-to-many class="Order"/> </bag> </class> </hibernate-mapping> Note that even though associations are declared using target class names.2. Entity representation modes can also be set on a per Session basis: Session dynamicSession = pojoSession. Thanks to the Hibernate mapping.

hibernate.util.close() . For example. given that representation's org. XML Mapping.hibernate.Tuplizer. 4.. // Continue on pojoSession Please note that the call to getSession() using an EntityMode is on the Session API. then a tuplizer is the thing which knows how to create such a data structure and how to extract values from and inject values into such a data structure. Tuplizers org..hibernate. </class> </hibernate-mapping> public class CustomMapTuplizerImpl extends org.mapping.tuple.hibernate. the correpsonding tuplizer knows how create the POJO through its constructor and how to access the POJO properties using the defined property accessors. Persistent Classes dynamicSession. and also leave the transac- tion and connection handling to the primary unit of work. for the POJO entity mode. protected final Map generateMap() { Hibernate 3.DynamicMapEntityTuplizer { // override the buildInstantiator() method to plug in our custom map.Map implementation other than java.hibernate.tuple. or perhaps you need to define a dif- ferent proxy generation strategy than the one used by default...EntityTuplizer and org. not the SessionFactory. represented by the org. En- tityTuplizers are responsible for managing the above mentioned contracts in regards to entities. This means you don't have tocall flush() and close() on the secondary Session. More information about the XML representation capabilities can be found in Chapter 18. while Com- ponentTuplizers do the same for components.hibernate..EntityMode.. Perhaps you require that a java. transaction. Users may also plug in their own tuplizers. and its sub-interfaces. That way.other properties --> .tuple. There are two high-level types of Tuplizers. protected final Instantiator buildInstantiator( org.7 46 .PersistentClass mappingInfo) { return new CustomMapInstantiator( mappingInfo ).5.tuple. } private static final class CustomMapInstantiator extends org. the new Session shares the underlying JDBC connection. Going back to the example of our customer entity: <hibernate-mapping> <class entity-name="Customer"> <!-- Override the dynamic-map entity-mode tuplizer for the customer entity --> <tuplizer entity-mode="dynamic-map" class="CustomMapTuplizerImpl"/> <id name="id" type="long" column="ID"> <generator class="sequence"/> </id> <!-.ComponentTuplizer interfaces..hibernate. are responsible for managing a particular representa- tion of a piece of data. Tuplizers definitions are attached to the entity or component mapping they are meant to manage.HashMap be used while in the dynamic-map entity-mode.util.. If a given piece of data is thought of as a data structure.2. Both would be achieved by defining a custom tuplizer implementation.DynamicMapInstantitor { // override the generateMap() method to return our custom map.tuple. and other context information.

} else if ( "toString".entityName = entityName. Object[] args) throws Throwable { String methodName = method.hashCode() ).put( propertyName. The hibernate test suite has an example of this exact style of usage under the <package>org. One example might be using proxied interfaces as your domain model. } else if ( methodName. if ( methodName.hibernate. The interface defines a single method resolveEntityName which is passed the entity instance and is expected to return the appropriate entity name (null is allowed and would indicate that the resolver does not know how to resolve the entity name of the given entity instance).EntityNameResolver interface is a contract for resolving the entity name of a given entity instance. Serializable id) { this.equals( methodName ) ) { return new Integer( this.EntityNameResolver is going to be most useful in the case of dynamic models. } public Object invoke(Object proxy.test.substring( 3 ). } else if ( "hashCode". data. } } } 4.2. args[0] ). } return null. } } /** * */ public class ProxyHelper { Hibernate 3.get( "Id" ). return data. private HashMap data = new HashMap(). public DataProxyHandler(String entityName.substring( 3 ). Method method. } public HashMap getData() { return data.getName().7 47 .tuplizer2</package> .hibernate.startsWith( "get" ) ) { String propertyName = methodName. Generally speaking.hibernate. /** * A very trivial JDK Proxy InvocationHandler implementation where we proxy an interface as * the domain model and simply store persistent state in an internal Map.startsWith( "set" ) ) { String propertyName = methodName. EntityNameResolvers The org. Persistent Classes return new CustomMap(). an org.equals( methodName ) ) { return entityName + "#" + data. This is an extremely * trivial example meant only for illustration. } public String getEntityName() { return entityName. */ public final class DataProxyHandler implements InvocationHandler { private String entityName.get( propertyName ).6.put( "Id".dynamicentity. id ). Here is some of the code from that package for illustration. data.

isAssignableFrom( handler. } } return null. Hence the equals and hashCode impls */ public class MyEntityNameResolver implements EntityNameResolver { public static final MyEntityNameResolver INSTANCE = new MyEntityNameResolver().determineConcreteSubclassEntityName( entityInstance. return myHandler.lang.2. we return null if ( Proxy. implementing the getEntityNameResolvers method. public String resolveEntityName(Object entity) { return ProxyHelper. Persistent Classes public static String extractEntityName(Object object) { // Our custom java. so we simply extract it from there // if this represents one of our proxies. } // various other utility methods . factory )...isProxyClass( object. Since this particular impl can handle resolution for all of our entities we want to * take advantage of the fact that SessionFactoryImpl keeps these in a Set so that we only ever * have one instance registered. } public boolean equals(Object obj) { return getClass(). SessionFactoryImplementor String entityName = ProxyHelper. So keeping that number down * helps that process be as speedy as possible.hashCode(). * Hibernate must iterate over all the registered resolvers.extractEntityName( entity ).getClass() ) ) { DataProxyHandler myHandler = ( DataProxyHandler ) handler.getClass() ) ) { InvocationHandler handler = Proxy.getClass() ).EntityNameResolver users must either: 1. } public String determineConcreteSubclassEntityName(Object entityInstance.. } return entityName. if ( entityName == null ) { entityName = super.getInvocationHandler( object ).Proxy instances actually bundle // their appropriate entity name. when it comes time to resolve an entity name. * IMPL NOTE : An EntityNameResolver really defines a strategy for how entity names should be * resolved. Implement a custom Tuplizer.INSTANCE }.7 48 .class. Hibernate 3. } /** * The EntityNameResolver implementation. if ( DataProxyHandler.hibernate. } public int hashCode() { return getClass(). } . otherwise. } public EntityNameResolver[] getEntityNameResolvers() { return new EntityNameResolver[] { MyEntityNameResolver.. mappedEntity ).reflect. Why? Well. PersistentClass mappedEntity) { super( entityMetamodel.. } In order to register an org. } } public class MyEntityTuplizer extends PojoEntityTuplizer { public MyEntityTuplizer(EntityMetamodel entityMetamodel.extractEntityName( entityInstance ).getEntityName().equals( obj.

SessionFactory) using the registerEntityNameResolver method.7 49 .impl. TODO: Document user-extension framework in the property and proxy packages Hibernate 3.hibernate. Persistent Classes 2.2. Register it with the org.SessionFactoryImpl (which is the implementation class for org.hibernate.

Lets kick off with an example mapping: <?xml version="1.Chapter 5.sourceforge. even though many Hibernate users choose to write the XML by hand. Note that.0//EN" "http://hibernate. Basic O/R Mapping 5.2.1.ColorUserType" not-null="true" update="false"/> <property name="sex" not-null="true" update="false"/> <property name="litterId" column="litterId" update="false"/> <many-to-one name="mother" column="mother_id" update="false"/> <set name="kittens" inverse="true" order-by="litter_id"> <key column="mother_id"/> <one-to-many class="Cat"/> </set> <subclass name="DomesticCat" discriminator-value="D"> Hibernate 3. not table declarations.net/hibernate-mapping-3. meaning that mappings are constructed around persistent class declarations. including XDoclet. The mapping document is designed to be readable and hand-editable.7 50 . Middlegen and AndroMDA.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.types.dtd"> <hibernate-mapping package="eg"> <class name="Cat" table="cats" discriminator-value="C"> <id name="id"> <generator class="native"/> </id> <discriminator column="subclass" type="character"/> <property name="weight"/> <property name="birthdate" type="date" not-null="true" update="false"/> <property name="color" type="eg. a number of tools exist to gen- erate the mapping document. Mapping declaration Object/relational mappings are usually defined in an XML document. The mapping language is Java-centric.0.

1. Basic O/R Mapping <property name="name" type="string"/> </subclass> </class> <class name="Dog"> <!-. This custom EntityResolver recognizes two different systemId namespaces.dtd" [ <!ENTITY types SYSTEM "classpath://your/domain/types.. the resolver will attempt to resolve these entities via (1) the current thread context classloader and (2) the classloader which loaded the Hibernate classes. the resolver attempts to resolve these entities via the classlaoder which loaded the Hibernate classes.) 5.xml. An example of utilizing user namespacing: <?xml version="1. Doctype All XML mappings should declare the doctype shown. EntityResolver As mentioned previously.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.. The manner in which it does this is by registering a custom org. (For example the not-null attribute.7 51 .EntityResolver implementation with the SAXReader it uses to read in the xml files.jar.sourceforge.sourceforge.net/. Hibernate will always look for the DTD in its classpath first. in the directory hibernate-x.0//EN" "http://hibernate.0. The actual DTD may be found at the URL above.x.sax.2.net/hibernate-mapping-3.x/src/org/hibernate or in hibernate3.mapping for Dog could go here --> </class> </hibernate-mapping> We will now discuss the content of the mapping document. • a user namespace is recognized whenever the resolver encounteres a systemId using a classpath:// URL protocol. </id> <class> &types. </hibernate-mapping> Hibernate 3. We will only describe the document elements and attributes that are used by Hibernate at runtime.xml"> ]> <hibernate-mapping package="your. If you experience lookups of the DTD using an Internet connection. The mapping document also contains some extra optional at- tributes and elements that affect the database schemas exported by the schema export tool. Hibernate will first attempt to resolve DTDs in its classpath. check your DTD declaration against the contents of your claspath. • a hibernate namespace is recognized whenever the resolver encounteres a systemId starting with ht- tp://hibernate.1.domain"> <class name="MyEntity"> <id name="id" type="my-custom-id-type"> .

Dog.2.hbm.hbm.3.defaults to property): The strategy Hibernate should use for accessing all properties. as shown above.domain package and contains a custom Section 5.3.7 52 . (4) default-access (optional . If missing. (5) default-lazy (optional .1.2.name" (7) /> (1) schema (optional): The name of a database schema.xml.hbm. or if using inheritance. (6) auto-import (optional . “Custom value types”. tablenames will be qualified by the given schema and catalog names.xml.g.2. you should set auto-import="false".xml. 5. Animal.xml is a resource in the your. class You may declare a persistent class using the class element: <class name="ClassName" (1) table="tableName" (2) discriminator-value="discriminator_value" (3) mutable="true|false" (4) schema="owner" (5) catalog="catalog" (6) proxy="ProxyInterface" (7) dynamic-update="true|false" (8) dynamic-insert="true|false" (9) select-before-update="true|false" (10) polymorphism="implicit|explicit" (11) Hibernate 3. tablenames will be unqualified. (2) catalog (optional): The name of a database catalog. If specified. Can be a custom implementation of PropertyAccessor. (3) default-cascade (optional . Hi- bernate will throw an exception if you attempt to assign two classes to the same "imported" name.defaults to none): A default cascade style. <hibernate-mapping schema="schemaName" (1) catalog="catalogName" (2) default-cascade="cascade_style" (3) default-access="field|property|ClassName" (4) default-lazy="true|false" (5) auto-import="true|false" (6) package="package. e. If you have two persistent classes with the same (unqualified) name.defaults to true): The default value for unspecifed lazy attributes of class and collection mappings. The schema and catalog attributes specify that tables referred to in this mapping belong to the named schema and/or catalog. hibernate-mapping This element has several optional attributes. Basic O/R Mapping Where types. Cat. by default. It is however good practice (and expected by some tools) to map only a single persistent class (or a single class hierarchy) in one mapping file and name it after the persistent superclass. The default-cascade attribute specifies what cascade style should be assumed for properties and collections which do not specify a cascade attribute. Note that the hibernate-mapping element allows you to nest several persistent <class> mappings. (7) package (optional): Specifies a package prefix to assume for unqualified class names in the mapping doc- ument.defaults to true): Specifies whether we can use unqualified class names (of classes in this mapping) in the query language. The auto-import attribute lets us use unqualified class names in the query language.1. 5.

(14) batch-size (optional. (10) select-before-update (optional. Hibernate 3.defaults to the unqualified class name): The name of its database table. defaults to version): Determines the optimistic locking strategy. In certain cases (actually. “Dynamic models” and Chapter 18. on Oracle. See below for more information. it is assumed that the mapping is for a non-POJO entity. Hi- bernate can use the rowid extra column for fast updates if you set this option to rowid. but don't. (15) optimistic-lock (optional. (11) polymorphism (optional. this means that Hibernate will perform an extra SQL SELECT to determine if an UPDATE is actually required.7 53 . potentially). you should provide an explicit arbitrary name for the entity. See Section 4. (16) lazy (optional): Lazy fetching may be completely disabled by setting lazy="false".4. If this attribute is missing. You may specify the name of the class itself.defaults to the class name): A value that distiguishes individual sub- classes. You would then declare implement- ing classes of that interface using the <subclass> element. (21) abstract (optional): Used to mark abstract superclasses in <union-subclass> hierarchies. defaults to implicit): Determines whether implicit or explicit query polymorph- ism is used. (4) mutable (optional. eg. Useful if you want to have a view instead of a base table. defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed. (17) entity-name (optional. only when a transient object has been associated with a new session using update()). defaults to the class name): Hibernate3 allows a class to be mapped multiple times (to different tables. and allows entity mappings that are represented by Maps or XML at the Java level. (19) rowid (optional): Hibernate can use so called ROWIDs on databases which support. Basic O/R Mapping where="arbitrary sql where condition" (12) persister="PersisterClass" (13) batch-size="N" (14) optimistic-lock="none|version|dirty|all" (15) lazy="true|false" (16) entity-name="EntityName" (17) check="arbitrary sql check condition" (18) rowid="rowid" (19) subselect="SQL expression" (20) abstract="true|false" (21) node="element-name" /> (1) name (optional): The fully qualified Java class name of the persistent class (or interface).2. You should specify the class name using the standard form ie. defaults to true): Specifies that instances of the class are (not) mutable. In these cases. (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. (9) dynamic-insert (optional. defaults to 1) specify a "batch size" for fetching instances of this class by identifier. defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null. XML Mapping for more information. defaults to false): Specifies that Hibernate should never perform an SQL UPDATE unless it is certain that an object is actually modified. (7) proxy (optional): Specifies an interface to use for lazy initializing proxies. (8) dynamic-update (optional. It is perfectly acceptable for the named persistent class to be an interface. (2) table (optional . (20) subselect (optional): Maps an immutable and read-only entity to a database subselect. (18) check (optional): A SQL expression used to generate a multi-row check constraint for automatic schema generation. E. (5) schema (optional): Override the schema name specified by the root <hibernate-mapping> element. You may persist any static inner class. A ROWID is an implementation detail and represents the physical location of a stored tuple. (6) catalog (optional): Override the catalog name specified by the root <hibernate-mapping> element.Foo$Bar.g. used for polymorphic behaviour. Acceptable values include null and not null. (3) discriminator-value (optional .

name </subselect> <synchronize table="item"/> <synchronize table="bid"/> <id name="name"/> Hibernate 3.test. especially with updates).CustomPersister for a simple example (of "persistence" to a Hashtable).hibernate. It is very useful to prevent a database update trigger being called unnecessarily if you reattach a graph of detached instances to a Session.2. You may. If you enable dynamic-update.persister. for example.ClassPersister that implements per- sistence via. Use judiciously. Hibernate will ini- tially return CGLIB proxies which implement the named interface. The optional proxy attribute enables lazy initialization of persistent instances of the class. Implicit polymorphism means that instances of the class will be returned by a query that names any superclass or implemented interface or the class and that instances of any subclass of the class will be returned by a query that names the class itself. as expected this is transparent at the database level (note that some DBMS don't support views properly.amount). Sometimes you want to use a view. Basic O/R Mapping Immutable classes. Explicit polymorphism is useful when two different classes are mapped to the same table (this allows a "lightweight" class that contains a subset of the table columns). For most purposes the default. may not be updated or deleted by the application. max(bid. See "Proxies for Lazy Initialization" below. with a legacy schema). stored procedure calls. for example.7 54 . The actual persistent object will be loaded when a method of the proxy is invoked. when Session. In this case. This allows Hibernate to make some minor performance optimizations. This is the optimal strategy with respect to performance and is the only strategy that correctly handles modific- ations made to detached instances (ie. but might actually decrease performance in others. The persister attribute lets you customize the persistence strategy used for the class. Note that the dynamic-update and dynamic-insert settings are not inherited by subclasses and so may also be specified on the <subclass> or <joined-subclass> elements. specify your own subclass of org.hibernate. is appropriate. serialization to flat files or LDAP. Use of select-before-update will usually decrease performance.item_id = item. allowing some concurrent updates • none do not use optimistic locking We very strongly recommend that you use version/timestamp columns for optimistic locking with Hibernate.id group by item.name. polymorphism="implicit". These settings may increase performance in some cases. but can't create one in the database (ie. mutable="false". you will have a choice of optimistic locking strategies: • version check the version/timestamp columns • all check all columns • dirty check the changed columns. count(*) from item join bid on bid.merge() is used).EntityPersister or you might even provide a com- pletely new implementation of the interface org. See org. Explicit polymorphism means that class instances will be returned only by queries that explicitly name that class and that queries that name the class will return only instances of subclasses mapped inside this <class> declaration as a <subclass> or <joined-subclass>.hibernate.persister. you can map an immutable and read-only entity to a given SQL subselect expression: <class name="Summary"> <subselect> select item. There is no difference between a view and a base table for a Hibernate mapping.

7 55 .1. ensuring that auto-flush happens correctly.IdentifierGenerator. (5) access (optional . If any parameters are required to configure or initialize the generator instance. Hibernate provides a range of built-in implementations. This is a very simple inter- face.defaults to the property name): The name of the primary key column.defaults to property): The strategy Hibernate should use for accessing the property value. <id name="id" type="long" column="cat_id"> <generator class="org. it is assumed that the class has no identifier property. There is an alternative <composite-id> declaration to allow access to legacy data with composite keys.2. However. (2) type (optional): A name that indicates the Hibernate type.. The <subselect> is available as both as an attribute and a nested mapping element.hibernate. </class> Declare the tables to synchronize this entity with.id.id. (4) unsaved-value (optional . they are passed using the <param> element." <generator class="generatorClass"/> </id> (1) name (optional): The name of the identifier property. and that queries against the derived entity do not return stale data. Basic O/R Mapping . 5. <id name="propertyName" (1) type="typename" (2) column="column_name" (3) unsaved-value="null|any|none|undefined|id_value" (4) access="field|property|ClassName"> (5) node="element-name|@attribute-name|element/@attribute|. Generator The optional <generator> child element names a Java class used to generate unique identifiers for instances of the persistent class.hibernate. some applications may choose to provide their own specialized implementations. (3) column (optional .defaults to a "sensible" value): An identifier property value that indicates that an instance is newly instantiated (unsaved). We strongly discourage its use for anything else. Most classes will also have a Java- Beans-style property holding the unique identifier of an instance.4. If the name attribute is missing. There are shortcut names for the built-in generators: Hibernate 3. The unsaved-value attribute is almost never needed in Hibernate3.. The <id> element defines the mapping from that property to the primary key column. id Mapped classes must declare the primary key column of the database table.TableHiLoGenerator"> <param name="table">uid_table</param> <param name="column">next_hi_value_column</param> </generator> </id> All generators implement the interface org. distinguishing it from detached instances that were saved or loaded in a previous session.

unique within a network (the IP ad- dress is used). foreign uses the identifier of another associated object. MySQL. The UUID is encoded as a string of hexadecimal digits of length 32. but combines this with JDBC3 getGeneratedKeys to actually return the generated identifier value as part of the insert statement execution. sequence-identity a specialized sequence generation strategy which utilizes a database sequence for the actual value genera- tion. McKoi or a generator in Interbase. This is the default strategy if no <generator> element is specified.7 56 . Sybase and HypersonicSQL. Hi/lo algorithm The hilo and seqhilo generators provide two alternate implementations of the hi/lo algorithm.2. Do not use in a cluster. assigned lets the application to assign an identifier to the object before save() is called. guid uses a database-generated GUID string on MS SQL Server and MySQL. Basic O/R Mapping increment generates identifiers of type long.4. short or int. short or int hilo uses a hi/lo algorithm to efficiently generate identifiers of type long. Oracle. Usually used in conjunction with a <one-to-one> primary key association. SAP DB. Note comments on these insert statements are disabled due to a bug in the Oracle drivers. short or int. sequence uses a sequence in DB2. select retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retriev- ing the primary key value. The hi/lo al- gorithm generates identifiers that are unique only for a particular database. This strategy is only known to be supported on Oracle 10g drivers targetted for JDK 1. a favorite ap- Hibernate 3. native picks identity. sequence or hilo depending upon the capabilities of the underlying database. PostgreSQL. identity supports identity columns in DB2. short or int. uuid uses a 128-bit UUID algorithm to generate identifiers of type string. given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. given a named database sequence. MS SQL Server. The returned identifier is of type long. short or int that are unique only when no other process is inserting data into the same table. The returned identifier is of type long. seqhilo uses a hi/lo algorithm to efficiently generate identifiers of type long.

forcing Hibernate to go to the database to determine if an instance is transient or detached. Sybase. UUID algorithm The UUID contains: IP address. Assigned identifiers If you want the application to assign identifiers (as opposed to having Hibernate generate them). sequence and hilo strategies. For databases that support sequences (DB2. unless there is a version or timestamp prop- erty. so this is the best we can do without using JNI. When Hibernate is using an application server datasource to obtain connections enlisted with JTA. PostgreSQL. <id name="id" type="long" column="cat_id"> <generator class="hilo"> <param name="table">hi_value</param> <param name="column">next_value</param> <param name="max_lo">100</param> </generator> </id> <id name="id" type="long" column="cat_id"> <generator class="seqhilo"> <param name="sequence">hi_value</param> <param name="max_lo">100</param> </generator> </id> Unfortunately. you must properly configure the hi- bernate. you can't use hilo when supplying your own Connection to Hibernate. This generator is used when the primary key is a natural key instead of a surrogate key. This special generator will use the identifier value already assigned to the object's iden- tifier property. MySQL. Interbase. or you define Interceptor.isUnsaved().manager_lookup_class. startup time of the JVM (accurate to a quarter second). The second uses an Oracle-style sequence (where supported). you may use the assigned generator. dependant upon the capabilities of the underlying database. MS SQL). Basic O/R Mapping proach to identifier generation. Choosing the assigned generator makes Hibernate use unsaved-value="undefined". It's not possible to obtain a MAC address or memory address from Java code. system time and a counter value (unique within the JVM).7 57 . Hibernate 3. McKoi. Oracle. The first implementation requires a "special" database table to hold the next available "hi" value. Identity columns and sequences For databases which support identity columns (DB2.2. Both these strategies require two SQL queries to insert a new object. SAP DB) you may use sequence style key generation. you may use identity key generation. <id name="id" type="long" column="person_id"> <generator class="sequence"> <param name="sequence">person_id_sequence</param> </generator> </id> <id name="id" type="long" column="person_id" unsaved-value="0"> <generator class="identity"/> </id> For cross-platform development.transaction. This is the default behavior if you do no specify a <generator> element. the native strategy will choose from the identity.

SequenceStyleGenerator however achieves portability in a different manner.x). there is a unique valued property named socialSecurityNumber defined by the class.6. defaults to next_val): The name of the column on the table which is used to hold the value. • force_table_use (optional.5.1.hibernate. <id name="id" type="long" column="person_id"> <generator class="select"> <param name="key">socialSecurityNumber</param> </generator> </id> In the above example. this is analogous to the clause typical named "STARTS WITH". • value_column_name (optional. In sequence creation terms.MultipleHiLoPerTableGenerator) and secondly as a re-implementation of org.7 58 .2. Hibernate 3. The first of these new generators is org.enhanced. as a natural key. this is analogous to the clause typical named "INCREMENT BY". and a surrogate key named person_id whose value is generated by a trigger.id.id. defaults to false): Should we force the use of a table as the backing structure even though the dialect might support sequence? • value_column (optional.TableGenerator which is intended firstly as a replacement for the table generator (although it actually functions much more like org. • initial_value (optional. • optimizer (optional.enhanced.id. Basic O/R Mapping Primary keys assigned by triggers For legacy schemas only (Hibernate does not generate DDL with triggers). there are 2 new generators which represent a re-thinking of 2 different aspects of identifier generation. Essen- tially this generator defines a table capable of holding a number of different increment values simultaneously by using multiple distinctly keyed rows. The first aspect is database portability.hibernate.SequenceStyleGenerator which is intended firstly as a replacement for the sequence generator and secondly as a better portability generator than native (because native (generally) chooses between identity and sequence which have largely different semantics which can cause subtle isssues in applications eyeing portability). “Identifier generator optimization” The second of these new generators is org. Enhanced identifier generators Starting with release 3. defaults to next_val): Only relevant for table structures! The name of the column on the table which is used to hold the value. defaults to 1): The value by which subsequent calls to the sequence/table should differ. This generator has a number of configuration parameters: • table_name (optional. The difference between this and native is that table-based and sequence- based storage have the same exact semantic (in fact sequences are exactly what Hibernate tries to emmulate with its table-based generators).hibernate.hibernate. they are included in the current releases and can be referenced by FQN.hibernate. In se- quence creation terms.enhanced. however. This generator has a number of configuration parameters: • sequence_name (optional. the second is optimization (not having to query the database for every request for a new identifier value).MultipleHiLoPerTableGenerator utilizing the notion of pluggable optimiziers.1.2.3.3. defaults to hibernate_sequence): The name of the sequence (or table) to be used. It chooses between using a table or a sequence in the database to store its incrementing values depending on the capabilities of the dialect being used.id. • increment_size (optional. org.id. defaults to 1): The initial value to be retrieved from the sequence/table. defaults to hibernate_sequences): The name of the table to be used. These two new generators are intended to take the place of some of the named generators described above (starting in 3. 5. defaults to none): See Section 5.

defaults to 1): The initial value to be retrieved from the table. defaults to 255): Used for schema generation. the increment_size is multiplied by that value in memory to define a group "hi value". • segment_value (optional. “Enhanced identifier gen- erators” support this notion. • optimizer (optional. • pooled: like was discussed for hilo. “Identifier generator optimization” 5.. Currently only the two enhanced generators (Section 5. composite-id <composite-id name="propertyName" class="ClassName" mapped="true|false" access="field|property|ClassName"> node="element-name|.6..7 59 . defaults to sequence_name): The name of the column on the table which is used to hold the "segement key". This is the value which distinctly identifies which increment value to use.7.. Instead. however. you may map multiple properties of the class as identifier properties. The values from the database for this optimizer are expected to be sequential.6. • hilo: applies a hi/lo algorithm around the database retrieved values.1.. It must also implements Serializable. this approach to composite identifiers means that a persistent object is its own identifier. defaults to default): The "segment key" value for the segment from which we want to pull increment values for this generator. The values retrieved from the database structure for this optimizer indicates the "group number". • initial_value (optional. The <composite-id> element accepts <key-property> property mappings and <key-many-to-one> mappings as child elements. There Hibernate 3. This is the role of the pluggable optimizers..1.1. • segment_value_length (optional. <composite-id> <key-property name="medicareNumber"/> <key-property name="dependent"/> </composite-id> Your persistent class must override equals() and hashCode() to implement composite identifier equality." <key-property name="propertyName" type="typename" column="column_name"/> <key-many-to-one name="propertyName class="ClassName" column="column_name"/> .2. the column size to create this segment key column. you'd ideally want to group a bunch of them in memory and only hit the database when you have exhausted your in-memory value group. • none (generally this is the default if no optimizer was specified): This says to not perform any optimiza- tions. this optimizers attempts to minimize the number of hits to the data- base. Identifier generator optimization For identifier generators which store values in the database. • increment_size (optional.1. Here. </composite-id> For a table with a composite key. and hit the database each and every request. we simply store the starting value for the "next group" into the database structure rather than a sequential value in combination with an in-memory grouping algorithm. increment_size here refers to the values coming from the database. 5. defaults to ): See Section 5.5. Basic O/R Mapping • segment_column_name (optional. it is inefficient for them to hit the database on each and every call to generate a new identifier value. defaults to 1): The value by which subsequent calls to the table should differ. Unfortunately.

defaults to true) set this to false if your discriminator column is also part of a mapped Hibernate 3. (4) insert (optional . and discourage it for serious applications. both the composite identifier class. A restricted set of types may be used: string.defaults to class) the name of the discriminator column. discriminator The <discriminator> element is required for polymorphic persistence using the table-per-class-hierarchy map- ping strategy and declares a discriminator column of the table. where the identifier properties named inside the <composite-id> element are duplicated on both the persistent class and a separate identifier class. integer. Basic O/R Mapping is no convenient "handle" other than the object itself. • class (optional. 5. Serializable.4. The discriminator column contains marker val- ues that tell the persistence layer what subclass to instantiate for a particular row. required for this approach): A property of component type that holds the composite identifi- er (see chapter 9). short. • class (optional . The disadvantage of this approach is quite obvious—code duplication. MedicareId. You must instantiate an instance of the persistent class it- self and populate its identifier properties before you can load() the persistent state associated with a composite key.7 60 . The identifier class must override equals() and hashCode() and im- plement. We call this approach an embedded composite identifier.2. defaults to false): indicates that a mapped composite identifier is used.defaults to the property type determined by reflection): The component class used as a composite identifier (see next section). and that the con- tained property mappings refer to both the entity class and the composite identifier class.8. <discriminator column="discriminator_column" (1) type="discriminator_type" (2) force="true|false" (3) insert="true|false" (4) formula="arbitrary sql expression" (5) /> (1) column (optional .1. <composite-id class="MedicareId" mapped="true"> <key-property name="medicareNumber"/> <key-property name="dependent"/> </composite-id> In this example. A second approach is what we call a mapped composite identifier. an identifier component is the one we recommend for almost all applications. The following attributes are used to specify a mapped composite identifier: • mapped (optional. and the entity class itself have properties named medicareNumber and dependent.defaults to string) a name that indicates the Hibernate type (3) force (optional . but required for a mapped composite identifier): The class used as a composite identifier. “Components as composite identifiers”. boolean. byte. yes_no. We will describe a third.defaults to false) "force" Hibernate to specify allowed discriminator values even when retrieving all instances of the root class. • access (optional . This third approach. The attributes described below apply only to this alternative approach: • name (optional. even more convenient approach where the composite identifier is implemented as a component class in Section 8. (2) type (optional . character.defaults to property): The strategy Hibernate should use for accessing the property value. true_false.

This is particularly use- ful if you plan to use long transactions (see below). Actual values of the discriminator column are specified by the discriminator-value attribute of the <class> and <subclass> elements.1. no matter what other unsaved-value strategies are spe- cified. distinguishing it from detached instances that were saved or loaded in a previous session. (5) unsaved-value (optional . This will not usually be the case. (3) type (optional .6. May be set to false if and only if the database column is defined with a default value of 0.) (6) generated (optional . “Generated Properties”. Declaring a nullable version or timestamp property is an easy way to avoid any problems with transitive reattachment in Hibernate. (undefined specifies that the identifier property value should be used.defaults to undefined): A version property value that indicates that an instance is newly instantiated (unsaved). short.defaults to the property name): The name of the column holding the version number. Basic O/R Mapping composite identifier. Allows content-based discrimination.7 61 . timestamp (optional) Hibernate 3. (2) name: The name of a property of the persistent class. The force attribute is (only) useful if the table contains rows with "extra" discriminator values that are not mapped to a persistent class. (4) access (optional ." /> (1) column (optional . <version column="version_column" (1) name="propertyName" (2) type="typename" (3) access="field|property|ClassName" (4) unsaved-value="null|negative|undefined" (5) generated="never|always" (6) insert="true|false" (7) node="element-name|@attribute-name|element/@attribute|. 'c') then 0 else 1 end" type="integer"/> 5.) (5) formula (optional) an arbitrary SQL expression that is executed when a type has to be evaluated. especially useful for people using assigned identifiers or composite keys! 5. so Hibernate will detact any in- stance with a null version or timestamp as transient.1. version (optional) The <version> element is optional and indicates that the table contains versioned data. See the discussion of Section 5. A version or timestamp property should never be null for a detached instance. 'b'.defaults to true): Specifies whether the version column should be included in SQL in- sert statements. Using the formula attribute you can declare an arbitrary SQL expression that will be used to evaluate the type of a row: <discriminator formula="case when CLASS_TYPE in ('a'. Version numbers may be of Hibernate type long. (Tells Hibernate to not include the column in SQL INSERTs.2.defaults to integer): The type of the version number. (7) insert (optional .defaults to never): Specifies that this version property value is actually generated by the database.9. integer.defaults to property): The strategy Hibernate should use for accessing the property value. timestamp or calendar.10.

(undefined specifies that the identifier property value should be used.defaults to never): Specifies that this timestamp property value is actually gener- ated by the database.defaults to property): The strategy Hibernate should use for accessing the property value. <timestamp column="timestamp_column" (1) name="propertyName" (2) access="field|property|ClassName" (3) unsaved-value="null|undefined" (4) source="vm|db" (5) generated="never|always" (6) node="element-name|@attribute-name|element/@attribute|. “Generated Properties”.defaults to null): A version property value that indicates that an instance is newly instantiated (unsaved). This is intended as an al- ternative to versioning. See the discussion of Section 5. <property name="propertyName" (1) column="column_name" (2) type="typename" (3) update="true|false" (4) insert="true|false" (4) formula="arbitrary SQL expression" (5) access="field|property|ClassName" (6) lazy="true|false" (7) unique="true|false" (8) not-null="true|false" (9) optimistic-lock="true|false" (10) generated="never|insert|always" (11) node="element-name|@attribute-name|element/@attribute|.) (5) source (optional .defaults to the property name): The name of a column holding the timestamp. And <timestamp source="db"> is equivalent to <version type="dbtimestamp"> 5. but will be safer for use in clustered environ- ments." /> (1) column (optional . However. (4) unsaved-value (optional ." index="index_name" unique_key="unique_key_id" length="L" precision="P" scale="S" /> (1) name: the name of the property. or from the current JVM? Database-based timestamps incur an overhead because Hibernate must hit the database in order to determine the "next value".defaults to vm): From where should Hibernate retrieve the timestamp value? From the database.11. property The <property> element declares a persistent.2. (2) name: The name of a JavaBeans style property of Java type Date or Timestamp of the persistent class. sometimes the application might use the timestamps in other ways.7 62 . Basic O/R Mapping The optional <timestamp> element indicates that the table contains timestamped data.6. distinguishing it from detached instances that were saved or loaded in a pre- vious session. (3) access (optional . Timestamps are by nature a less safe implementation of optimistic locking. Hibernate 3. while others might be unsafe for usage in locking due to lack of precision (Oracle 8 for ex- ample). Note that <timestamp> is equivalent to <version type="timestamp">. with an initial lowercase letter. that not all Dialects are known to support retrieving of the database's current timestamp. (6) generated (optional .1. JavaBean style property of the class. Note also.

String. (5) formula (optional): an SQL expression that defines the value for a computed property. (3) type (optional): a name that indicates the Hibernate type. (9) not-null (optional): Enable the DDL generation of a nullability constraint for the columns. integer. or to specify a custom type.2.lang.) The access attribute lets you control how Hibernate will access the property at runtime. string. Computed proper- ties do not have a column mapping of their own.TIMESTAMP. float. You may specify your own strategy for property access by naming a class that implements the interface org. 4. object.orderNumber = orderNumber )"/> Note that you can reference the entities own table by not declaring an alias on a particular column (customerId in the given example).hibernate. The name of a serializable Java class. In other words. By default. int. com. serializable. 2. This may also be specified by nested <column> element(s).defaults to never): Specifies that this property value is actually generated by the database. java.Clob). The name of a Hibernate basic type (eg. An especially powerful feature are derived properties. (11) generated (optional . Hibernate will use reflection upon the named property to take a guess at the correct Hibernate type. timestamp. “Generated Properties”.6. Product p WHERE li. allow this to be the target of a property-ref. char. java.productId = p. These properties are by definition read-only. You declare the computation as a SQL expression. this translates to a SELECT clause subquery in the SQL query that loads an instance: <property name="totalPrice" formula="( SELECT SUM (li. to distinguish between Hibernate.Integer.illflow.PropertyAccessor. blob).DATE and Hibernate. Hibernate will call the property get/set pair. the property value is computed at load time. If you do not specify a type.defaults to true) : specifies that the mapped columns should be included in SQL UPDATE and/or INSERT statements. using reflection.lang. Also.defaults to false): Specifies that this property should be fetched lazily when the instance variable is first accessed (requires build-time bytecode instrumentation). (6) access (optional . binary. Setting both to false allows a pure "derived" property whose value is initialized from some other property that maps to the same colum(s) or by a trigger or other ap- plication.7 63 .defaults to the property name): the name of the mapped database table column.util.sql. If you specify access="field". java.price) FROM LineItem li. (7) lazy (optional . character. determines if a version increment should occur when this property is dirty. this is not always enough. Hibernate will try to interpret the name of the return class of the property getter using rules 2. The class name of a custom type (eg. Also note that you can use the nested <formula> mapping element if you don't like to use the attribute. typename could be: 1. Hibernate will bypass the get/set pair and ac- cess the field directly.property. However. In certain cases you will still need the type attribute. 3. (10) optimistic-lock (optional .defaults to true): Specifies that updates to this property do or do not require acquisition of the optimistic lock. 4 in that order. 3.customerId = customerId AND li. float. (For example. (4) update. Basic O/R Mapping (2) column (optional .productId AND li. java. The name of a Java class with a default basic type (eg. insert (optional . Hibernate 3. See the discussion of Section 5. (8) unique (optional): Enable the DDL generation of a unique constraint for the columns.Date. date.MyCustomType).defaults to property): The strategy Hibernate should use for accessing the property value.quantity*p.type.

(10) not-null (optional): Enable the DDL generation of a nullability constraint for the foreign key columns. <many-to-one name="propertyName" (1) column="column_name" (2) class="ClassName" (3) cascade="cascade_style" (4) fetch="join|select" (5) update="true|false" (6) insert="true|false" (6) property-ref="propertyNameFromAssociatedClass" (7) access="field|property|ClassName" (8) unique="true|false" (9) not-null="true|false" (10) optimistic-lock="true|false" (11) lazy="proxy|no-proxy|false" (12) not-found="ignore|exception" (13) entity-name="EntityName" (14) formula="arbitrary SQL expression" (15) node="element-name|@attribute-name|element/@attribute|. (2) column (optional): The name of the foreign key column.7 64 . Basic O/R Mapping 5. Also. lazy="false" specifies that the association will always be eagerly fetched. insert (optional . 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. (5) fetch (optional . Setting both to false allows a pure "derived" association whose value is initialized from some other property that maps to the same colum(s) or by a trigger or other ap- plication.defaults to true): Specifies that updates to this property do or do not require acquisition of the optimistic lock. (4) cascade (optional): Specifies which operations should be cascaded from the parent object to the associ- ated object.12.2. the primary key of the associated class is used. lazy="no-proxy" specifies that the property should be fetched lazily when the instance variable is first accessed (requires build-time bytecode instrumentation). This makes the association multiplicity effectively one to one.defaults to property): The strategy Hibernate should use for accessing the property value." embed-xml="true|false" index="index_name" unique_key="unique_key_id" foreign-key="foreign_key_name" /> (1) name: The name of the property. (8) access (optional .defaults to true) specifies that the mapped columns should be included in SQL UPDATE and/or INSERT statements. single point associations are proxied. dertermines if a version increment should occur when this property is dirty. Hibernate 3.defaults to exception): Specifies how foreign keys that reference missing rows will be handled: ignore will treat a missing row as a null association.defaults to select): Chooses between outer-join fetching or sequential select fetching. (3) class (optional . (7) property-ref: (optional) The name of a property of the associated class that is joined to this foreign key. In other words. (6) update. al- low this to be the target of a property-ref. (12) lazy (optional .defaults to proxy): By default. (9) unique (optional): Enable the DDL generation of a unique constraint for the foreign-key column. (11) optimistic-lock (optional .defaults to the property type determined by reflection): The name of the associated class. This may also be specified by nested <column> element(s). many-to-one An ordinary association to another persistent class is declared using a many-to-one element. (13) not-found (optional . If not specified.1.

persist. (2) class (optional .11. See Section 10.merge. for example.) <property name="serialNumber" unique="true" type="string" column="SERIAL_NUMBER"/> Then the mapping for OrderItem might use: <many-to-one name="product" property-ref="serialNumber" column="PRODUCT_SERIAL_NUMBER"/> This is certainly not encouraged. Hibernate 3.2. you should map the refer- enced properties inside a named <properties> element. lock. This is an ugly relational model. The meaningful values are the names of Hibernate's basic operations.ssn" column="OWNER_SSN"/> 5. however. you may specify a property path: <many-to-one name="owner" property-ref="identity. delete. one-to-one A one-to-one association to another persistent class is declared using a one-to-one element. For example.delete-orphan".1." embed-xml="true|false" foreign-key="foreign_key_name" /> (1) name: The name of the property. merge. suppose the Product class had a unique serial number. If the referenced unique key comprises multiple properties of the associated entity. (The unique attribute controls Hi- bernate's DDL generation with the SchemaExport tool. cas- cade="persist. that is not the primary key. If the referenced unique key is the property of a component. refresh. Setting a value of the cascade attribute to any meaningful value other than none will propagate certain opera- tions to the associated object. A typical many-to-one declaration looks as simple as this: <many-to-one name="product" class="Product" column="PRODUCT_ID"/> The property-ref attribute should only be used for mapping legacy data where a foreign key refers to a unique key of the associated table other than the primary key. Basic O/R Mapping (14) entity-name (optional): The entity name of the associated class. save-update. “Transitive persistence” for a full explanation. Note that single valued associations (many-to-one and one-to-one associations) do not support orphan delete.evict" or cascade="all. replicate. as well as the special values delete- orphan and all and comma-separated combinations of operation names.defaults to the property type determined by reflection): The name of the associated class. <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) lazy="proxy|no-proxy|false" (9) entity-name="EntityName" (10) node="element-name|@attribute-name|element/@attribute|. evict.13.7 65 .

.test.hibernate. (See org. the primary key of the associated class is used. There are two varieties of one-to-one association: • primary key associations • unique foreign key associations Primary key associations don't need an extra table column. Note that if constrained="false". This option affects the order in which save() and delete() are cascaded. Basic O/R Mapping (3) cascade (optional) specifies which operations should be cascaded from the parent object to the associated object. single point associations are proxied. <one-to-one name="person" class="Person"/> <one-to-one name="employee" class="Employee" constrained="true"/> Now we must ensure that the primary keys of related rows in the PERSON and EMPLOYEE tables are equal. (8) formula (optional): Almost all one to one associations map to the primary key of the owning entity. a foreign key with a unique constraint.7 66 . In the rare case that this is not the case. We use a special Hibernate identifier generation strategy called foreign: <class name="person" table="PERSON"> <id name="id" column="PERSON_ID"> <generator class="foreign"> <param name="property">employee</param> </generator> </id> . Alternatively.defaults to select): Chooses between outer-join fetching or sequential select fetching. and determines whether the association may be proxied (it is also used by the schema export tool). lazy="no-proxy" specifies that the property should be fetched lazily when the instance variable is first accessed (requires build-time bytecode instrumentation).defaults to proxy): By default.defaults to property): The strategy Hibernate should use for accessing the property value. from Employee to Person. (5) fetch (optional . add the following mappings to Employee and Person. (4) constrained (optional) specifies that a foreign key constraint on the primary key of the mapped table ref- erences the table of the associated class. If not specified. may be expressed as: Hibernate 3.2. (7) access (optional . proxying is impossible and Hibernate will eager fetch the as- sociation! (10) entity-name (optional): The entity name of the associated class.. respectively.onetooneformula for an example.) (9) lazy (optional . (6) property-ref: (optional) The name of a property of the associated class that is joined to the primary key of this class. So if you want two objects to be related by a primary key as- sociation. you must make sure that they are assigned the same identifier value! For a primary key association. if two rows are related by the association then the two table rows share the same primary key value. you may specify a some other column. lazy="false" specifies that the association will always be eagerly fetched. columns or expression to join on using an SQL formula. <one-to-one name="employee" class="Employee" constrained="true"/> </class> A newly saved instance of Person is then assigned the same primary key value as the Employee instance refered with the employee property of that Person.

. defaults to false): By default.. (2) class (optional . even better. Hibernate will generate the necessary unique key and nullability constraints.. This mapping is not intended for use with entities with natural primary keys. Compon- ents may. dynamic-component The <component> element maps properties of a child object to columns of the table of a parent class." > <property .2... /> . and your mapping will be more self- documenting. </component> (1) name: The name of the property.. (3) insert: Do the mapped columns appear in SQL INSERTs? (4) update: Do the mapped columns appear in SQL UPDATEs? (5) access (optional . <component name="propertyName" (1) class="className" (2) insert="true|false" (3) update="true|false" (4) access="field|property|ClassName" (5) lazy="true|false" (6) optimistic-lock="true|false" (7) unique="true|false" (8) node="element-name|.. you should still try to identify natural keys for all entities.. components or collections..... </natural-id> Even though we recommend the use of surrogate keys as primary keys..14.7 67 .. in turn.. /> ./> <many-to-one . 5.defaults to property): The strategy Hibernate should use for accessing the property value. natural identifier properties as assumed to be immutable (constant)... /> <many-to-one .1. Hibernate 3.. natural-id <natural-id mutable="true|false"/> <property ..1.. component.15. declare their own properties. See "Components" below. A natural key is a property or combination of properties that is unique and non-null. • mutable (optional.. Basic O/R Mapping <many-to-one name="person" class="Person" column="PERSON_ID" unique="true"/> And this association may be made bidirectional by adding the following to the Person mapping: <one-to-one name"employee" class="Employee" property-ref="person"/> 5. If it is also immutable. Map the properties of the natural key inside the <natural-id> element.defaults to the property type determined by reflection): The name of the component (child) class... We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.

5. In other words. (7) optimistic-lock (optional ... where the property names refer to keys of the map... It is also a convenient way to define a multi-column unique constraint. determines if a version increment should occur when this property is dirty..not an actual property name. (8) unique (optional ..1.2. <properties name="logicalName" (1) insert="true|false" (2) update="true|false" (3) optimistic-lock="true|false" (4) unique="true|false" (5) > <property .7 68 . For example. <properties name="name" unique="true" update="false"> <property name="firstName"/> <property name="initial"/> <property name="lastName"/> </properties> </class> Then we might have some legacy data association which refers to this unique key of the Person table. (2) insert: Do the mapped columns appear in SQL INSERTs? (3) update: Do the mapped columns appear in SQL UPDATEs? (4) optimistic-lock (optional . logical grouping of properties of a class. The <dynamic-component> element allows a Map to be mapped as a component. determines if a version increment should occur when these properties are dirty.. Basic O/R Mapping (6) lazy (optional .. “Dynamic components”. instead of to the primary key: Hibernate 3../> <many-to-one . The child <property> tags map properties of the child class to table columns. /> . The most important use of the construct is that it allows a combination of properties to be the target of a property-ref..defaults to false): Specifies that this component should be fetched lazily when the in- stance variable is first accessed (requires build-time bytecode instrumentation).5.16. </properties> (1) name: The logical name of the grouping .defaults to false): Specifies that a unique constraint exists upon all mapped columns of the component. The <component> element allows a <parent> subelement that maps a property of the component class as a ref- erence back to the containing entity... properties The <properties> element allows the definition of a named. if we have the following <properties> mapping: <class name="Person"> <id name="personNumber"/> . (5) unique (optional .defaults to true): Specifies that updates to these properties do or do not re- quire acquisition of the optimistic lock.defaults to true): Specifies that updates to this component do or do not re- quire acquisition of the optimistic lock... see Section 8.. In other words.defaults to false): Specifies that a unique constraint exists upon all mapped columns of the component..

</subclass> (1) name: The fully qualified class name of the subclass. 5. Inheritance Mapping..defaults to the class name): A value that distiguishes individual sub- classes.... (3) proxy (optional): Specifies a class or interface to use for lazy initializing proxies.17. 5. If none is specified. For information about inheritance mappings. (4) lazy (optional.18..1. Inherited state is retrieved by joining with the table of the superclass. <joined-subclass name="ClassName" (1) table="tablename" (2) proxy="ProxyInterface" (3) lazy="true|false" (4) dynamic-update="true|false" dynamic-insert="true|false" schema="schema" catalog="catalog" extends="SuperclassName" persister="ClassName" subselect="SQL expression" entity-name="EntityName" node="element-name"> Hibernate 3. For the table-per-class-hierarchy mapping strategy.. (2) discriminator-value (optional .2. We use the <joined-subclass> element. Each subclass in a heirarchy must define a unique discriminator- value.7 69 . <version> and <id> properties are assumed to be inherited from the root class. the fully qualified Java class name is used. joined-subclass Alternatively. the <subclass> declaration is used. subclass Finally. polymorphic persistence requires the declaration of each subclass of the root persistent class.1. <subclass name="ClassName" (1) discriminator-value="discriminator_value" (2) proxy="ProxyInterface" (3) lazy="true|false" (4) dynamic-update="true|false" dynamic-insert="true|false" entity-name="EntityName" node="element-name" extends="SuperclassName"> <property . each subclass may be mapped to its own table (table-per-subclass mapping strategy). Each subclass should declare its own persistent properties and subclasses. see Chapter 9. /> .. Basic O/R Mapping <many-to-one name="person" class="Person" property-ref="name"> <column name="firstName"/> <column name="initial"/> <column name="lastName"/> </many-to-one> We don't recommend the use of this kind of thing outside the context of mapping legacy data. defaults to true): Setting lazy="false" disables the use of lazy fetching.

.19.Dog"> <!-. Each subclass must.0. You can simply map each class with a separate <class> declaration. see Chapter 9. you need to use the <union-subclass> mapping. Inheritance Mapping.sourceforge. <union-subclass name="ClassName" (1) table="tablename" (2) proxy="ProxyInterface" (3) lazy="true|false" (4) Hibernate 3.. In Hibernate. declare a table column holding the object identifier using the <key> element.1.2.. union-subclass A third option is to map only the concrete classes of an inheritance hierarchy to tables.. (3) proxy (optional): Specifies a class or interface to use for lazy initializing proxies.mapping for Dog could go here --> </class> </hibernate-mapping> For information about inheritance mappings.. including inherited state. (2) table: The name of the subclass table.. The mapping at the start of the chapter would be re-written as: <?xml version="1. </joined-subclass> (1) name: The fully qualified class name of the subclass.7 70 .. (4) lazy (optional. > <property .. 5. however. defaults to true): Setting lazy="false" disables the use of lazy fetching. an as- sociation to the superclass of your hierarchy).g. if you wish use polymorphic associations (e..dtd"> <hibernate-mapping package="eg"> <class name="Cat" table="CATS"> <id name="id" column="uid" type="long"> <generator class="hilo"/> </id> <property name="birthdate" type="date"/> <property name="color" not-null="true"/> <property name="sex" not-null="true"/> <property name="weight"/> <many-to-one name="mate"/> <set name="kittens"> <key column="MOTHER"/> <one-to-many class="Cat"/> </set> <joined-subclass name="DomesticCat" table="DOMESTIC_CATS"> <key column="CAT"/> <property name="name" type="string"/> </joined-subclass> </class> <class name="eg. (the table- per-concrete-class strategy) where each table defines all persistent state of the class. No discriminator column is required for this mapping strategy. it is not absolutely necessary to explicitly map such inheritance hierarchies..0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate. /> .net/hibernate-mapping-3. However. Basic O/R Mapping <key .

2..defaults to join): If set to join.. (4) lazy (optional. /> . (3) proxy (optional): Specifies a class or interface to use for lazy initializing proxies.. the default.. defaults to true): Setting lazy="false" disables the use of lazy fetching. For information about inheritance mappings.. it is possible to map properties of one class to several tables. No discriminator column or key column is required for this mapping strategy. (6) optional (optional .. which will be is- sued only if a row turns out to represent an instance of the subclass.. Hibernate will insert a row only if the properties defined by this join are non-null and will always use an outer join to retrieve the properties. </join> (1) table: The name of the joined table.1. (4) fetch (optional . Inner joins will still be used to re- trieve a <join> defined by the class and its superclasses.. (2) schema (optional): Override the schema name specified by the root <hibernate-mapping> element. (2) table: The name of the subclass table. join Using the <join> element. For example.7 71 . /> <property . 5..defaults to false): If enabled. /> . Hibernate will use an inner join to retrieve a <join> defined by a class or its superclasses and an outer join for a <join> defined by a subclass. Inheritance Mapping. </union-subclass> (1) name: The fully qualified class name of the subclass.20. Hibernate will not try to insert or update the properties defined by this join.. Basic O/R Mapping dynamic-update="true|false" dynamic-insert="true|false" schema="schema" catalog="catalog" extends="SuperclassName" abstract="true|false" persister="ClassName" subselect="SQL expression" entity-name="EntityName" node="element-name"> <property . (3) catalog (optional): Override the catalog name specified by the root <hibernate-mapping> element. (5) inverse (optional ... see Chapter 9.. <join table="tablename" (1) schema="owner" (2) catalog="catalog" (3) fetch="join|select" (4) inverse="true|false" (5) optional="true|false"> (6) <key . the address information for a person can be mapped to a separate table (while preserving value type semantics for all properties): <class name="Person" table="PERSON"> Hibernate 3.defaults to false): If enabled. If set to select then Hibernate will use a sequential select for a <join> defined on a subclass.

(Provided for legacy data. <key column="columnname" (1) on-delete="noaction|cascade" (2) property-ref="propertyName" (3) not-null="true|false" (4) update="true|false" (5) unique="true|false" (6) /> (1) column (optional): The name of the foreign key column. that references the primary key of the original table.2. <formula> is an alternative to the formula attribute... (6) unique (optional): Specifies that the foreign key should have a unique constraint (this is implied whenever the foreign key is also the primary key).1. and defines the foreign key in the joined table. and Hibernate will use a database-level ON CASCADE DELETE constraint. Basic O/R Mapping <id name="id" column="PERSON_ID">. However. it is useful for switching between inheritance mapping strategies in a single hierarchy.22. (2) on-delete (optional. If you map a unidirectional one to many to a non-nullable foreign key. you must declare the key column using <key not-null="true">. Like- wise. all keys should be defined on-de- lete="cascade". defaults to noaction): Specifies whether the foreign key constraint has database- level cascade delete enabled. key We've seen the <key> element crop up a few times now. instead of many indi- vidual DELETE statements.7 72 . column and formula elements Any mapping element which accepts a column attribute will alternatively accept a <column> subelement.21. It appears anywhere the parent mapping element defines a join to a new table.</id> <join table="ADDRESS"> <key column="ADDRESS_ID"/> <property name="address"/> <property name="zip"/> <property name="country"/> </join> .. 5. (3) property-ref (optional): Specifies that the foreign key refers to columns that are not the primary key of the orginal table. This may also be specified by nested <column> element(s).1. (5) update (optional): Specifies that the foreign key should never be updated (this is implied whenever the foreign key is also part of the primary key). Hibernate 3. Be aware that this feature bypasses Hibernate's usual optimistic locking strategy for versioned data.) (4) not-null (optional): Specifies that the foreign key columns are not nullable (this is implied whenever the foreign key is also part of the primary key).. This feature is often only useful for legacy data models. We recommend that for systems where delete performance is important. The not-null and update attributes are useful when mapping a unidirectional one to many association. 5. as explained later. we recommend fewer tables than classes and a fine- grained domain model.

23. <many-to-one name="homeAddress" class="Address" insert="false" update="false"> <column name="person_id" not-null="true" length="10"/> <formula>'MAILING'</formula> </many-to-one> 5. It is impossible to specify a foreign key constraint for this kind of association. for example. This type of mapping always requires more than one column. any There is one further type of property mapping. etc). and you don't want to specify the fully qualified (package) name in Hibernate queries. <import class="java. <any name="being" id-type="long" meta-type="string"> <meta-value value="TBL_ANIMAL" class="Animal"/> <meta-value value="TBL_HUMAN" class="Human"/> Hibernate 3. Basic O/R Mapping <column name="column_name" length="N" precision="N" scale="N" not-null="true|false" unique="true|false" unique-key="multicolumn_unique_key_name" index="index_name" sql-type="sql_type_name" check="SQL expression" default="SQL expression"/> <formula>SQL expression</formula> column and formula attributes may even be combined within the same property or association mapping to ex- press. Classes may be "imported" explicitly. You may even import classes and interfaces that are not explicitly mapped. rather than relying upon auto-import="true".lang.7 73 .defaults to the unqualified class name): A name that may be used in the query lan- guage. audit logs.2. exotic join conditions.1.Object" rename="Universe"/> <import class="ClassName" (1) rename="ShortName" (2) /> (1) class: The fully qualified class name of of any Java class. (2) rename (optional .24.1. so this is most certainly not meant as the usual way of map- ping (polymorphic) associations. The meta-type attribute lets the application specify a custom type that maps database column values to persist- ent classes which have identifier properties of the type specified by id-type. You should use this only in very special cases (eg. import Suppose your application has two persistent classes with the same name. The remaining columns hold the identifier. You must specify the mapping from values of the meta-type to class names. The first column holds the type of the associated entity. 5. user session data. The <any> mapping element defines a polymorphic association to classes from multiple tables.

Up until now. /> . Hibernate Types 5.. An entity's persistent state consists of references to other entities and instances of value types. we can say that all types (classes) provided by the JDK have value type semantics in Java. not all user-defined classes with persistent state are entities.. (5) access (optional . Entities must be explicitly saved and deleted (except that saves and deletions may be cascaded from a parent entity to its children).lang. Since value objects (and primitives) are persisted and deleted along with their containing entity they may not be independently ver- sioned..defaults to string): Any type that is allowed for a discriminator mapping.. /> <meta-value .. (6) optimistic-lock (optional .. values (in particular collections and components) are persisted and deleted by reachability.2. collections (not what's inside a collection). A component is a user defined class with value semantics. They may also be versioned. Contrast this with the usual Java model where an unreferenced object is garbage collected. /> <column . A Java property of type java.defaults to none): the cascade style.. Values are prim- itives. Entities support circular and shared references.String also has value semantics. 5.. so they cannot be shared by two entities or collections. Strictly speaking..2.7 74 .. <column . Values have no independent identity. (3) meta-type (optional . Basic O/R Mapping <meta-value value="TBL_ALIEN" class="Alien"/> <column name="table_name"/> <column name="id"/> </any> <any name="propertyName" (1) id-type="idtypename" (2) meta-type="metatypename" (3) cascade="cascade_style" (4) access="field|property|ClassName" (5) optimistic-lock="true|false" (6) > <meta-value ..defaults to property): The strategy Hibernate should use for accessing the property value. Entities and values To understand the behaviour of various Java language-level objects with respect to the persistence service. (4) cascade (optional.. In other words. we've been using the term "persistent class" to refer to entities. </any> (1) name: the property name. (2) id-type: the identifier type. Unlike entities.defaults to true): Specifies that updates to this property do or do not require acquisition of the optimistic lock.and corresponds more closely to how application objects are usually used in large systems..2... /> . We will continue to do that.. components and certain immutable objects. define if a version increment should occur if this prop- erty is dirty. we need to classify them into two groups: An entity exists independently of any other objects holding references to the entity. while user-defined types may be mapped with entity or value type semantics. however.. This decision is up to the application Hibernate 3. Given this definition.1.. This is different from the ODMG model of object persistence by reachablity .

util.String to VARCHAR (or Oracle VARCHAR2). true_false Type mappings from Java primitives or wrapper classes to appropriate (vendor-specific) SQL column types. java.Class to VARCHAR (or Oracle VARCHAR2). The challenge is to map the Java type system (and the developers' definition of entities and value types) to the SQL/database type system.util. usually with a type at- tribute. serializable Maps serializable Java types to an appropriate SQL binary type. calendar. 5.Calendar to SQL types TIMESTAMP and DATE (or equivalent). currency Type mappings from java. big_decimal. For value types we use <property>. double.lang. date.lang. We'll revisit both concepts throughout the documentation. etc.math.util. Instances of TimeZone are mapped to their ID.Boolean. Hibernate provides many mappings (for standard JDK value types) out of the box. All built-in Hibernate types except collections support null semantics.Currency to VARCHAR (or Oracle VARCHAR2). character.2. <component>. text Maps long Java strings to a SQL CLOB or TEXT type.lang. big_integer Type mappings from java. short.2. locale.Locale. time. long. yes_no. as you'll see later. class A type mapping from java.math.BigDecimal and java.7 75 . You may also indicate the Hibernate type serializable with the name of a serializable Java class or interface that does not default to a basic type.util. A good hint for an entity class in a domain model are shared references to a single instance of that class. string A type mapping from java. timestamp Type mappings from java.2. TIME and TIMESTAMP (or equi- valent).BigInteger to NUMERIC (or Oracle NUMBER). while composition or aggregation usually translates to a value type. Hibernate 3. byte.util. Instances of Locale and Currency are mapped to their ISO codes. timezone. You can write your own mapping types and implement your cus- tom conversion strategies as well. calendar_date Type mappings from java. Basic value types The built-in basic mapping types may be roughly categorized into integer. binary Maps byte arrays to an appropriate SQL binary type. A Class is mapped to its fully qualified name.Date and its subclasses to SQL types DATE. The value of this attribute is the name of a Hibernate mapping type. The bridge between both systems is provided by Hibernate: for entities we use <class>. boolean. boolean. float. Basic O/R Mapping developer. <subclass> and so on.TimeZone and java. yes_no and true_false are all alternative encodings for a Java boolean or java.

DoubleStringType"> <column name="first_string"/> <column name="second_string"/> </property> Notice the use of <column> tags to map a property to multiple columns. it may be useful to define a shorter name for it. blob Type mappings for the JDBC classes java. The CompositeUserType. your UserType must implement the org. 5. you should not call Date. blob and clob. imm_calendar_date. you might have a Java property getName()/setName() of type java.hibernate. These types may be inconveni- ent for some applications.STRING represents the string type. Custom value types It is relatively easy for developers to create their own value types. To implement a customtype. Check out org. imm_calendar.2.Clob and java.lang. implement either org. (Composite identifiers are also allowed.) imm_date. since the blob or clob object may not be reused outside of a transaction. You can do this using Hibernate 3.usertype.sql.test.BigInteger to VARCHAR columns.DoubleStringType to see the kind of things that are possible.usertypes. To supply parameters to your custom type. Basic O/R Mapping clob.setTime() for an instance mapped as imm_timestamp.Blob. To change the value of the property.ParameterizedType interface. You may even supply parameters to a UserType in the mapping file. imm_timestamp. imm_time.CompositeUserType and declare properties using the fully qualified classname of the type. and UserVersionType interfaces provide support for more specialized uses.2. SURNAME. and have that change made persistent. So. where Hibernate makes certain optim- izations appropriate only for immutable Java types.hibernate.) The basic value types have corresponding Type constants defined on org. the application must assign a new (nonidentical) object to the property.test. see below. imm_binary Type mappings for what are usually considered mutable Java types.hibernate. For example. driver support is patchy and inconsistent. Unique identifiers of entities and collections may be of any basic type except binary.UserType or org.7 76 . For example. imm_serializable. EnhancedUserType.sql.hibernate. Hibernate does not provide a built-in type for this.hibernate. But custom types are not limited to mapping a property (or collection element) to a single table column. If you use a certain UserType very often. For example.DefaultValueIntegerType"> <param name="default">0</param> </type> </property> The UserType can now retrieve the value for the parameter named default from the Properties object passed to it. UserCollectionType.String that is persisted to the columns FIRST_NAME. INITIAL. (Furthermore. To do this. for example.Hibernate. Hibernate. and the application treats the object as immutable.mycompany.3.lang. you can use the <type> element in your mapping files.hibernate. you might want to persist prop- erties of type java. <property name="twoStrings" type="org. <property name="priority"> <type name="com.

<typedef class="com.usertypes. the entity name is the same as the class name.2. 5. it is nevertheless considered good form to use custom types for (non-entity) classes that occur frequently in your application. <class name="Contract" table="Contracts" entity-name="CurrentContract"> . a MonetaryAmount class is a good candidate for a Com- positeUserType. Mapping a class more than once It is possible to provide more than one mapping for a particular persistent class. In this case you must specify an entity name do disambiguate between instances of the two mapped entities. <many-to-one name="currentContract" column="currentContractId" entity-name="CurrentContract"/> </class> Notice how associations are now specified using entity-name instead of class... or when mapping associations to the named entity. Basic O/R Mapping the <typedef> element.4. 5. even though it could easily be mapped as a component. Hibernate will use the correct quotation style for the SQL Dialect (usually double quotes.. SQL quoted identifiers You may force Hibernate to quote an identifier in the generated SQL by enclosing the table or column name in backticks in the mapping document. but brackets for SQL Server and backticks for MySQL).7 77 .3. Even though Hibernate's rich range of built-in types and support for components means you will very rarely need to use a custom type. One motivation for this is abstraction. <set name="history" inverse="true" order-by="effectiveEndDate desc"> <key column="currentContractId"/> <one-to-many entity-name="HistoricalContract"/> </set> </class> <class name="Contract" table="ContractHistory" entity-name="HistoricalContract"> . your mapping documents would be future-proofed against possible changes in your way of representing monetary values. <class name="LineItem" table="`Line Item`"> <id name="id" column="`Item Id`"/><generator class="assigned"/></id> <property name="itemNumber" column="`Item #`"/> . </class> Hibernate 3. For example. Typedefs assign a name to a custom type.. With a custom type.) Hibernate lets you specify the entity name when working with persistent objects. (By default.DefaultValueIntegerType" name="default_zero"> <param name="default">0</param> </typedef> <property name="priority" type="default_zero"/> It is also possible to override the parameters supplied in a typedef on a case-by-case basis by using type para- meters on the property mapping.. and may also contain a list of default para- meter values if the type is parameterized.mycompany. when writing queries..

Basic O/R Mapping 5. import java.id * generator-class="native" * column="CAT_ID" */ public Long getId() { return id. } void setBirthdate(Date date) { birthdate = date. and so there are some alternative ways to define O/R mapping metadata in Hibernate.util. /** * @hibernate. } /** * @hibernate.tags.2. // identifier private Date birthdate. import java.Set.many-to-one * column="PARENT_ID" */ public Cat getMother() { return mother.property * column="BIRTH_DATE" */ public Date getBirthdate() { return birthdate.util. } /** * @hibernate. private Cat mother.Date. } void setMother(Cat mother) { this. Hibernate 3. We will not cover this approach in this document. package eg. } /** * @hibernate. However. /* * @hibernate. we include the following example of the Cat class with XDoclet mappings. } private void setId(Long id) { this.property * column="WEIGHT" */ public float getWeight() { return weight.5. Metadata alternatives XML isn't for everyone.mother = mother.7 78 . 5. private char sex. Using XDoclet markup Many Hibernate users prefer to embed mapping information directly in sourcecode using XDoclet @hibernate.1.id=id. private float weight.class * table="CATS" */ public class Cat { private Long id. since strictly it is considered part of XDoclet. private Set kittens private Color color.5.

This mechnism is more powerful than XDoclet annotations and better supported by tools and IDEs.sex=sex.2. IntelliJ IDEA.add(kitten).0 introduced XDoclet-style annotations at the language level. as a separate download. Using JDK 5.0 Annotations JDK 5.collection-key * column="PARENT_ID" * @hibernate. } /** * @hibernate.collection-one-to-many */ public Set getKittens() { return kittens. } void setKittens(Set kittens) { this. } /** * @hibernate.set * inverse="true" * order-by="BIRTH_DATE" * @hibernate. } } See the Hibernate web site for more examples of XDoclet and Hibernate. type-safe and checked at compile time.weight = weight.property * column="COLOR" * not-null="true" */ public Color getColor() { return color.2.0 annotations as the primary metadata mechanism for en- tity beans. The new revi- sion of the EJB specification (JSR-220) uses JDK 5. 5. Hibernate3 implements the EntityManager of JSR-220 (the persistence API).7 79 .property * column="SEX" * not-null="true" * update="false" */ public char getSex() { return sex. support for mapping metadata is available via the Hibernate Annotations package. This is an example of a POJO class annotated as an EJB entity bean: @Entity(access = AccessType. Both EJB3 (JSR-220) and Hibernate3 metadata is supported.color = color. } // addKitten not needed by Hibernate public void addKitten(Cat kitten) { kittens.FIELD) public class Customer implements Serializable { Hibernate 3.5. } void setColor(Color color) { this.kittens = kittens. supports auto-completion and syntax highlighting of JDK 5. } void setSex(char sex) { this. for example. } /** * @hibernate. Basic O/R Mapping } void setWeight(float weight) { this.0 annotations.

5.execute() method is valid here (ALTERs.. however.Statement.. @Embedded private Address homeAddress.9.0 Annotations (and JSR-220) is still work in progress and not completed.7 80 .11.10. String lastName..means that the given property value is not generated within the database. The first mode is to explicitly list the CREATE and DROP commands out in the mapping file: <hibernate-mapping> Hibernate 3. Things like created-date would fall into this category.7.2. Auxiliary Database Objects Allows CREATE and DROP of arbitrary database objects.states that the property value is generated both on insert and on update. // Getter/setter and business methods } Note that support for JDK 5.1. Long id. whenever Hibernate issues an SQL INSERT or UPDATE for an entity which has defined generated properties.states that the given property value is generated on insert. really any SQL com- mand that can be run via a java. in conjunction with Hibernate's schema evolution tools. it immediately issues a select afterwards to retrieve the generated values.. Date birthday. “property” can be marked as generated. Marking properties as generated. @Transient Integer age.1. String firstName.ALL) @JoinColumn(name="CUSTOMER_ID") Set<Order> orders. INSERTS.sql. Only Section 5. Properties marked as generated must additionally be non-insertable and non-updateable. Section 5. never (the default) . “timestamp (optional)”. Es- sentially. Although de- signed specifically for creating and dropping things like triggers or stored procedures.10. insert . “timestamp (optional)” properties can be marked as generated. Please refer to the Hibernate Annotations module for more details. always . etc). “version (optional)”. Hibernate ap- plications needed to refresh objects which contain any properties for which the database was generating val- ues.1. this option is not available there. to provide the ability to fully define a user schema within the Hibernate mapping files. and Section 5. lets the application delegate this responsibility to Hibernate. “version (optional)” and Section 5. There are essentially two modes for defining auxiliary database objects. Basic O/R Mapping @Id. @OneToMany(cascade=CascadeType. Note that even thought Section 5.6. but is not regenerated on subsequent up- dates. Typically.9. Generated Properties Generated properties are properties which have their values generated by the database.1.1. 5.

.. these database objects can be optionally scoped such that they only apply when certain dialects are used.. <database-object> <create>CREATE TRIGGER my_trigger .. Basic O/R Mapping ..2.AuxiliaryDatabaseObject interface..Oracle9iDialect"/> <dialect-scope name="org. <hibernate-mapping> .dialect.hibernate. This custom class must implement the org. <database-object> <definition class="MyTriggerDefinition"/> </database-object> </hibernate-mapping> Additionally...mapping.dialect.hibernate.Oracle10gDialect"/> </database-object> </hibernate-mapping> Hibernate 3. <hibernate-mapping> .7 81 .</create> <drop>DROP TRIGGER my_trigger</drop> </database-object> </hibernate-mapping> The second mode is to supply a custom class which knows how to construct the CREATE and DROP com- mands. <database-object> <definition class="MyTriggerDefinition"/> <dialect-scope name="org.hibernate.

Collections instances have the usual behavior of value types. Cat kitten = new DomesticCat(). TreeMap. Two entities may not share a refer- ence to the same collection instance.) Notice how we initialized the instance variable with an instance of HashSet.getKittens().util. java.util. You shouldn't have to worry much about any of this. Persistent collections Hibernate requires that persistent collection-valued fields be declared as an interface type. java.getKittens().util. Watch out for errors like this: Cat cat = new DomesticCat().UserCollectionType. cat.2.add(kitten).SortedMap or . Use persistent collections the same way you use ordinary Java collections.Set. When you make the instance per- sistent .List. Set kittens = new HashSet(). for example: public class Product { private String serialNumber.persist(cat).2. kittens = cat. } void setSerialNumber(String sn) { serialNumber = sn.usertype. collection-valued properties do not support null value semantics. .util.. 6.hibernate.. For ex- ample. } public String getSerialNumber() { return serialNumber.7 82 .by calling persist(). its elements might be moved from one table to another.SortedSet. If a collection is passed from one persistent object to another. Due to the underlying relational model.Chapter 6. kittens.Map. java. public Set getParts() { return parts.parts = parts.util. session. HashSet. java... kittens collection is a Set (HashSet) cat. <class name="Product"> <id name="serialNumber" column="productSerialNumber"/> Hibernate 3..Hibernate will actually replace the HashSet with an instance of Hibernate's own implementation of Set. java. anything you like! (Where "anything you like" means you will have to write an implementation of org. Collection Mapping 6. Collection mappings The Hibernate mapping element used for mapping a collection depends upon the type of the interface. // Okay.Collection. TreeSet or ArrayList. } void setParts(Set parts) { this.util. depending upon the interface type. Hibernate does not distinguish between a null collection reference and an empty collection. They are automatically persisted when referenced by a persistent object and automatically deleted when unreferenced. for example . // Error! The persistent collections injected by Hibernate behave like HashMap.setKittens(kittens). private Set parts = new HashSet(). } } The actual interface might be java. Just make sure you understand the semantics of bidirectional associations (discussed later).1. a <set> element is used for mapping properties of type Set. This is the best way to initialize collection valued properties of newly instantiated (non-persistent) instances.

defaults to 1) specify a "batch size" for lazily fetching instances of this collection...defaults to none) enable operations to cascade to child entities (7) sort (optional) specify a sorted collection with natural sort order.4 only) specify a table column (or columns) that define the iteration order of the Map.7 83 .. (12) access (optional . it is often reasonable to disable this setting.defaults to property name) the name of the collection table (not used for one-to-many associations) (3) schema (optional) the name of a table schema to override the schema declared on the root element (4) lazy (optional . The <map> element is representative: <map name="propertyName" (1) table="table_name" (2) schema="schema_name" (3) lazy="true|extra|false" (4) inverse="true|false" (5) cascade="all|none|save-update|delete|all-delete-orphan|delet(6)e-orphan" sort="unsorted|natural|comparatorClass" (7) order-by="column_name asc|desc" (8) where="arbitrary sql where condition" (9) fetch="join|select|subselect" (10) batch-size="N" (11) access="field|property|ClassName" (12) optimistic-lock="true|false" (13) mutable="true|false" (14) node="element-name|. defaults to select) Choose between outer-join fetching.defaults to false) mark this collection as the "inverse" end of a bidirectional associ- ation (6) cascade (optional . fetching by sequential select. /> </map> (1) name the collection property name (2) table (optional .. /> <element .defaults to true): Species that changes to the state of the collection results in increment of the owning entity's version.. (13) optimistic-lock (optional . and fetching by sequential subselect." embed-xml="true|false" > <key .. <bag>. or to enable "extra-lazy" fetching where most operations do not initialize the col- lection (suitable for very large collections) (5) inverse (optional .defaults to property): The strategy Hibernate should use for accessing the collection property value. Set or bag. together with an optional asc or desc (9) where (optional) specify an arbitrary SQL WHERE condition to be used when retrieving or removing the collection (useful if the collection should contain only a subset of the available data) (10) fetch (optional. Collection Mapping <set name="parts"> <key column="productSerialNumber" not-null="true"/> <one-to-many class="Part"/> </set> </class> Apart from <set>. /> <map-key .defaults to true) may be used to disable lazy fetching and specify that the association is always eagerly fetched. <map>.) (14) mutable (optional .2. <array> and <primitive-array> mapping elements. there is also <list>. (For one to many associations. JDK1.defaults to true): A value of false specifies that the elements of the collection never change (a minor performance optimization in some cases)... (11) batch-size (optional.. or a given comparator class (8) order-by (optional. Hibernate 3.

custom types. 6. Indexed collections All collection mappings. There may be a nullability constraint on the foreign key column. including all basic types. components.2. mapped with <composite-map-key>. references to other entities. The index of a Map may be of any basic type. only the "link" between the two objects is considered to be state held by the collection. 6. defaults to 0): The value of the index column that corresponds to the first element of the list or array. or it may be a composite type. with <one-to-many> or <many-to-many>. mapped with <map-key>. the next two are used to map entity associations. The first two map elements with value semantics.2. it may be an entity reference mapped with <map-key-many-to-many>. <key column="productSerialNumber" on-delete="cascade"/> See the previous chapter for a full definition of the <key> element. or List index. and of course. by default). except those with set and bag semantics. The mapped column contains sequential integers (numbered from zero. The index of an array or list is always of type integer and is mapped using the <list-index> element. This foreign key is referred to as the collection key column (or columns) of the collection table. Collection elements Collections may contain almost any other Hibernate type.1."/> (1) column_name (required): The name of the column holding the collection index values. Collection elements are mapped by <element> or <composite-element>. This is an important distinction: an object in a collection might be handled with "value" semantics (its lifecycle fully depends on the collection owner) or it might be a reference to another entity. In the latter case.7 84 .. <list-index column="column_name" (1) base="0|1|. The collection key column is mapped by the <key> element. with its own lifecycle. or Map key.. (1) base (optional.2. <map-key column="column_name" (1) formula="any SQL expression" (2) type="type_name" (3) node="@attribute-name" length="N"/> Hibernate 3.2. Collection foreign keys Collection instances are distinguished in the database by the foreign key of the entity that owns the collection. For uni- directional one to many associations.2. this is implied. <key column="productSerialNumber" not-null="true"/> The foreign key constraint may use ON DELETE CASCADE. or in the case of entity references. The contained type is referred to as the collection element type. the foreign key column is nullable by default. need an index column in the collection table - a column that maps to an array index. so you might need to spe- cify not-null="true". Collection Mapping 6. For most collections.3.

covering many common relational models. we use the <element> tag.2.2. We suggest you experiment with the schema generation tool to get a feeling for how various mapping declarations translate to database tables. (3) type (required): The type of the collection element. (2) formula (optional): An SQL formula used to evaluate the element. but it may be optionally sorted or ordered. Collection Mapping (1) column (optional): The name of the column holding the collection index values.4. A bag does not retain its order when it is retrieved from the database. you should map the property as a Hibernate <bag>. collection element column or columns and possibly an index column or columns. 6. If your table doesn't have an index column. For a collection of values. <element column="column_name" (1) formula="any SQL expression" (2) type="typename" (3) length="L" precision="P" scale="S" not-null="true|false" unique="true|false" node="element-name" /> (1) column (optional): The name of the column holding the collection element values. Collections of values and many-to-many associations Any collection of values or many-to-many association requires a dedicated collection table with a foreign key column or columns. <many-to-many column="column_name" (1) formula="any SQL expression" (2) class="ClassName" (3) fetch="select|join" (4) unique="true|false" (5) not-found="ignore|exception" (6) entity-name="EntityName" (7) property-ref="propertyNameFromAssociatedClass" (8) node="element-name" embed-xml="true|false" /> Hibernate 3. and you still wish to use List as the property type. (2) formula (optional): A SQL formula used to evaluate the key of the map. There are quite a range of mappings that can be generated for collections. <map-key-many-to-many column="column_name" (1) formula="any SQL expression" (2)(3) class="ClassName" /> (1) column (optional): The name of the foreign key column for the collection index values. (3) type (reguired): The type of the map keys. A many-to-many association is specified using the <many-to-many> element.7 85 . (3) class (required): The entity class used as the map key. (2) formula (optional): A SQL formula used to evaluate the foreign key of the map key.

Collection Mapping (1) column (optional): The name of the element foreign key column. (2) formula (optional): An SQL formula used to evaluate the element foreign key value.defaults to exception): Specifies how foreign keys that reference missing rows will be handled: ignore will treat a missing row as a null association. (5) unique (optional): Enable the DDL generation of a unique constraint for the foreign-key column. for full eager fetching (in a single SELECT) of an entity and its many-to-many rela- tionships to other entities.7 86 . (3) class (required): The name of the associated class. This makes the association multiplicity effectively one to many. Some examples. This is a special case.2. (4) fetch (optional .in this case. a many to many association: <array name="addresses" table="PersonAddress" cascade="persist"> <key column="personId"/> <list-index column="sortOrder"/> <many-to-many column="addressId" class="Address"/> </array> A map from string indices to dates: <map name="holidays" table="holidays" schema="dbo" order-by="hol_name asc"> <key column="id"/> <map-key column="hol_name" type="string"/> <element column="hol_date" type="date"/> </map> A list of components (discussed in the next chapter): <list name="carComponents" table="CarComponents"> <key column="carId"/> <list-index column="sortOrder"/> <composite-element class="CarComponent"> <property name="price"/> <property name="type"/> <property name="serialNumber" column="serialNum"/> Hibernate 3. first. (7) entity-name (optional): The entity name of the associated class. the primary key of the associated class is used. (6) not-found (optional . you would enable join fetching not only of the collection itself. but also with this attribute on the <many-to-many> nested element. as an alternative to class. (8) property-ref: (optional) The name of a property of the associated class that is joined to this foreign key.defaults to join): enables outer-join or sequential select fetching for this association. a set of strings: <set name="names" table="person_names"> <key column="person_id"/> <element column="person_name" type="string"/> </set> A bag containing integers (with an iteration order determined by the order-by attribute): <bag name="sizes" table="item_sizes" order-by="size asc"> <key column="item_id"/> <element column="size" type="integer"/> </bag> An array of entities . If not specified.

One-to-many associations A one to many association links the tables of two classes via a foreign key.3. This mapping loses certain semantics of normal Java collections: • An instance of the contained entity class may not belong to more than one instance of the collection • An instance of the contained entity class may not appear at more than one value of the collection index An association from Product to Part requires existence of a foreign key column and possibly an index column to the Part table. Very important note: If the foreign key column of a <one-to-many> association is declared NOT NULL.3. A <one-to-many> tag indicates that this is a one to many association. with no intervening collection table. Advanced collection mappings 6.5. Collection Mapping </composite-element> </list> 6. This example shows a map of Part entities by name (where partName is a persistent property of Part).util.SortedSet. you must declare the <key> mapping not-null="true" or use a bidirectional association with the collection mapping marked inverse="true". You must spe- cify a comparator in the mapping file: <set name="aliases" table="person_aliases" sort="natural"> <key column="person"/> Hibernate 3. Notice that the <one-to-many> element does not need to declare any columns. <one-to-many class="ClassName" (1) not-found="ignore|exception" (2) entity-name="EntityName" (3) node="element-name" embed-xml="true|false" /> (1) class (required): The name of the associated class. Nor is it necessary to specify the table name anywhere. Sorted collections Hibernate supports collections implementing java. See the discussion of bidirectional associations later in this chapter.SortedMap and java. Notice the use of a formula-based index.defaults to exception): Specifies how cached identifiers that reference missing rows will be handled: ignore will treat a missing row as a null association.util.2. (3) entity-name (optional): The entity name of the associated class. <map name="parts" cascade="all"> <key column="productId" not-null="true"/> <map-key formula="partName"/> <one-to-many class="Part"/> </map> 6.2.1. as an alternative to class. (2) not-found (optional .7 87 .

6..list(). not in memory.TreeSet or java.4 or higher (it is implemented using LinkedHashSet or LinkedHashMap). but it can not be an in- dexed collection).2.7 88 . Here's an example of a bidirectional many-to-many association. Collection Mapping <element column="name" type="string"/> </set> <map name="holidays" sort="my. hol_name"> <key column="year_id"/> <map-key column="hol_name" type="string"/> <element column="hol_date type="date"/> </map> Note that the value of the order-by attribute is an SQL ordering.HolidayComparator"> <key column="year_id"/> <map-key column="hol_name" type="string"/> <element column="hol_date" type="date"/> </map> Allowed values of the sort attribute are unsorted. sortedUsers = s.util.getUsers().name" ). This performs the ordering in the SQL query. natural and the name of a class implementing java.createFilter( group.TreeMap. <bag name="items" table="CATEGORY_ITEM"> <key column="CATEGORY_ID"/> Hibernate 3. not a HQL ordering! Associations may even be sorted by some arbitrary criteria at runtime using a collection filter().custom. Sorted collections actually behave like java. <set name="aliases" table="person_aliases" order-by="lower(name) asc"> <key column="person"/> <element column="name" type="string"/> </set> <map name="holidays" order-by="hol_date. This solution is only available under JDK 1. single-valued at the other many-to-many set or bag valued at both ends You may specify a bidirectional many-to-many association simply by mapping two many-to-many associations to the same database table and declaring one end as inverse (which one is your choice. each category can have many items and each item can be in many categories: <class name="Category"> <id name="id" column="CATEGORY_ID"/> . Bidirectional associations A bidirectional association allows navigation from both "ends" of the association.util.Comparator. "order by this. Two kinds of bidirectional association are supported: one-to-many set or bag valued at one end.util.2.3. If you want the database itself to order the collection elements use the order-by attribute of set.. bag or map mappings.

. these are or- thogonal concepts! 6..persist(category). If there is a property of the child class which maps to the index column.... <!-..getItems(). Bidirectional associations with indexed collections A bidirectional association where one end is represented as a <list> or <map> requires special consideration. no problem... Hibernate 3.add(item). <many-to-one name="parent" class="Parent" column="parent_id" not-null="true"/> </class> Mapping one end of an association with inverse="true" doesn't affect the operation of cascades..inverse end --> <bag name="categories" table="CATEGORY_ITEM" inverse="true"> <key column="ITEM_ID"/> <many-to-many class="Category" column="CATEGORY_ID"/> </bag> </class> Changes made only to the inverse end of the association are not persisted.. <set name="children" inverse="true"> <key column="parent_id"/> <one-to-many class="Child"/> </set> </class> <class name="Child"> <id name="id" column="child_id"/> . This is easier to understand if you think about the Java object model and how we create a many-to-many re- lationship in Java: category. // The category now "knows" about the relationship item. one link from A to B and another link from B to A.getCategories(). // The relationship won't be saved! session.. we can continue using in- verse="true" on the collection mapping: <class name="Parent"> <id name="id" column="parent_id"/> .3.add(category). // The relationship will be saved The non-inverse side is used to save the in-memory representation to the database. Collection Mapping <many-to-many class="Item" column="ITEM_ID"/> </bag> </class> <class name="Item"> <id name="id" column="CATEGORY_ID"/> . // The item now "knows" about the relationship session.7 89 . You may define a bidirectional one-to-many association by mapping a one-to-many association to the same ta- ble column(s) as a many-to-one association and declaring the many-valued end inverse="true".2. <class name="Parent"> <id name="id" column="parent_id"/> .persist(item). This means that Hibernate has two representations in memory for every bidirectional association.3.

.2.. the collection-valued end of the association is responsible for updates to the foreign key. Collection Mapping <map name="children" inverse="true"> <key column="parent_id"/> <map-key column="name" type="string"/> <one-to-many class="Child"/> </map> </class> <class name="Child"> <id name="id" column="child_id"/> . Instead. we could use the following mapping: <class name="Parent"> <id name="id" column="parent_id"/> ... In this case.. <map name="children"> <key column="parent_id" not-null="true"/> <map-key column="name" type="string"/> <one-to-many class="Child"/> </map> </class> <class name="Child"> <id name="id" column="child_id"/> . TODO: Does this really result in some unnecessary update statements? 6. <many-to-one name="parent" class="Parent" column="parent_id" insert="false" update="false" not-null="true"/> </class> Note that in this mapping.. <property name="name" not-null="true"/> <many-to-one name="parent" class="Parent" column="parent_id" not-null="true"/> </class> But..7 90 .. if there is no such property on the child class. we can't map the collection inverse="true". Ternary associations There are three possible approaches to mapping a ternary association..4. One is to use a Map with an association as its index: <map name="contracts"> <key column="employer_id" not-null="true"/> <map-key-many-to-many column="employee_id" class="Employee"/> <one-to-many class="Contract"/> </map> <map name="connections"> <key column="incoming_node_id"/> <map-key-many-to-many column="outgoing_node_id" class="Node"/> <many-to-many column="connection_id" class="Connection"/> Hibernate 3.3. we can't think of the association as truly bidirectional (there is information available at one end of the association that is not available at the other end).

Nevertheless. however. Note that the update performance of an <idbag> is much better than a regular <bag>! Hibernate can locate indi- vidual rows efficiently and update or delete them individually. Collection Mapping </map> A second approach is to simply remodel the association as an entity class. The <idbag> element lets you map a List (or Collection) with bag semantics..id=id. <idbag name="lovers" table="LOVERS"> <collection-id column="ID" type="long"> <generator class="sequence"/> </collection-id> <key column="PERSON1"/> <many-to-many column="PERSON2" class="Person" fetch="join"/> </idbag> As you can see. an <idbag> has a synthetic id generator. public long getId() { return id. } private void setId(long id) { this.2. which we will discuss later. .util. a pure association table doesn't seem to benefit much from a surrogate key (though a collection of composite val- ues might).7 91 . just like an entity class! A different surrogate key is assigned to each collection row. private Set children. A final alternative is to use composite elements.Set. the native identifier generation strategy is not supported for <idbag> collection identifiers. Hibernate provides a feature that allows you to map many to many associations and collections of values to a table with a surrogate key. Hibernate does not provide any mechanism to discover the surrogate key value of a particular row. Using an <idbag> If you've fully embraced our view that composite keys are a bad thing and that entities should have synthetic identifiers (surrogate keys). just like a list. public class Parent { private long id.5. } Hibernate 3.. } private Set getChildren() { return children. In the current implementation. So lets look at an example.3. } . This class: package eg. Collection examples The previous sections are pretty confusing. this point is quite arguable. import java. } private void setChildren(Set children) { this. This is the approach we use most commonly. map or set.. 6.. 6.. then you might find it a bit odd that the many to many associations and collections of values that we've shown so far all map to tables with composite keys! Now.children=children..4.

parent_id bigint not null ) alter table child add constraint childfk0 (parent_id) references parent Alternatively.7 92 . if you absolutely insist that this association should be unidirectional. the most natural mapping is a one- to-many association: <hibernate-mapping> <class name="Parent"> <id name="id"> <generator class="sequence"/> </id> <set name="children"> <key column="parent_id"/> <one-to-many class="Child"/> </set> </class> <class name="Child"> <id name="id"> <generator class="sequence"/> </id> <property name="name"/> </class> </hibernate-mapping> This maps to the following table definitions: create table parent ( id bigint not null primary key ) create table child ( id bigint not null primary key. name varchar(255). parent_id bigint ) alter table child add constraint childfk0 (parent_id) references parent If the parent is required. Collection Mapping has a collection of Child instances.2. use a bidirectional one-to-many association: <hibernate-mapping> <class name="Parent"> <id name="id"> <generator class="sequence"/> </id> <set name="children" inverse="true"> <key column="parent_id"/> <one-to-many class="Child"/> </set> </class> <class name="Child"> <id name="id"> <generator class="sequence"/> </id> <property name="name"/> <many-to-one name="parent" class="Parent" column="parent_id" not-null="true"/> </class> </hibernate-mapping> Notice the NOT NULL constraint: create table parent ( id bigint not null primary key ) create table child ( id bigint not null primary key. If each child has at most one parent. name varchar(255). you can declare the NOT NULL constraint on the <key> mapping: Hibernate 3.

a many-to-many association is appropriate: <hibernate-mapping> <class name="Parent"> <id name="id"> <generator class="sequence"/> </id> <set name="children" table="childset"> <key column="parent_id"/> <many-to-many class="Child" column="child_id"/> </set> </class> <class name="Child"> <id name="id"> <generator class="sequence"/> </id> <property name="name"/> </class> </hibernate-mapping> Table definitions: create table parent ( id bigint not null primary key ) create table child ( id bigint not null primary key. primary key ( parent_id. name varchar(255) ) create table childset ( parent_id bigint not null. Hibernate 3. child_id bigint not null. see Chapter 21. child_id ) ) alter table childset add constraint childsetfk0 (parent_id) references parent alter table childset add constraint childsetfk1 (child_id) references child For more examples and a complete walk-through a parent/child relationship mapping.7 93 .2. if a child might have multiple parents. we will catalog all possibilities in the next chapter. Collection Mapping <hibernate-mapping> <class name="Parent"> <id name="id"> <generator class="sequence"/> </id> <set name="children"> <key column="parent_id" not-null="true"/> <one-to-many class="Child"/> </set> </class> <class name="Child"> <id name="id"> <generator class="sequence"/> </id> <property name="name"/> </class> </hibernate-mapping> On the other hand. Ex- ample: Parent/Child. Even more exotic association mappings are possible.

and by multiplicity.2. Unidirectional associations 7. Association Mappings 7. one to one A unidirectional one-to-one association on a foreign key is almost identical. <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <many-to-one name="address" column="addressId" unique="true" not-null="true"/> </class> Hibernate 3. addressId bigint not null ) create table Address ( addressId bigint not null primary key ) 7.2. 7. starting with unidirectional mappings. In this section we'll go through the canonic- al cases one by one. <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <many-to-one name="address" column="addressId" not-null="true"/> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> </class> create table Person ( personId bigint not null primary key. so all our examples use not null foreign keys. Introduction Association mappings are the often most difficult thing to get right.1.2. We'll use Person and Address in all the examples. This is not a requirement of Hibernate.1.Chapter 7. Nullable foreign keys are not considered good practice in traditional data modelling.2. We'll classify associations by whether or not they map to an intervening join table. The only difference is the column unique constraint. many to one A unidirectional many-to-one association is the most common kind of unidirectional association. and the mappings will all work if you drop the nullability constraints.2.7 94 . and then considering the bidirectional cases.

<class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <set name="addresses"> <key column="personId" not-null="true"/> <one-to-many class="Address"/> </set> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> </class> create table Person ( personId bigint not null primary key ) create table Address ( addressId bigint not null primary key. (Notice that we've reversed the direction of the association in this example. one to many A unidirectional one-to-many association on a foreign key is a very unusual case. addressId bigint not null unique ) create table Address ( addressId bigint not null primary key ) A unidirectional one-to-one association on a primary key usually uses a special id generator. personId bigint not null ) We think it's better to use a join table for this kind of association.7 95 .) <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> </class> <class name="Address"> <id name="id" column="personId"> <generator class="foreign"> <param name="property">person</param> </generator> </id> <one-to-one name="person" constrained="true"/> </class> create table Person ( personId bigint not null primary key ) create table Address ( personId bigint not null primary key ) 7. and is not really recommen- ded.2. Hibernate 3.3.2. Association Mappings <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> </class> create table Person ( personId bigint not null primary key.

one to many A unidirectional one-to-many association on a join table is much preferred.2.3. addressId bigint not null ) create table Address ( addressId bigint not null primary key ) Hibernate 3.2. Association Mappings 7.7 96 . <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <join table="PersonAddress" optional="true"> <key column="personId" unique="true"/> <many-to-one name="address" column="addressId" not-null="true"/> </join> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null primary key.1. many to one A unidirectional many-to-one association on a join table is quite common when the association is optional.3. addressId bigint not null primary key ) create table Address ( addressId bigint not null primary key ) 7.3. Notice that by specifying unique="true". <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <set name="addresses" table="PersonAddress"> <key column="personId"/> <many-to-many column="addressId" unique="true" class="Address"/> </set> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId not null. we have changed the multiplicity from many-to-many to one-to-many. Unidirectional associations with join tables 7.

we have a unidirectional many-to-many association. primary key (personI create table Address ( addressId bigint not null primary key ) 7. one to one A unidirectional one-to-one association on a join table is extremely unusual. <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <set name="addresses" table="PersonAddress"> <key column="personId"/> <many-to-many column="addressId" class="Address"/> </set> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null.3. addressId bigint not null unique ) create table Address ( addressId bigint not null primary key ) 7.3.2. but possible. addressId bigint not null.4. Bidirectional associations Hibernate 3.3. many to many Finally. <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <join table="PersonAddress" optional="true"> <key column="personId" unique="true"/> <many-to-one name="address" column="addressId" not-null="true" unique="true"/> </join> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null primary key.4.7 97 . Association Mappings 7.

(This is the standard parent/ child relationship.2. Association Mappings 7. and let Hibernate manage the association from the collections side to maintain the index of each element (making the other side virtually inverse by setting update="false" and insert="false"): <class name="Person"> <id name="id"/> . one to one A bidirectional one-to-one association on a foreign key is quite common. addressId bigint not null ) create table Address ( addressId bigint not null primary key ) If you use a List (or other indexed collection) you need to set the key column of the foreign key to not null.4. <list name="people"> <key column="addressId" not-null="true"/> <list-index column="peopleIdx"/> <one-to-many class="Person"/> </list> </class> It is important that you define not-null="true" on the <key> element of the collection mapping if the underly- ing foreign key column is NOT NULL.. <class name="Person"> <id name="id" column="personId"> Hibernate 3.) <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <many-to-one name="address" column="addressId" not-null="true"/> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> <set name="people" inverse="true"> <key column="addressId"/> <one-to-many class="Person"/> </set> </class> create table Person ( personId bigint not null primary key. <many-to-one name="address" column="addressId" not-null="true" insert="false" update="false"/> </class> <class name="Address"> <id name="id"/> . one to many / many to one A bidirectional many-to-one association is the most common kind of association. but on the <key> element. Don't only declare not-null="true" on a possible nested <column> ele- ment. 7.1..2.4...7 98 .

7 99 .5. <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <set name="addresses" table="PersonAddress"> <key column="personId"/> <many-to-many column="addressId" unique="true" class="Address"/> Hibernate 3.2. addressId bigint not null unique ) create table Address ( addressId bigint not null primary key ) A bidirectional one-to-one association on a primary key uses the special id generator. Association Mappings <generator class="native"/> </id> <many-to-one name="address" column="addressId" unique="true" not-null="true"/> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> <one-to-one name="person" property-ref="address"/> </class> create table Person ( personId bigint not null primary key. or on the join.5. one to many / many to one A bidirectional one-to-many association on a join table. Bidirectional associations with join tables 7. <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <one-to-one name="address"/> </class> <class name="Address"> <id name="id" column="personId"> <generator class="foreign"> <param name="property">person</param> </generator> </id> <one-to-one name="person" constrained="true"/> </class> create table Person ( personId bigint not null primary key ) create table Address ( personId bigint not null primary key ) 7. Note that the inverse="true" can go on either end of the association.1. on the collection.

7 100 . addressId bigint not null primary key ) create table Address ( addressId bigint not null primary key ) 7.2. Association Mappings </set> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> <join table="PersonAddress" inverse="true" optional="true"> <key column="addressId"/> <many-to-one name="person" column="personId" not-null="true"/> </join> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null. one to one A bidirectional one-to-one association on a join table is extremely unusual. but possible.2. <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <join table="PersonAddress" optional="true"> <key column="personId" unique="true"/> <many-to-one name="address" column="addressId" not-null="true" unique="true"/> </join> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> <join table="PersonAddress" optional="true" inverse="true"> <key column="addressId" unique="true"/> <many-to-one name="person" column="personId" not-null="true" unique="true"/> </join> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null primary key.5. addressId bigint not null unique ) create table Address ( addressId bigint not null primary key ) Hibernate 3.

2. More complex association mappings More complex association joins are extremely rare.7 101 . primary key (personI create table Address ( addressId bigint not null primary key ) 7. effectiveEndDate and effectiveStartDatecolumns. addressId bigint not null.3. many to many Finally. imagine that the association between Employee and Organization is maintained in an Employment table full of historical employment data. For example. Then an association to the employee's most recent em- ployer (the one with the most recent startDate) might be mapped this way: Hibernate 3.5. we have a bidirectional many-to-many association. Hibernate makes it possible to handle more complex situ- ations using SQL fragments embedded in the mapping document. mapped as follows: <properties name="currentAccountKey"> <property name="accountNumber" type="string" not-null="true"/> <property name="currentAccount" type="boolean"> <formula>case when effectiveEndDate is null then 1 else 0 end</formula> </property> </properties> <property name="effectiveEndDate" type="date"/> <property name="effectiveStateDate" type="date" not-null="true"/> Then we can map an association to the current instance (the one with null effectiveEndDate) using: <many-to-one name="currentAccountInfo" property-ref="currentAccountKey" class="AccountInfo"> <column name="accountNumber"/> <formula>'1'</formula> </many-to-one> In a more complex example. <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <set name="addresses" table="PersonAddress"> <key column="personId"/> <many-to-many column="addressId" class="Address"/> </set> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> <set name="people" inverse="true" table="PersonAddress"> <key column="addressId"/> <many-to-many column="personId" class="Person"/> </set> </class> create table Person ( personId bigint not null primary key ) create table PersonAddress ( personId bigint not null. if a table with historical ac- count information data defines accountNumber.6. Association Mappings 7.

orgId from Employments group by orgId having startDate = max(startDate) </subselect> <many-to-one name="mostRecentEmployer" class="Organization" column="orgId"/> </join> You can get quite creative with this functionality. Association Mappings <join> <key column="employeeId"/> <subselect> select employeeId.7 102 . but it is usually more practical to handle these kinds of cases using HQL or a criteria query.2. Hibernate 3.

Hibernate 3. .util.birthday = birthday. Component Mapping The notion of a component is re-used in several different contexts.1. For example. public String getFirst() { return first. not an entity reference.Chapter 8. } . } private void setKey(String key) { this. private Name name... } public java. } void setLast(String last) { this. but doesn't need to declare any interfaces or identifier properties. String last.... throughout Hibernate. The term "compon- ent" refers to the object-oriented notion of composition (not to architecture-level components)..7 103 . Notice that Name defines getter and setter methods for its persistent properties.key=key. } public class Name { char initial. } public char getInitial() { return initial..initial = initial. private String key.name = name.last = last. } void setFirst(String first) { this.2. } } Now Name may be persisted as a component of Person. you might model a person like this: public class Person { private java.Date getBirthday() { return birthday.. Dependent objects A component is a contained object that is persisted as a value type.util. 8.Date birthday.first = first.. } public void setName(Name name) { this. } void setInitial(char initial) { this. String first. } public void setBirthday(java. public String getKey() { return key.util. for different purposes.. } public Name getName() { return name. } public String getLast() { return last.Date birthday) { this.

The <component> element allows a <parent> subelement that maps a property of the component class as a ref- erence back to the containing entity. only "the same" by value. but the two person objects would contain two independent name ojects. etc).Name" unique="true"> <parent name="namedPerson"/> <!-. The properties of a component may be of any Hibernate type (collections. first and last. When reloading the containing object. two persons could have the same name. <set name="someNames" table="some_names" lazy="true"> <key column="id"/> <composite-element class="eg. <class name="eg.2. In other words.7 104 .reference back to the Person --> <property name="initial"/> <property name="first"/> <property name="last"/> </component> </class> 8.Name"> <!-.Person" table="person"> <id name="Key" column="pid" type="string"> <generator class="uuid"/> </id> <property name="birthday" type="date"/> <component name="Name" class="eg. birthday. Hibernate 3.Name"> <!-. Hibernate is intended to sup- port a very fine-grained object model. it is very important to implement equals() and hashCode() correctly. This should be okay for most purposes.Person" table="person"> <id name="Key" column="pid" type="string"> <generator class="uuid"/> </id> <property name="birthday" type="date"/> <component name="Name" class="eg. Declare your component collection by re- placing the <element> tag with a <composite-element> tag.2.class attribute optional --> <property name="initial"/> <property name="first"/> <property name="last"/> </component> </class> The person table would have the columns pid. Nested components should not be considered an exotic usage. Component Mapping Our Hibernate mapping would look like: <class name="eg. components do not support shared references. Like all value types. Collections of dependent objects Collections of components are supported (eg. Hibernate will as- sume that if all component columns are null. then the entire component is null. an array of type Name).class attribute required --> <property name="initial"/> <property name="first"/> <property name="last"/> </composite-element> </set> Note: if you define a Set of composite elements. many-to-one associations. other components. initial. The null value semantics of a component are ad hoc.

Make sure you over- ride hashCode() and equals() correctly on the component class. A map- ping like this allows you to map extra columns of a many-to-many association table to the composite element class. Hi- bernate has to use each columns value to identify a record when deleting objects (there is no separate primary key column in the composite element table)... the relational model and persistence semantics are still slightly different. Remember that components are value types and don't allow shared references. 8. Please note that a composite element mapping doesn't support null-able properties if you're using a <set>.OrderLine"> <many-to-one name="purchaseDetails class="eg. If your composite element itself contains components.4. Component Mapping Composite elements may contain components but not collections. price and quantity are properties of the association: <class name="eg.. > .Purchase"> <property name="purchaseDate"/> <property name="price"/> <property name="quantity"/> <many-to-one name="item" class="eg.7 105 .Order" ..3. Even ternary (or quaternary. By this stage you should be asking yourself if a one-to-many associ- ation is more appropriate.a collection of compon- ents which themselves have components. Try remodelling the composite element as an entity . You have to either use only not-null properties in a composite-element or choose a <list>.Item"/> <!-. <map>.. <bag> or <idbag>.. This is a pretty exotic case . A special case of a composite element is a composite element with a nested <many-to-one> element. use the <nested-composite-element> tag. <set name="purchasedItems" table="purchase_items" lazy="true"> <key column="order_id"> <composite-element class="eg.2... A single Purchase can be in the set of an Order. there can't be a reference to the purchae on the other side. which is not possible with null values..Order" .Item"/> </composite-element> </set> </class> Composite elements may appear in queries using the same syntax as associations to other entities.. Components as Map indices The <composite-map-key> element lets you map a component class as the key of a Map.. > .. etc) associations are possible: <class name="eg. for bidirectional association navigation.Purchase"/> <many-to-one name="item" class="eg. 8. The following is a many-to-many association from Order to Item where purchaseDate. but it can't be referenced by the Item at the same time. <set name="purchasedItems" table="purchase_items" lazy="true"> <key column="order_id"> <composite-element class="eg. Components as composite identifiers You may use a component as an identifier of an entity class.class attribute is optional --> </composite-element> </set> </class> Of course.but note that even though the Java model is the same. Your component class must satisfy certain require- Hibernate 3.

. • It must re-implement equals() and hashCode().. Note: in Hibernate3. any foreign keys referencing the OrderLine table are also composite. Instead the application must assign its own identifiers. Component Mapping ments: • It must implement java. <class name="OrderLine"> <composite-id name="id" class="OrderLineId"> <key-property name="lineId"/> <key-property name="orderId"/> <key-property name="customerId"/> </composite-id> <property name="name"/> <many-to-one name="order" class="Order" insert="false" update="false"> <column name="orderId"/> <column name="customerId"/> </many-to-one> . You can't use an IdentifierGenerator to generate composite keys. An association to OrderLine would be mapped like this: <many-to-one name="orderLine" class="OrderLine"> <!-.7 106 . For example.Serializable.io. Use the <composite-id> tag (with nested <key-property> elements) in place of the usual <id> declaration.. But do it any- way. </class> Now.2.the "class" attribute is optional.) A many-to-many association to OrderLine also uses the composite foreign key: <set name="undeliveredOrderLines"> <key column name="warehouseId"/> <many-to-many class="OrderLine"> <column name="lineId"/> <column name="orderId"/> <column name="customerId"/> </many-to-many> </set> The collection of OrderLines in Order would use: <set name="orderLines" inverse="true"> <key> <column name="orderId"/> <column name="customerId"/> Hibernate 3. the OrderLine class has a primary key that depends upon the (composite) primary key of Order. You must declare this in your map- pings for other classes. the second requirement is not an absolutely hard requirement of Hibernate. as usual --> <column name="lineId"/> <column name="orderId"/> <column name="customerId"/> </many-to-one> (Note that the <column> tag is an alternative to the column attribute everywhere. consistently with the database's notion of composite key equality.

as usual. Even better. just by editing the mapping document. using a DOM parser. . declares no columns. <list name="deliveryAttempts"> <key> <!-... you can access (and change) Hibernate's configuration-time metamodel via the Configuration ob- ject.a collection inherits the composite key type --> <column name="lineId"/> <column name="orderId"/> <column name="customerId"/> </key> <list-index column="attemptId" base="1"/> <composite-element class="DeliveryAttempt"> ..... </composite-element> </set> </class> 8. <class name="OrderLine"> . Hibernate 3.2. Runtime manipulation of the mapping document is also possible. Component Mapping </key> <one-to-many class="OrderLine"/> </set> (The <one-to-many> element. The advantage of this kind of mapping is the ability to determine the actual properties of the bean at deployment time..7 107 .) If OrderLine itself owns a collection..5. Dynamic components You may even map a property of type Map: <dynamic-component name="userAttributes"> <property name="foo" column="FOO" type="string"/> <property name="bar" column="BAR" type="integer"/> <many-to-one name="baz" class="Baz" column="BAZ_ID"/> </dynamic-component> The semantics of a <dynamic-component> mapping are identical to <component>. it also has a composite foreign key.

</subclass> <subclass name="CashPayment" discriminator-value="CASH"> . <subclass name="CreditCardPayment" discriminator-value="CREDIT"> <property name="creditCardType" column="CCTYPE"/> .. and joined-subclass mappings in separate mapping docu- ments. Hibernate supports a fourth. CashPayment. ChequePayment.. Note: Previously this feature made the ordering of the mapping documents important.2. The Three Strategies Hibernate supports the three basic inheritance mapping strategies: • table per class hierarchy • table per subclass • table per concrete class In addition. Table per class hierarchy Suppose we have an interface Payment. union-subclass. directly beneath hibernate-mapping. It is possible to mix together the table per hierarchy and table per subclass strategies. It is possible to define subclass.. the ordering of mapping files does not matter when using the extends keyword.1. with implementors CreditCardPayment. and then make use of implicit polymorphism to achieve polymorphism across the whole hierarchy. Hibernate 3. This allows you to extend a class hierachy just by adding a new mapping file. However. You must specify an extends attribute in the subclass mapping. slightly different kind of polymorphism: • implicit polymorphism It is possible to use different mapping strategies for different branches of the same inheritance hierarchy..Chapter 9.7 108 . The ordering inside a single mapping file still needs to be defined as superclasses before subclasses. Inheritance Mapping 9.1. The table per hierarchy mapping would look like: <class name="Payment" table="PAYMENT"> <id name="id" type="long" column="PAYMENT_ID"> <generator class="native"/> </id> <discriminator column="PAYMENT_TYPE" type="string"/> <property name="amount" column="AMOUNT"/> ... by combining the <subclass> and <join> elements (see be- low). naming a previously mapped su- perclass. Hi- bernate does not support mixing <subclass>.1. <hibernate-mapping> <subclass name="DomesticCat" extends="Cat" discriminator-value="D"> <property name="name" type="string"/> </subclass> </hibernate-mapping> 9. under the the same <class> element. and <joined-subclass> and <union-subclass> mappings under the same root <class> element. Since Hibern- ate3.

.. The three subclass tables have primary key associations to the superclass table (so the relational model is actually a one-to-one association).. The approach taken by Hibernate is much more difficult to implement but argu- ably more correct from a relational point of view..3..7 109 . </subclass> </class> Exactly one table is required. Other object/ relational mappers use a different implementation of table per subclass which requires a type discriminator column in the superclass table. </joined-subclass> <joined-subclass name="CashPayment" table="CASH_PAYMENT"> <key column="PAYMENT_ID"/> . Inheritance Mapping </subclass> <subclass name="ChequePayment" discriminator-value="CHEQUE"> . <subclass name="CreditCardPayment" discriminator-value="CREDIT"> <join table="CREDIT_PAYMENT"> <key column="PAYMENT_ID"/> <property name="creditCardType" column="CCTYPE"/> . you may combine the use of <subclass> and <join>. using a discriminator Note that Hibernate's implementation of table per subclass requires no discriminator column.. may not have NOT NULL constraints. 9.2. such as CCTYPE. Table per subclass A table per subclass mapping would look like: <class name="Payment" table="PAYMENT"> <id name="id" type="long" column="PAYMENT_ID"> <generator class="native"/> </id> <property name="amount" column="AMOUNT"/> . 9. as follow: <class name="Payment" table="PAYMENT"> <id name="id" type="long" column="PAYMENT_ID"> <generator class="native"/> </id> <discriminator column="PAYMENT_TYPE" type="string"/> <property name="amount" column="AMOUNT"/> . </joined-subclass> <joined-subclass name="ChequePayment" table="CHEQUE_PAYMENT"> <key column="PAYMENT_ID"/> .. <joined-subclass name="CreditCardPayment" table="CREDIT_PAYMENT"> <key column="PAYMENT_ID"/> <property name="creditCardType" column="CCTYPE"/> . There is one big limitation of this mapping strategy: columns declared by the sub- classes.1.2.. </joined-subclass> </class> Four tables are required. Table per subclass.. If you would like to use a discriminator column with the table per subclass strategy...1.. </join> </subclass> <subclass name="CashPayment" discriminator-value="CASH"> <join table="CASH_PAYMENT"> <key column="PAYMENT_ID"/> Hibernate 3...

9. Mixing table per class hierarchy with table per subclass You may even mix the table per hierarchy and table per subclass strategies using this approach: <class name="Payment" table="PAYMENT"> <id name="id" type="long" column="PAYMENT_ID"> <generator class="native"/> </id> <discriminator column="PAYMENT_TYPE" type="string"/> <property name="amount" column="AMOUNT"/> .. </subclass> <subclass name="ChequePayment" discriminator-value="CHEQUE"> . Inheritance Mapping ... a polymorphic association to the root Payment class is mapped using <many-to-one>. <union-subclass name="CreditCardPayment" table="CREDIT_PAYMENT"> <property name="creditCardType" column="CCTYPE"/> . <class name="Payment"> <id name="id" type="long" column="PAYMENT_ID"> <generator class="sequence"/> </id> <property name="amount" column="AMOUNT"/> .. Table per concrete class There are two ways we could go about mapping the table per concrete class strategy.... </union-subclass> <union-subclass name="CashPayment" table="CASH_PAYMENT"> . The first is to use <union-subclass>.. </join> </subclass> </class> The optional fetch="select" declaration tells Hibernate not to fetch the ChequePayment subclass data using an outer join when querying the superclass... </subclass> </class> For any of these mapping strategies.5.2.4..1...7 110 . <many-to-one name="payment" column="PAYMENT_ID" class="Payment"/> 9. </union-subclass> Hibernate 3..1... </join> </subclass> <subclass name="CashPayment" discriminator-value="CASH"> .. <subclass name="CreditCardPayment" discriminator-value="CREDIT"> <join table="CREDIT_PAYMENT"> <property name="creditCardType" column="CCTYPE"/> .. </join> </subclass> <subclass name="ChequePayment" discriminator-value="CHEQUE"> <join table="CHEQUE_PAYMENT" fetch="select"> <key column="PAYMENT_ID"/> .

. <any name="payment" meta-type="string" id-type="long"> <meta-value value="CREDIT" class="CreditCardPayment"/> <meta-value value="CASH" class="CashPayment"/> <meta-value value="CHEQUE" class="ChequePayment"/> <column name="PAYMENT_CLASS"/> <column name="PAYMENT_ID"/> </any> Hibernate 3.6. indeed the primary key seed has to be shared accross all unioned subclasses of a hierarchy. </class> Notice that nowhere do we mention the Payment interface explicitly. in the mapping).. Table per concrete class.. (We might relax this in a future release of Hibernate. If you want to avoid duplication..1.2. Of course. </class> <class name="CashPayment" table="CASH_PAYMENT"> <id name="id" type="long" column="CASH_PAYMENT_ID"> <generator class="native"/> </id> <property name="amount" column="CASH_AMOUNT"/> . using implicit polymorphism An alternative approach is to make use of implicit polymorphism: <class name="CreditCardPayment" table="CREDIT_PAYMENT"> <id name="id" type="long" column="CREDIT_PAYMENT_ID"> <generator class="native"/> </id> <property name="amount" column="CREDIT_AMOUNT"/> . Each table defines columns for all properties of the class. The disadvantage of this approach is that Hibernate does not generate SQL UNIONs when performing poly- morphic queries.7 111 .. an additional table (defaults to PAYMENT in the example above) is needed to hold instances of the superclass. consider using XML entities (e. map it with abstract="true". For this mapping strategy. The limitation of this approach is that if a property is mapped on the superclass...xml"> ] in the DOCTYPE declartion and &allproperties. Inheritance Mapping <union-subclass name="ChequePayment" table="CHEQUE_PAYMENT"> . Also notice that properties of Payment are mapped in each of the subclasses. if it is not abstract..g. the column name must be the same on all subclass tables. includ- ing inherited properties. a polymorphic association to Payment is usually mapped using <any>. If your superclass is abstract. 9. </union-subclass> </class> Three tables are involved for the subclasses. </class> <class name="ChequePayment" table="CHEQUE_PAYMENT"> <id name="id" type="long" column="CHEQUE_PAYMENT_ID"> <generator class="native"/> </id> <property name="amount" column="CHEQUE_AMOUNT"/> . [ <!ENTITY allproperties SYSTEM "allproperties.) The identity generator strategy is not allowed in union subclass inheritance.

one-to-one one. load()/get queries joins to-one to-many to-many () table per <many-to-o <one-to-on <one-to-ma <many-to-m s.) <class name="CreditCardPayment" table="CREDIT_PAYMENT"> <id name="id" type="long" column="CREDIT_PAYMENT_ID"> <generator class="native"/> </id> <discriminator column="CREDIT_CARD" type="string"/> <property name="amount" column="CREDIT_AMOUNT"/> . from Order class. </joined-subclass> </class> Once again. each of the subclasses could easily be part of another inheritance hierarchy! (And you can still use polymorphic queries against the Payment interface..1.. we don't mention Payment explicitly.1. 9.7. </joined-subclass> <joined-subclass name="ChequePayment" table="CHEQUE_PAYMENT"> <key column="PAYMENT_ID"/> <property name="amount" column="CHEQUE_AMOUNT"/> ...7 112 ..Hibernate automatically returns instances of CreditCardPayment (and its subclasses. from Payment . The following table shows the limitations of table per concrete-class mappings. and of implicit polymorphism. <joined-subclass name="CashPayment" table="CASH_PAYMENT"> <key column="PAYMENT_ID"/> <property name="amount" column="CASH_AMOUNT"/> .payment p Hibernate 3. Poly. Features of inheritance mappings Inherit.2. Poly. many..2.. Since the subclasses are each mapped in their own <class> element (and since Payment is just an interface). There are somewhat less restrictive limitations to <union-subclass> mappings. since they also implement Payment).. Poly. Poly. Table 9. CashPayment and ChequePayment but not instances of Nonelectronic- Transaction.class.get(Paym from Pay. Poly. Inheritance Mapping 9.for ex- ample. Poly- ance morphic morphic morphic morphic morphic morphic morphic strategy many. Poly. Mixing implicit polymorphism with other inheritance mappings There is one further thing to notice about this mapping. If we execute a query against the Payment interface . <subclass name="MasterCardPayment" discriminator-value="MDC"/> <subclass name="VisaPayment" discriminator-value="VISA"/> </class> <class name="NonelectronicTransaction" table="NONELECTRONIC_TXN"> <id name="id" type="long" column="TXN_ID"> <generator class="native"/> </id> . ment p o join hierarchy id) o. Limitations There are certain limitations to the "implicit polymorphism" approach to the table per concrete-class mapping strategy. in Hibernate. ne> e> ny> any> ent.

load()/get queries joins to-one to-many to-many () table per <many-to-o <one-to-on <one-to-ma <many-to-m s.ad polymorph. Inheritance Mapping Inherit. not suppor- concrete ted ted ny> iter. Poly.class. Poly. Poly. Poly. from Order concrete.7 113 .get(Paym from Pay. Poly.2. id) o.payment (union-subc verse="tru p lass) e" only) table per <any> not suppor. one-to-one one. many. d( Re- ism) stric- tions. ment p o join id) o.idEq (id) ).uniqueRe sult() Hibernate 3. ment p ted class ia(Payment (implicit .payment p table per <many-to-o <one-to-on <one-to-ma <many-to-m s. Poly- ance morphic morphic morphic morphic morphic morphic morphic strategy many.<many-to-a s.class).class. Poly. from Order subclass ne> e> ny> any> ent.createCr from Pay. ne> e> ny> (for any> ent. ment p o join class in.not suppor.get(Paym from Pay.

This part is taken care of by Hibernate and is only relevant for the application developer when tuning the performance of the system. or a composite key.GINGER).Chapter 10.2. This feature enables a programming model for long running units of work that require user think-time. the identifier is generated and assigned to the cat when save() is called. Hibernate object states Hibernate defines and supports the following object states: • Transient . • Persistent . We'll now discuss the states and state transitions (and the Hibernate methods that trigger a transition) in more detail.e.setSex('M'). A detached instance can be reattached to a new Session at a later point in time.an object is transient if it has just been instantiated using the new operator. making it (and all the modifications) persistent again. • Detached . fritz. Working with objects Hibernate is a full object/relational mapping solution that not only shields the developer from the details of the underlying database management system. and not necessarily about the execution of SQL statements. The reference to the object is still valid. 10. or DELETE statements when an object should be made transient. a unit of work from the point of view of the user. the identifier should be assigned to the cat instance before calling save(). fritz. fritz. If Cat has a generated identifier.save(fritz).a detached instance is an object that has been persistent. We call them application transactions.2. It might just have been saved or loaded. Transient instances will be destroyed by the garbage collector if the application doesn't hold a reference anymore. it is by definition in the scope of a Session.setColor(Color. This is. of course. with the semantics defined in the EJB3 early Hibernate 3. but its Session has been closed. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition). but also offers state management of objects.a persistent instance has a representation in the database and an identifier value. however.7 114 . Long generatedId = (Long) sess. and it is not associ- ated with a Hibernate Session.1. If Cat has an assigned identifier. and the detached instance might even be modified in this state. a very natural object-oriented view of persistence in Java applications. Developers don't execute manual UPDATE statements. i. We can make a tran- sient instance persistent by associating it with a session: DomesticCat fritz = new DomesticCat(). 10. You may also use persist() instead of save(). In other words. Making objects persistent Newly instantiated instances of a a persistent class are considered transient by Hibernate. Hibernate application developers should always think about the state of their objects.setName("Fritz"). It has no persistent representation in the database and no identifier value has been assigned. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. contrary to the management of SQL statements in common JDBC/SQL persistence layers.

load(Cat. load() takes a class object and will load the state into a newly instantiated instance of that class. Then.get(Cat.TABBY)..class. Cat cat = (Cat) sess. Set kittens = cat.setSex('F').getKittens().class. you might violate a NOT NULL constraint if you save() the objects in the wrong order. If you are not certain that a matching row exists. This behaviour is very useful if you wish to create an association to an object without actually loading it from the database. in persist- ent state. DomesticCat pk = new DomesticCat(). See the API docu- Hibernate 3.setName("PK"). pk. generatedId).class. Loading an object The load() methods of Session gives you a way to retrieve a persistent instance if you already know its identi- fier. the kittens collection in the previous example). If the class is mapped with a proxy. DomesticCat pk = (DomesticCat) sess. using a LockMode.3. new Long(pkId) ). // you need to wrap primitive identifiers long id = 1234. pk. Working with objects draft. these objects may be made persistent in any order you like unless you have a NOT NULL constraint upon a for- eign key column. load() just returns an uninitialized proxy and does not actually hit the database until you invoke a method of the proxy. You may even load an object using an SQL SELECT . new Long(1234) ).Hibernate will take care of everything. // load pk's state into cat sess.save(cat. Usually you don't bother with this detail. id). even NOT NULL constraint violations don't occur .. } return cat. you may assign the identifier using an overloaded version of save().setKittens( new HashSet() ). Alternatively. Cat fritz = (Cat) sess. pk. id). you should use the get() method. FOR UPDATE.7 115 .save( pk.setColor(Color. 10. pk. Transitive persistence is discussed later in this chapter. pk. if (cat==null) { cat = new Cat(). you can load state into a given instance: Cat cat = new DomesticCat(). If the object you make persistent has associated objects (e. It also allows multiple instances to be loaded as a batch if batch- size is defined for the class mapping. new Long(id) ). However. sess.load( cat.2. sess. There is never a risk of violating foreign key constraints. as you'll very likely use Hibernate's transitive persistence feature to save the associated objects automatically.g. which hits the database im- mediately and returns null if there is no matching row. Alternatively.addKitten(fritz).load( DomesticCat. Note that load() will throw an unrecoverable exception if there is no matching database row.

pk) .1. This interface offers methods for parameter binding.list().createQuery( "select cat.4. It is possible to re-load an object and all its collections at any time. Set uniqueMothers = new HashSet(mothersWithKittens.list().name = ?") .list(). 10. Entity instances retrieved by a query are in persistent state. Hibernate supports an easy-to-use but powerful object oriented query language (HQL).mother from Cat as cat where cat = ?") .7 116 . name) . You may also express your query in the native SQL of your database. the result of the query will be loaded completely into a collec- tion in memory.setDate(0.createQuery( "from Cat as cat where cat. The uniqueResult() method offers a shortcut if you know your query will only return a single object. List mothers = session. you need a query.mother as mother where cat.hibernate.createQuery( "select mother from Cat as cat join cat.2.setString(0.class. using the refresh() method. Note that queries that make use of eager Hibernate 3.mother = ?") .UPGRADE).get(Cat.refresh(cat). A query is usually executed by invoking list(). LockMode. result set handling. 10. Note that any associated instances or contained collections are not selected FOR UPDATE. Cat cat = (Cat) sess.list()). sess.setEntity(0.uniqueResult(). id. with optional support from Hibernate for result set conversion into objects.createQuery( "from Cat as cat where cat. This is useful when database triggers are used to initialize some of the properties of the object. Hibernate supports a sophisticated Criteria and Example query feature (QBC and QBE). List kittens = session.setEntity(0. Working with objects mentation for more information.]] Query mothersWithKittens = (Cat) session. “Fetching strategies”. izi) .4. unless you decide to specify lock or all as a cascade style for the association.flush(). Querying If you don't know the identifiers of the objects you are looking for. date) .save(cat). sess.createQuery( "select mother from Cat as mother left join fetch mother.kittens"). For programmatic query creation. and for the execution of the actual query.birthdate < ?") . //re-read the state (after the trigger executes) An important question usually appears at this point: How much does Hibernate load from the database and how many SQL SELECTs will it use? This depends on the fetching strategy and is explained in Section 19.1. Executing queries HQL and native SQL queries are represented with an instance of org. Cat mother = (Cat) session. //force the SQL INSERT sess.Query. You always ob- tain a Query using the current Session: List cats = session.

you might be able to achieve better performance by executing the query using the iterate() method.list() . iterate() will be slower than list() and might require many database hits for a simple query.createQuery("from eg.createQuery( "select cat.... } Bind parameters Hibernate 3.2.color. usually 1 for the initial select which only returns identifiers. } Scalar results Queries may specify a property of a class in the select clause. Working with objects fetching of collections usually return duplicates of the root objects (but with their collections initialized). .Qux q order by q. mother from Cat kitten join kitten. // dont need to process the rest break.createQuery( "select kitten. They may even call SQL aggregate functions. Integer count = (Integer) row[2].hasNext() ) { Object[] row = (Object[]) results.list() .next().calculateComplicatedAlgorithm() ) { // delete the current instance iter. min(cat. // fetch ids Iterator iter = sess. This will only usually be the case if you expect that the actual entity instances returned by the query will already be in the session or second-level cache. Color type = (Color) row[0].7 117 . while ( iter.next(). } } Queries that return tuples Hibernate queries sometimes return tuples of objects.next(). Date oldest = (Date) row[1].iterator(). Cat mother = tuple[1]..likeliness"). and n additional selects to initialize the actual instances.. while ( kittensAndMothers..mother mother") . in which case each tuple is returned as an array: Iterator kittensAndMothers = sess. You can filter these duplicates simply through a Set.hasNext() ) { Qux qux = (Qux) iter.remove()..iterate(). Properties or aggregates are considered "scalar" results (and not entities in persistent state). . If they are not already cached. Cat kitten = tuple[0].hasNext() ) { Object[] tuple = (Object[]) kittensAndMothers.color") . count(cat) from Cat cat " + "group by cat. // fetch the object // something we couldnt express in the query if ( qux.birthdate).iterator(). Iterating results Occasionally. Iterator results = sess. while ( results.

createQuery("from DomesticCat cat"). q. // Now get the first page of cats pageOfCats = new ArrayList().name.iterate(). The advantages of named parameters are: • named parameters are insensitive to the order they occur in the query string • they may occur multiple times in the same query • they are self-documenting //named parameter (preferred) Query q = sess.createQuery("from DomesticCat cat where cat.get(1) ). "Fritz"). Iterator cats = q.first() ) { // find the first name on each page of an alphabetical list of cats by name firstNamesOfPages = new ArrayList().2. q.createQuery("from DomesticCat cat where cat.scroll(PAGE_SIZE) ). cats.setParameterList("namesList".setString(0. Hibernate 3.add("Izi").add(name). q. names. names).add( cats. Hibernate knows how to translate this limit query into the native SQL of your DBMS.name in (:namesList)"). //named parameter list List names = new ArrayList(). Contrary to JDBC.list().beforeFirst().name = :name"). q. the Query interface may be used to obtain a Scrolla- bleResults object.next() ) pageOfCats. int i=0.setMaxResults(10).list(). if ( cats. firstNamesOfPages. Named parameters are identifiers of the form :name in the query string.name = ?"). names.createQuery("from DomesticCat cat where cat.iterate().setFirstResult(20).add("Fritz"). do { String name = cats.setString("name". Scrollable iteration If your JDBC driver supports scrollable ResultSets. "Izi"). Pagination If you need to specify bounds upon your result set (the maximum number of rows you want to retrieve and / or the first row you want to retrieve) you should use methods of the Query interface: Query q = sess. ScrollableResults cats = q. Query q = sess. Query q = sess. while( ( PAGE_SIZE > i++ ) && cats. List cats = q. Hibernate numbers parameters from zero.scroll(). cat from DomesticCat cat " + "order by cat. Working with objects Methods on Query are provided for binding values to named parameters or JDBC-style ? parameters.7 118 .getString(0). which allows flexible navigation of the query results. q. //positional parameter Query q = sess. } while ( cats. Iterator cats = q.createQuery("select cat. List cats = q.name").

custom(ColorUserType.createFilter( mother. you may also define native SQL queries in metadata.name = ? and cat.color = eg. for example eg. Even an empty filter query is useful. Also note that a query declaration inside a <hibernate-mapping> element requires a global unique name for the query.weight > ? ] ]></query> Parameter binding and executing is done programatically: Query q = sess.setString(0.2.setParameter( Color. 10. or migrate existing queries to Hibernate by placing them in mapping files. The query string may refer to this. "") Hibernate 3. q.getNamedQuery("ByNameAndMaximumWeight").list(). Collection blackKittenMates = session.getKittens(). Observe that filters do not require a from clause (though they may have one if required).close() Note that an open database connection (and cursor) is required for this functionality. and it's a copy of the given collection.2.4.ByNameAndMaximumWeight. Note that the actual program code is independent of the query language that is used.createFilter( pk. to load a subset of elements in a huge collection: Collection tenKittens = session.Cat. use setMaxResult()/set- FirstResult() if you need offline pagination functionality. "select this.createFilter( pk.setInt(1. Working with objects } cats. Filtering collections A collection filter is a special type of query that may be applied to a persistent collection or array.intValue") . e. meaning the current collection element. Filters are not limited to returning the collection elements themselves. Externalizing named queries You may also define named queries in the mapping document.BLACK.DomesticCat as cat where cat. The returned collection is considered a bag. q. "where this.list() ).7 119 . (Remember to use a CDATA section if your query contains characters that could be interpreted as markup.Color.list().BLACK. The original collection is not modified (this is contrary to the implication of the name "filter". Collection blackKittens = session. minWeight).class) ) .getKittens().mate where this. Hibernate.g. List cats = q. name). but consistent with expected behavior). while a query declaration inside a <class> element is made unique automatically by prepending the fully qualified name of the class.getKittens().) <query name="ByNameAndMaximumWeight"><![CDATA[ from eg.color = ?") .

Color.class ). just like Hibernate queries. using createSQLQuery() and let Hibernate take care of the mapping from result sets to objects. Hibernate provides an intuitive Criteria query API for these cases: Criteria crit = session. you must enclose SQL aliases in braces: List cats = session.4.flush().5.SUBCLASS AS {cat.add( Expression. crit.list().list().class ).list(). More information about native SQL queries in Hibernate can be found in Chapter 16. The Criteria and the associated Example API are discussed in more detail in Chapter 15. // changes to cat are automatically detected and persisted Sometimes this programming model is inefficient since it would require both an SQL SELECT (to load an ob- ject) and an SQL UPDATE (to persist its updated state) in the same session. "cat". Native SQL.mate}.setName("PK"). saved. 10. Note that you may at any time call session. {cat}.class).4. Working with objects .createSQLQuery( "SELECT {cat}. sess. rather than building query strings. Therefore Hibernate offers an altern- ate approach. So the most straightforward way to update the state of an object is to load() it.SEX AS {cat.MATE AS {cat.7 120 .createSQLQuery( "SELECT {cat. "cat".setFirstResult(0).2.load( Cat. If you chose to use the Hibernate API. Criteria queries HQL is extremely powerful but some developers prefer to build queries dynamically..BLACK ) ).ID AS {cat. There is no need to call a particular method (like update(). eg. 10. " + "{cat}. 10. List cats = session. objects loaded.3. {cat}. Queries in native SQL You may express a query in SQL.*} FROM CAT {cat} WHERE ROWNUM<10".setMaxResults(10) . crit. Hibernate 3. Criteria Queries. Modifying persistent objects Transactional persistent instances (ie.class. created or queried by the Session) may be manip- ulated by the application and any changes to persistent state will be persisted when the Session is flushed (discussed later in this chapter). using detached instances.connection() and use the JDBC Connection directly. and then manipulate it directly.sex}.4. using an object-oriented API. Cat. .list() SQL queries may contain named and positional parameters. List cats = crit. Cat. which has a differ- ent purpose) to make your modifications persistent.class}. " + "FROM CAT {cat} WHERE ROWNUM<10".eq( "color".id}.setMaxResults(10). while the Session is open: DomesticCat cat = (DomesticCat) sess. new Long(69) ).. cat.createCriteria(Cat.

LockMode. This can be automated of course. //do a version check. you can get a JDBC Connection at any time by calling session.merge() methods: // in the first session Cat cat = (Cat) firstSession. the notion of mass operations conflicts with object/relational mapping for online transaction processing- oriented applications. you don't have to think in statements to use it.. Working with objects Note that Hibernate does not offer its own API for direct execution of UPDATE or DELETE statements.2.7 121 . LockMode.connection(). see Section 10. then reassociate: sess. Modifying detached objects Many applications need to retrieve an object in one transaction. Reattachment is not the only usecase for lock().6.setMate(potentialMate).class. Hibernate supports this model by providing for reattachment of detached instances using the Ses- sion.update(mate). send it to the UI layer for manipulation. catId).NONE). then reassociate: sess. Future versions of Hibernate may however provide special mass operation functions. and merge() if you want to merge your modifications at any time without consideration of the state of the session. an exception would have been thrown. “Optimistic concurrency control”. LockMode. Further- more. firstSession.11.lock(fritz.save(potentialMate).UPGRADE). “Transitive persistence”.3. update() is usually the first method you would call in a fresh session.load(Cat. // in a higher layer of the application cat. However. 10. Other models for long units of work are discussed in Section 11. See Chapter 13. Hibernate is a state management service. in a new session secondSession.lock(pk. JDBC is a perfect API for execut- ing SQL statements. then save the changes in a new transaction.READ). //do a version check. the de- tached instance has to be unmodified! //just reassociate: sess. In other words. Batch processing for some possible batch operation tricks.lock(izi. using transitive persistence. using SELECT . The lock() method also allows an application to reassociate an object with a new session. // update mate If the Cat with identifier catId had already been loaded by secondSession when the application tried to reat- tach it. ensuring that reattachment of your detached instances is the first operation that is executed. FOR UPDATE. Hibernate 3.update(cat).update() or Session. see the API documentation and the chapter on transac- tion handling for more information. Cat potentialMate = new Cat(). Use update() if you are sure that the session does not contain an already persistent instance with the same identifier. // later. Note that lock() can be used with various LockModes. The application should individually update() detached instances reachable from the given detached instance if and only if it wants their state also updated. // update cat secondSession.. Applications that use this kind of approach in a high-concurrency envir- onment usually use versioned data to ensure isolation for the "long" unit of work.

save() it • otherwise update() the object and merge() is very different: • if there is a persistent instance with the same identifier currently associated with the session. Automatic state detection Hibernate users have requested a general purpose method that either saves a transient instance by generating a new identifier or updates/reattaches the detached instances associated with its current identifier.class. try to load it from the database. save() it • if the object is versioned (by a <version> or <timestamp>). Working with objects 10.7. Hibernate 3. // in the first session Cat cat = (Cat) firstSession. your application might still hold a reference to a deleted object. do nothing • if another object associated with the session has the same identifier. sa- veOrUpdate(). Some whole applications will never use either of these methods. it remains detached 10. so long as you are not trying to use instances from one session in another new session.saveOrUpdate(mate).7 122 . // update existing state (cat has a non-null id) secondSession. Usually update() or saveOrUpdate() are used in the following scenario: • the application loads an object in the first session • the object is passed up to the UI tier • some modifications are made to the object • the object is passed back down to the business logic tier • the application persists these modifications by calling update() in a second session saveOrUpdate() does the following: • if the object is already persistent in this session. Firstly. It's best to think of delete() as making a persistent instance transient. and the version property value is the same value assigned to a newly instantiated object.saveOrUpdate(cat). cat.delete() will remove an object's state from the database. // in a higher tier of the application Cat mate = new Cat(). save() it • if the object's identifier has the value assigned to a newly instantiated object. catID). throw an exception • if the object has no identifier property. The saveOrUp- date() method implements this functionality. Deleting persistent objects Session. or merge().delete(cat). or create a new persistent instance • the persistent instance is returned • the given instance does not become associated with the session.setMate(mate). in a new session secondSession. // later. you should not need to use update(). sess. Of course. // save the new instance (mate has a null id) The usage and semantics of saveOrUpdate() seems to be confusing for new users.8.2. copy the state of the given object onto the persistent instance • if there is no persistent instance currently associated with the session.load(Cat.

commit(). in the same order the corresponding objects were saved using Session. It is still pos- sible to violate a NOT NULL constraint on a foreign key column by deleting objects in the wrong order.openSession().close().replicate(cat.get(Cat. catId). Flushing the Session From time to time the Session will execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in memory. without regenerating identifier values. Replicating object between two different datastores It is occasionally useful to be able to take a graph of persistent instances and make them persistent in a different datastore. updates and insertions 5.9. or ignore the object otherwise Usecases for this feature include reconciling data entered into different database instances. 10. all entity deletions.g.openSession().hibernate.Transaction. all collection deletions 4. session2. Transaction tx1 = session1.beginTransaction(). ReplicationMode.OVERWRITE . in the same order the corresponding objects were deleted using Session. but forget to delete the children.beginTransaction(). rolling back changes made during non-ACID transactions and more. //retrieve a cat from one database Session session1 = factory1. all collection insertions 6. all entity insertions.7 123 . Transaction tx2 = session2. Working with objects You may delete objects in any order you like.10. upgrading system configuration information during product upgrades. • ReplicationMode.flush() The SQL statements are issued in the following order 1. without risk of foreign key constraint violations.2. all collection element deletions. Cat cat = session1. if you delete the parent.delete() Hibernate 3. The ReplicationMode determines how replicate() will deal with conflicts with existing rows in the database.overwrite any existing database row with the same identifier • ReplicationMode. tx2.LATEST_VERSION). 10.IGNORE .EXCEPTION .save() 2. e. occurs by default at the following points • before some query executions • from org.commit() • from Session. //reconcile with a second database Session session2 = factory2. tx1. all entity updates 3.class.close(). This process.LATEST_VERSION . flush.overwrite the row if its version number is earlier than the version number of the object.throw an exception if there is an existing database row with the same identi- fier • ReplicationMode. session2. session1.ignore the object when there is an existing database row with the same identifi- er • ReplicationMode.commit().

setFlushMode(FlushMode. sess = sf. since value-typed objects can't have shared references. where a Session is kept open and disconnected for a long time (see Sec- tion 11. or reattach individual objects. During flush. refresh. etc. “Extended session and automatic versioning”). // might return stale data sess. delete.2. an exception might occur (e. merge(). delete. you must indicate that in the mapping document. we discuss it in Chapter 11. delete the child from the database. replicate. saveOrUpdate().find("from Cat as cat left outer join cat.commit(). The FlushMode class defines three different modes: only flush at commit time (and only when the Hibernate Transaction API is used). Transac- tions And Concurrency. the cascade styles are named create. id). izi.close(). only the order in which they are executed. 10.. Entities have their own lifecycle. support shared references (so removing an entity from the collection does not mean it can be deleted).class. a collection of addresses or strings). Transitive persistence It is quite cumbersome to save. It is possible to change the default behavior so that flush occurs less frequently. de- lete(). when the parent is deleted. Transaction tx = sess. // allow queries to return stale state Cat izi = (Cat) sess. nor will they return the wrong data.there is a corresponding cascade style. or never flush unless flush() is called explicitly. categories and items.11. save-update. their lifecycle would depend on the parent and no further action would be required for convenient "cascading" of state changes.g. lock().kittens kitten").. or parent and child cats). the children will be deleted. there are absolutely no guarantees about when the Session executes the JDBC calls. Consider the following example: If the children in a parent/child relationship would be value typed (e. and there is by default no cascading of state from one entity to any other associated entities.7 124 .g.openSession(). Respectively. Since handling excep- tions involves some understanding of Hibernate's transactional behavior. Hibernate will detect this and. // flush occurs sess. When the parent is saved. not value-types (e. especially if you deal with a graph of as- sociated objects.3. if a DML operation violates a constraint). flush automatically using the explained routine. This even works for operations such as the removal of a child from the collection. evict().2. lock. Hibernate does guarantee that the Query. However. If you want an operation to be cascaded along an association. evict.) will never return stale data. the value-typed child objects are saved as well.load(Cat.including persist(). replicate() .setName(iznizi). Hibernate does not implement persistence by reachability by default.COMMIT). tx. A common case is a parent/child relationship. refresh(). Working with objects (An exception is that objects using native ID generation are inserted when they are saved.) Except when you explicity flush(). // change to izi is not flushed! . sess. For example: <one-to-one name="person" cascade="persist"/> Hibernate 3. For each basic operation of the Hibernate session . merge. The last mode is useful for long running units of work. Now consider the same scenario with parent and child objects being entities..list(.beginTransaction().g.

The precise semantics of cascading operations for a parent/child relationship are as follows: • If a parent is passed to persist(). Mapping an association (either a single valued association. note that cascading of operations can be applied to an object graph at call time or at flush time. all children are passed to saveOrUpdate() • If a transient or detached child becomes referenced by a persistent parent..delete. Cat fritz = . the application might use Hibernate's metadata to implement a "smart" deep-copy algorithm that understands which objects should be copied (eg. For example. • Otherwise. consider us- ing cascade="persist. associated entities). Hibernate 3. • If the child object's lifespan is bounded by the lifespan of the of the parent object make it a lifecycle object by specifying cascade="all.delete-orphan". and indicates that the de- lete() operation should be applied to any child object that is removed from the association. This metaphor is incomplete. and you want to save yourself some typing. immutable value types and. However. Hibernate exposes metadata via the ClassMetadata and CollectionMetadata interfaces and the Type hier- archy. or a collection) with cascade="all" marks the as- sociation as a parent/child style relationship where save/update/delete of the parent results in save/update/delete of the child or children.lock"/> You may even use cascade="all" to specify that all operations should be cascaded along the association.7 125 . nothing special happens . Working with objects Cascade styles my be combined: <one-to-one name="person" cascade="persist. From time to time. possibly. Futhermore.. a mere reference to a child from a persistent parent will result in save/update of the child. in which case the "orphaned" child is de- leted. ClassMetadata catMeta = sessionfactory. all children are passed to merge() • If a parent is passed to save(). Finally... you might not need cascade at all. if enabled.merge. mutable value types) and which should not (eg. all children are passed to persist() • If a parent is passed to merge().2. except in the case of a <one-to-many> association mapped with cascade="delete-orphan". A child which becomes unreferenced by its parent is not automatically de- leted. are cascaded to associated entities reachable when the operation is executed.the application should explicitly delete the child if necessary . Cas- cade is often useful for <one-to-one> and <one-to-many> associations. however.getClassMetadata(Cat. it is passed to saveOrUpdate() • If a parent is deleted. All op- erations.12.class). 10. But if you think that you will often be working with the par- ent and children together in the same transaction. Recommendations: • It doesn't usually make sense to enable cascade on a <many-to-one> or <many-to-many> association.. Using metadata Hibernate requires a very rich meta-level model of all entity and value types. A special cascade style. save-upate and delete-orphan are transitive for all associated entities reachable during flush of the Session. Instances of the metadata interfaces may be obtained from the SessionFactory.save-update". applies only to one-to-many associations. The default cascade="none" specifies that no operations are to be cascaded.unless cascade="delete-orphan".. all children are passed to delete() • If a child is dereferenced by a persistent parent. delete-orphan. update() or saveOrUpdate(). this model is very useful to the application itself.

i<propertyNames.2. i++ ) { if ( !propertyTypes[i]. propertyValues[i] ).isCollectionType() ) { namedValues. Working with objects Object[] propertyValues = catMeta.7 126 . String[] propertyNames = catMeta.getPropertyTypes().length.getPropertyValues(fritz).getPropertyNames().put( propertyNames[i]. Type[] propertyTypes = catMeta.isEntityType() && !propertyTypes[i]. // get a Map of all properties which are not collections or associations Map namedValues = new HashMap(). } } Hibernate 3. for ( int i=0.

Hibernate provides repeatable reads for lookup by identifier and entity queries (not reporting queries that return scalar values). the same is true for database transactions. The most common pattern in a multi-user client/server application is session-per-request.) Database transactions are never optional. or expects the application server to do so. that is. ANSI. Your application can expect the behavior as defined by the isola- tion level of your database transactions. Hence. A database transaction has to be as short as possible. Database calls in an ap- plication are made using a planned sequence. as many small transactions are unlikely to perform better than one clearly defined unit of work. using the SELECT FOR UPDATE syntax.Chapter 11. To complete this picture you also have to think about database transactions. a new Hibernate Ses- Hibernate 3. Session- Factory. Long database transactions will prevent your ap- plication from scaling to highly concurrent load.1. Note that thanks to the Session. auto-commit mode immediately. and Session.1. (Note that this also means that auto-commit after every single SQL statement is useless in an application. threadsafe object intended to be shared by all application threads. 11. hence consume no resources until used. all communication with a database has to occur inside a transaction. A Session will not obtain a JDBC Connection (or a Datasource) unless it is needed. It is created once. don't use the session-per-operation antipattern. single unit of work. and transaction isolation specification of your database management system.1.7 127 . this mode is intended for ad-hoc SQL console work. for a single request. until the unit of work is complete. Transactions And Concurrency The most important point about Hibernate and concurrency control is that it is very easy to understand. What is the scope of a unit of work? Can a single Hibernate Session span several database transactions or is this a one-to-one relationship of scopes? When should you open and close a Session and how do you demarc- ate the database transaction boundaries? 11. Hibern- ate directly uses JDBC connections and JTA resources without adding any additional locking behavior. We highly recommend you spend some time with the JDBC. from a Configuration instance. no matter if you read or write data. A Session is an inexpensive. they are grouped into atomic units of work. don't open and close a Session for every simple database call in a single thread! Of course. auto-commit behavior for reading data should be avoided. Session and transaction scopes A SessionFactory is an expensive-to-create. a conversa- tion. In addition to versioning for automatic optimistic concurrency control. non-threadsafe object that should be used once. a re- quest from the client is send to the server (where the Hibernate persistence layer runs). We start the discussion of concurrency control in Hibernate with the granularity of Configuration. As explained. which is also a transaction-scoped cache. as well as database transactions and long conversations. and then discarded. Hibernate does not lock objects in memory. it is almost never good design to hold a database trans- action open during user think time.2. Hibernate disables. The latter is also much more maintainable and extensible. to reduce lock contention in the database. In this model. Unit of work First. Optimistic concurrency control and this API are discussed later in this chapter. Hibernate also offers a (minor) API for pessimistic locking of rows. usually on application startup.

Clearly. it is not easily doable if you rely on EJBs with container-man- aged transactions. Extending the database transaction until view rendering is complete is easy to do if you implement your own interceptor. We call this unit of work. before rendering of any view can start. You will always get a Session scoped to the cur- rent database transaction. he also expects that he was the only person editing this information and that no conflicting modification can occur. the session is flushed and closed. declaratively with CMT. and end the transaction before the response is send to the client. Your application code can access a "current session" to process the request by simply calling sessionFact- ory. A first naive implementation might keep the Session and database transaction open during user think time. or a proxy/interception container. 11. starting and committing it when you open and close the Session. It will be atomic if only one of these database transactions (the last one) stores the updated data. • The user clicks "Save" after 5 minutes and expects his modifications to be made persistent. for ease of use and code portability.2. The challenge lies in the implementation. Once the work has been com- pleted (and the response for the client has been prepared). with locks held in the database to prevent concurrent modification.5.getCurrentSession() anywhere and as often as needed. common solutions are ServletFilter. This is especially useful in servlet applications that utilize a separate rendering phase after the re- quest has been processed. An EJB container is a standardized way to implement cross-cutting aspects such as transaction demarcation on EJB session beans. A single conversation usually spans several database transactions. prefer the Hibernate Transaction API shown later in this chapter. Hibernate provides built-in management of the "current session" to simplify this pattern. You would also use a single database transaction to serve the clients request. since lock contention would not allow the application to scale with the number of concurrent users. The relationship between the two is one-to-one and this model is a perfect fit for many applica- tions. In this case. This is easier to implement than it might sound.7 128 . AOP interceptor with a pointcut on the service methods.1. This is of course an anti-pattern.g. Long conversations The session-per-request pattern is not the only useful concept you can use to design units of work. “Contextual Sessions”. a long running conversation (or application trans- action). All you have to do is start a transaction when a server request has to be processed. especially if you use Hibernate's features: Hibernate 3. all others simply read data (e. In web and enterprise applications it is not acceptable for a database transaction to span a user interaction. This has to be configured for either resource-local or JTA environments. see Sec- tion 2. maintaining isolation of business processes becomes the partial responsibility of the application tier. You can do this in any way you like. Consider the following example: • The first screen of a dialog opens. in a wizard-style dialog spanning several request/ response cycles). and all database operations are executed in this unit of work. However.2. Transactions And Concurrency sion is opened. If you decide to use programmatic transaction demarcation. There are many ways how you can implement this in your application. Sometimes it is convenient to extend the scope of a Session and database transaction until the "view has been rendered". and to guarantee isolation and atomicity. from the point of view of the user. See the Hibernate website and forum for tips and examples around this Open Session in View pattern. as a transaction will be completed when an EJB method returns. Many busi- ness processes require a whole series of interactions with the user interleaved with database accesses. we have to use several database transactions to implement the converastion. The user is free to modify the objects. the data seen by the user has been loaded in a particular Session and database transaction.

they represent the same row). 11. you only have to guarantee stability as long as the objects are in the same Set. • Detached Objects . but explicitely. However. usually immutable. Hence there are two different no- tions of identity: Database Identity foo. Both might have the same database identity (i. might see unexpected results.If you decide to use the already discussed session-per-request pattern. it also provides the best scalabil- ity. The application never needs to synchronize on any business object. an application that uses == outside of a Session. Usually we only check at the end of the conversation.2. There is one caveat: Never use the database identi- fier to implement equality. for example. and reconnected when a new client request oc- curs. • Extended (or Long) Session . a combination of unique. attributes. in the scope of a Session) the two notions are equival- ent.e. The developer has to override the equals() and hashCode() methods in persist- ent classes and implement his own notion of object equality. Considering object identity An application may concurrently access the same persistent state in two different Sessions. if you put two detached instances into the same Set.equals( bar.3. Also note that this is not a Hibernate issue. Both session-per-request-with-detached-objects and session-per-conversation have advantages and disadvant- ages.Hibernate can do automatic optimistic concurrency control for you.getId(). This approach leaves Hibernate and the database to worry about concurrency.7 129 . the pattern is called session-per-request-with-detached-objects. The database identifier will change if a transient object is made persistent. since guaranteeing identity in single-threaded units of work only doesn't need expensive locking or other means of synchronization. and JVM identity for database identity is guaranteed by Hibernate.The Hibernate Session may be disconnected from the underlying JDBC con- nection after the database transaction has been committed. Hibernate 3. Hibernate allows you to reattach the objects and persist the modifications. as long as it sticks to a single thread per Session. Auto- matic versioning is used to isolate concurrent modifications and the Session is usually not allowed to be flushed automatically.1. Automatic ver- sioning is used to isolate concurrent modifications. the two instances will actually be "different" (JVM identity). changing the hashcode breaks the contract of the Set. an in- stance of a persistent class is never shared between two Session instances. we discuss them later in this chapter in the context of optimistic concurrency control. Transactions And Concurrency • Automatic Versioning . but JVM identity is by definition not guaranteed for instances in detached state. This pattern is known as session-per-conversation and makes even reattachment unnecessary. Conflicts are resolved using (automatic versioning) at flush/commit time. all loaded in- stances will be in detached state during user think time. it can automat- ically detect if a concurrent modification occured during user think time.e. using an optimistic approach. This might occur even in some unexpected places. but simply how Java object identity and equality has to be implemented. If the transient instance (usually together with detached instances) is held in a Set. while the application might concurrently access the "same" (persistent identity) business object in two different sessions. use a business key. However. However. Within a Session the application may safely use == to compare objects. See the Hibernate website for a more thorough discussion of this issue.getId() ) JVM Identity foo==bar Then for objects attached to a particular Session (i. Attributes for business keys don't have to be as stable as database primary keys.

7 130 . make sure you understand the implications before making a design decision: • A Session is not thread-safe.4. Keeping a Session open for the duration of a user session also means a high probability of stale data. Certainly. but we strongly encour- age its use unless you are in a CMT session bean. in other words. Common issues Never use the anti-patterns session-per-user-session or session-per-application (of course. If you keep your Hibernate Session in your HttpSession (discussed later). Things which are supposed to work concurrently. A Hibernate application can run in non-managed (i. will cause race conditions if a Session instance would be shared. In a non-managed environment. Transactions And Concurrency 11. you should consider synchronizing access to your Http session. it is often desirable to keep your persistence layer portable between non-managed resource-local en- vironments. or Swing workers. Note that some of the following issues might also appear with the recommended patterns. standalone. a user that clicks reload fast enough may use the same Session in two con- currently running threads. ending a Session involves four distinct phases: • flush the session • commit the transaction Hibernate 3. simple Web. Usually. Database transaction demarcation Datatabase (or system) transaction boundaries are always necessary. even for read-only operations. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction. Otherwise. there are rare excep- tions to this rule). The application developer has to manually set transaction boundaries. if you keep it open for a long time or simply load too much data. Hibernate offers a wrapper API called Transaction that translates into the nat- ive transaction system of your deployment environment. Usually this is not a problem. Hibernate is usually responsible for its own database connection pool.1. If your Session is bound to the application. Always use clear transaction boundaries. for example.or Swing applications) and man- aged J2EE environments. even for reading data. with the transaction assembly defined declaratively in deployment descriptors of EJB session beans. but you most likely should consider a Stored Procedure if you need mass data operations. Programmatic transaction demarcation is then no longer necessary. Batch processing. However. 11. Depending on your isolation level and database capabilities this might not be required but there is no downside if you always de- marcate transactions explicitly. commit. because exceptions are not recoverable and you have to start over after rollback anyway. One solution for this is to call clear() and evict() to manage the Ses- sion cache. and systems that can rely on JTA but use BMT instead of CMT. No communication with the database can occur outside of a database transaction (this seems to confuse many developers who are used to the auto- commit mode). you have to stop the application.2. begin. like HTTP requests. This API is actually optional. A managed environment usually provides container-man- aged transactions (CMT). a single database transaction is going to perform better than many small transactions.e. session beans. In both cases you'd use program- matic transaction demaracation. Some solutions are shown in Chapter 13. This means the database state and the business objects do get out of sync.2. or rollback database transactions himself. • The Session caches every object that is in persistent state (watched and checked for dirty state by Hibern- ate). • An exception thrown by Hibernate means you have to rollback your database transaction and close the Ses- sion immediately (discussed later in more detail). This means it grows endlessly until you get an OutOfMemoryException.

try { tx = sess. This Java code is portable and runs in both non-managed and JTA environments. Transactions And Concurrency • close the session • handle exceptions Flushing the session has been discussed earlier.10. database connections are usually handled by simple (i.getCurrentSession().commit(). factory. 11.2.. // do some work . fatal (system) exceptions should al- ways be caught at the "top". Hibernate 3.getTransaction(). // or display error message } You will very likely never see these code snippets in a regular application. Non-managed environment If a Hibernate persistence layer runs in a non-managed environment. non-DataSource) connection pools from which Hibernate obtains connections as needed. } catch (RuntimeException e) { factory.rollback(). A much more flexible solution is Hibernate's built-in "current session" context management. } catch (RuntimeException e) { if (tx != null) tx.rollback().transaction.getCurrentSession(). Note that you should select org..7 131 . and for the second example "thread" as your hibernate. the code that executes Hibernate calls (in the persistence layer) and the code that handles RuntimeException (and usually can only clean up and exit) are in different layers. throw e.1. The main implication of close() is that the JDBC connection will be relinquished by the ses- sion. } You don't have to flush() the Session explicitly . The current context management by Hibernate can significantly simplify this design.. tx.and non-managed environments..beginTransaction(). as all you need is access to a SessionFactory.JDBCTransactionFactory (which is the default). Transaction tx = null.e.getCurrentSession(). throw e.hibernate. A call to close() marks the end of a session. // or display error message } finally { sess.2. we'll now have a closer look at transaction demarcation and ex- ception handling in both managed. as described earli- er: // Non-managed environment idiom with getCurrentSession() try { factory.commit(). “Flushing the Session” for the session. // do some work .beginTransaction(). Exception handling is discussed later in this chapter. In other words.the call to commit() automatically triggers the synchroniza- tion (depending upon the Section 10.close().current_session_context_class. The session/transaction handling idiom looks like this: // Non-managed environment idiom Session sess = factory.getTransaction().openSession().

lookup("java:comp/UserTransaction").. the code is reduced to: // CMT idiom Session sess = factory.getCurrentSession()..2. Transactions And Concurrency 11.7 132 .commit(). not programatically.). So.commit().2.begin(). hence. } catch (RuntimeException e) { if (tx != null) tx. // or display error message } finally { sess..rollback().getCurrentSession().. tx.rollback(). If you use bean-managed transactions (BMT) Hibernate will tell the application server to start and end a BMT transaction if you use the Transaction API. throw e.persist(. } catch (RuntimeException e) { tx. the getCurrentSession() functionality for easy con- text propagation..close(). Hibernate offers two strategies for JTA integration. // or display error message } With CMT. behind EJB session beans). Transaction tx = null. } If you want to use a transaction-bound Session.openSession(). tx. try { tx = sess.. You can also install a standalone JTA implementation and use it without EJB. // do some work . Using JTA If your persistence layer runs in an application server (e.2.g. the transaction management code is identical to the non- managed environment. This means you do not need to use the Hibernate Transaction API at all with BMT or CMT. every datasource con- nection obtained by Hibernate will automatically be part of the global JTA transaction.beginTransaction(). In a CMT/EJB even rollback happens automatically. you will have to use the JTA UserTransaction API directly: // BMT idiom with getCurrentSession() try { UserTransaction tx = (UserTransaction)new InitialContext() . // Do some work on Session bound to transaction factory.. // BMT idiom Session sess = factory. that is. since an unhandled RuntimeException thrown by a ses- sion bean method tells the container to set the global transaction to rollback. factory..). throw e. tx. // do some work .getCurrentSession(). transaction demarcation is done in session bean deployment descriptors. and you get automatic propagation of the "current" Hibernate 3.load(.

2. • LockAcquisitionException .3. Hi- bernate will attempt to convert the eexception into a more meningful subclass of JDBCException. make sure that your hibernate. not recoverable and appropriate action should be taken.indicates some form of integrity constraint violation. when you config- ure Hibernate's transaction factory. it is also possible to plug in a custom implementation (see the javadocs for the SQLExceptionConverterFactory class for de- tails).close() or Hibernate. • SQLGrammarException . Ensure that the Session will be closed by calling close() in a finally block.transaction. However. Hibernate wraps SQLExceptions thrown while interacting with the database in a JDBCException. In a managed environment.close(Iterator) explicity from a finally block.2.7 133 . and org. There is one caveat to the use of after_statement connection release mode. the SQLExceptionConverter is defined by the configured dialect. which is then used by default. Transaction timeouts ensure that no misbehaving transaction can indefin- itely tie up resources while returning no response to the user.indicates a grammar or syntax problem with the issued SQL. Hibernate cannot fully provide this functionality.CMTTransactionFactory in a CMT session bean. (Of course.getCause(). Note that Hibernate might also throw other unchecked exceptions which are not a HibernateException.JTATransactionFactory if you use JTA directly (BMT).hibernate. The getCurrentSession() operation has one downside in a JTA environment. Exception handling If the Session throws an exception (including any SQLException). The standard JDBCException subtypes are: • JDBCConnectionException . Due to a silly limitation of the JTA spec. Furthermore. Hibernate can at least control data access operations. The HibernateException. in higher layers) and an error message is presented to the application user (or some other appropriate action is taken). Hibernate converts the SQLException into an appropriate JDBCException subclass using the SQLExceptionConverter attached to the SessionFact- ory. again. Transactions And Concurrency Session bound to the transaction.close() and discard the Session instance.) 11. Remember to also set hibernate. which wraps most of the errors that can occur in a Hibernate persistence layer. or set to "jta". In most systems. you should immediately rollback the data- base transaction. You must release the underlying database cursor by calling ScrollableResults.transaction.hibernate.2.indicates an error with the underlying JDBC communication.4. No exception thrown by Hibernate can be treated as recoverable. Certain methods of Session will not leave the session in a consistent state.transaction.e. Transaction timeout One extremely important feature provided by a managed environment like EJB that is never provided for non- managed code is transaction timeout. call Session. it is not possible for Hibernate to automatically clean up any unclosed ScrollableResults or Iterator instances returned by scroll() or iterate(). Note that you should choose org. In fact. unchecked and fatal excep- tions are handled in one of the first frames of the method call stack (i. is an unchecked exception (it wasn't in older versions of Hibernate). we shouldn't force the applica- tion developer to catch an unrecoverable exception at a low layer.manager_lookup_class. Hibernate can delegate transaction timeout to JTA.indicates an error acquiring a lock level necessary to perform the requested operation.a generic exception which did not fall into any of the other categories. 11.current_session_context_class is either unset (backwards compatiblity). ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. • ConstraintViolationException . Outside a managed (JTA) environment. however. These are. • GenericJDBCException . most applications can easily avoid using scroll() or iterate() at all from the JTA or CMT code. In our opinion. By default. The underly- ing SQLException is always available via JDBCException. This functioanlity is abstracted by the Hibern- Hibernate 3.

Transactions And Concurrency ate Transaction object. each interaction with the database occurs in a new Session and the developer is responsible for reloading all persistent instances from the database before manip- ulating them.openSession(). 11.getTransaction(). // do some work .. throw e. // or display error message } finally { sess.commit() } catch (RuntimeException e) { sess.7 134 . t.2.close(). try { //set transaction timeout to 3 seconds sess.getVersion(). It is the approach most similar to entity EJBs.begin(). 11. Application version checking In an implementation without much help from Hibernate.load( foo.. Optimistic concurrency control The only approach that is consistent with high concurrency and high scalability is optimistic concurrency con- trol with versioning.commit().3. int oldVersion = foo. // foo is an instance loaded by a previous Session session = factory.getTransaction(). foo. to detect conflicting updates (and to prevent lost updates). In that case. This approach forces the application to carry out its own version checking to ensure conversation transaction isolation. session. Of course. last commit wins will be the default strategy Hibernate 3.3. sess. or timestamps.getTransaction(). you may use this approach and just skip the version check. Version checking uses version numbers. This approach is the least efficient in terms of database access.getVersion ) throw new StaleObjectStateException().setProperty("bar"). if you are operating in a low-data-concurrency environment and don't require version checking. // load the current state if ( oldVersion!=foo.close(). The version property is mapped using <version>.getTransaction(). sess. but version checking also has the benefit of preventing lost updates in single database transactions. Session sess = factory. session. Transaction t = session.beginTransaction().rollback().1.getKey() ). where transaction timeouts must be defined declar- atively. The use cases we show are in the context of long conversations. and Hibernate will automatically increment it during flush if the entity is dirty.openSession(). } Note that setTimeout() may not be called in a CMT bean. Hibernate provides for three possible approaches to writing application code that uses optimistic concurrency.setTimeout(3). foo.

As the Session is also the (mandatory) first-level cache and contains all loaded objects. You should use a Ses- sion only for a single conversation. Usually you would set FlushMode. // Also return JDBC connection session. The extended session pattern.) Also note that you should keep the disconnected Session close to the persistence layer.3. Beginning a new database transaction on an old ses- sion obtains a new connection and resumes the session. an HttpSession should be kept as small as possible. (Note that earlier Hibernate versions required explicit disconnection and reconnection of a Session. known as session- per-conversation.3. Hence. Often not only single instances. start transaction foo. The Session is disconnected from any underlying JDBC connection when waiting for user interaction. use an EJB stateful session bean to hold the Session in a three-tier environment. This ap- proach is the most efficient in terms of database access.2. only this last database transaction would include the flush() operation. as beginning and ending a transaction has the same effect. and then also close() the session to end the conversation. In other words. is more difficult to implement with automatic cur- rent session context management.2. and don't transfer it to the web layer (or even serialize it to a separate tier) to store it in the HttpSession. so that only the last database transaction cycle is al- lowed to actually persist all modifications made in this conversation. see the Hibernate Wiki for examples. You don't need to lock any data that you are updating. Transactions And Concurrency for your long conversations.3. Extended session and automatic versioning A single Session instance and its persistent instances are used for the whole conversation. session. Keep in mind that this might confuse the users of the application.commit(). Clearly. to force a version check on data you aren't updating. but complete graphs of modified ojects have to be checked.setProperty("bar").READ on any objects that might have been updated by another transaction.7 135 .beginTransaction(). or session-per-conversation.g. The application need not concern itself with version checking or with reattaching detached instances. you may call Session. 11. manual version checking is only feasible in very trivial circumstances and not practical for most ap- plications. After reconnection.lock() with LockMode. This pattern is problematic if the Session is too big to be stored during user think time. // Only for last transaction in conversation The foo object still knows which Session it was loaded in. Hibern- ate offers automatic version checking with either an extended Session or detached instances as the design paradigm. You need to supply your own implementation of the CurrentSessionCon- text for this. e. throwing an exception if concurrent modi- fication is detected. as it will soon also have stale data. // Only for last transaction in conversation t. Committing a database transaction disconnects a ses- sion from the JDBC connection and returns the connection to the pool.close(). // foo is an instance loaded earlier by the old session Transaction t = session. Detached objects and automatic versioning Hibernate 3.NEVER on an extended Session. as they might ex- perience lost updates without error messages or a chance to merge conflicting changes. we can probably use this strategy only for a few request/response cycles.flush(). nor does it have to reload instances in every database transac- tion. // Obtain a new JDBC connection. It's up to the developer to catch and handle this exception (common options are the oppor- tunity for the user to merge changes or to restart the business conversation with non-stale data). Hibernate checks instance versions at flush time. 11. These methods are deprecated.

advanced users may sometimes wish to obtain exclusive pessimistic locks. Transaction t = session. with a comparison of the state of all fields in a row. Again.update(). Hibernate might execute uneccessary updates.7 136 . // foo is an instance loaded by a previous Session foo. Sometimes concurrent modification can be permitted as long as the changes that have been made don't overlap. // Use merge() if "foo" might have been loaded already t. Hibernate will check instance versions during flush. Note that this concepetually only works if Hibernate can compare the old and new state. forcing Hibernate to SELECT the instance to en- sure that changes did actually occur. or re-obtain locks at the start of a new transac- tion. throwing an exception if conflicting updates oc- cured. In both cases. before updating the row. Its usually enough to specify an isolation level for the JDBC connections and then simply let the database do all the work. bypassing all caches) if you are sure that the object has not been modified.setProperty("bar").3. never lock objects in memory! Hibernate 3. versioning can't rely on a particular column in a table. other applications might also access the same database and don't know how to handle version numbers or even timestamps.openSession(). This is usually not a problem. session = factory. with dedicated version/timestamp columns or with full/dirty field comparison. If you use transitive persistence to cascade reattachment to associated entities. session. turn on optimistic-lock="all" in the <class> mapping. You may also call lock() instead of update() and use LockMode.READ (performing a version check. However. the same persistent instances are reused for each interaction with the database. Customizing automatic versioning You may disable Hibernate's automatic version increment for particular properties and collections by setting the optimistic-lock mapping attribute to false. Hibernate uses a single UPDATE statement (with an appropriate WHERE clause) per entity to execute the version check and update the information. However. In both cases.4. To force a version check without a version or timestamp property mapping. 11. Transactions And Concurrency Each interaction with the persistent store occurs in a new Session.close(). or Session.2.commit(). if you use a single long Session and not session-per-request-with-detached-objects.beginTransaction(). session. Hibernate will then no longer increment versions if the property is dirty. Pessimistic Locking It is not intended that users spend much time worring about locking strategies.e.4. Hibernate will always use the locking mechanism of the database.saveOrUpdate(foo). Ses- sion. You can customize this behavior by set- ting select-before-update="true" in the <class> mapping. 11.saveOrUpdate(). Hibernate will only compare dirty fields dur- ing flush. If you set optimistic-lock="dirty" when mapping the <class>. Legacy database schemas are often static and can't be modified. i. but on update triggers in the database might be ex- ecuted even when no changes have been made to detached instances. The application manipulates the state of detached instances ori- ginally loaded in another Session and then reattaches them using Session.merge(). Or.

Connection Release Modes The legacy (2. FOR UPDATE NOWAIT under Oracle. A lock is obtained by the following mechanisms: • LockMode. • A call to Session.says to release connections after a org. currently the only situation where this occurs is through the use of org. this returns ConnectionReleaseMode. Hibernate 3.hibernate.x introduced the notion of connection release modes to tell a session how to handle its JDBC con- nections. UPGRADE or UP- GRADE_NOWAIT.. and the requested object was not yet loaded by the session. FOR UPDATE.. FOR UPDATE on databases which support that syntax. • AFTER_TRANSACTION . • LockMode.ConnectionReleaseMode: • ON_CLOSE .) If the database does not support the requested lock mode. The different re- lease modes are identified by the enumerated values of org.READ is acquired automatically when Hibernate reads data under Repeatable Read or Serializable isolation level. user-supplied connections are outside the breadth of this discussion..7 137 .load() is called with UPGRADE or UPGRADE_NOWAIT.lock(). Objects associated with the session via a call to update() or saveOrUpdate() also start out in this lock mode. specifying a LockMode.AFTER_STATEMENT.hibernate.ScrollableResults.. The Hibernate session obatins a connection when it first needs to perform some JDBC access and holds unto that connection until the session is closed..transaction.UPGRADE_NOWAIT may be acquired upon explicit user request using a SELECT . (In the case of UPGRADE or UPGRADE_NOWAIT. Transactions And Concurrency The LockMode class defines the different lock levels that may be acquired by Hibernate. The configuration parameter hibernate.x) behavior of Hibernate in regards to JDBC connection management was that a Session would obtain a connection when it was first needed and then hold unto that connection until the session was closed. If load() is called for an object that is already loaded with a less restrictive lock than the one requested. This ensures that applications will be portable. Hibernate will use an appropriate alternate mode (instead of throwing an exception). FOR UPDATE is used.load(). For JTATransac- tionFactory. Session.5. Note that the following discussion is pertinent only to connections provided through a configured ConnectionProvider.NONE represents the absence of a lock.getDefaultReleaseMode() method.2. for JDBCTransactionFactory.says to release connections after each and every statement execution.setLockMode().is essentially the legacy behavior described above.Transaction has completed.hibernate.. This aggressive releasing is skipped if that statement leaves open resources associated with the given session. • LockMode.. the object is loaded using SELECT . • LockMode.. • A call to Query.hibernate. Hibernate calls lock() for that object. 11. All objects switch to this lock mode at the end of a Trans- action. May be re-acquired by explicit user request. SELECT . If Session. The possible values: • auto (the default) .UPGRADE may be acquired upon explicit user request using SELECT . this choice delegates to the release mode returned by the org. • AFTER_STATEMENT (also referred to as aggressive release) . The "explicit user request" is expressed in one of the following ways: • A call to Session.connection.release_mode is used to specify which release mode to use.TransactionFactory. • LockMode.WRITE is acquired automatically when Hibernate updates or inserts a row. Hibernate 3.lock() performs a version number check if the specified lock mode is READ.

AFTER_TRANSACTION.says to use ConnectionReleaseMode.2.AFTER_TRANSACTION.7 138 . • on_close . • after_transaction .AFTER_STATEMENT. if a session is considered to be in auto-commit mode connections will be released as if the release mode were AFTER_STATEMENT. the con- figured ConnectionProvider is consulted to see if it supports this setting (supportsAggressiveRelease()). This setting is only safe in environments where we can either re-acquire the same underlying JDBC connection each time we make a call into ConnectionPro- vider.ON_CLOSE. It is rarely a good idea to change this de- fault behavior as failures due to the value of this setting tend to indicate bugs and/or invalid assumptions in user code. This setting is left for backwards compatibil- ity. This setting should not be used in JTA environments.AFTER_TRANSACTION. If not. but its use is highly discouraged. the release mode is reset to ConnectionRelease- Mode. Also note that with ConnectionReleaseMode.says to use ConnectionReleaseMode. Additionally. Transactions And Concurrency this returns ConnectionReleaseMode. Hibernate 3.getConnection() or in auto-commit environments where it does not matter whether we get back the same connection.AFTER_TRANSACTION.says to use ConnectionReleaseMode. • after_statement .

String[] propertyNames. 12. package org.util. Type[] types) { // do nothing } public boolean onFlushDirty(Object entity.7 139 . import org.hibernate.hibernate. Type[] types) { if ( entity instanceof Auditable ) { updates++.2.util.Iterator. String[] propertyNames. for ( int i=0. Serializable id.hibernate. Type[] types) { if ( entity instanceof Auditable ) { Hibernate 3. String[] propertyNames. public class AuditInterceptor extends EmptyInterceptor { private int updates.test. i < propertyNames. Object[] state.EmptyInterceptor. Object[] state. You may either implement Interceptor directly or (better) extend EmptyInterceptor. Serializable id.length.io.type. deleted or loaded. import java. } public boolean onLoad(Object entity. public void onDelete(Object entity. import java. the following Interceptor automatically sets the createTimestamp when an Auditable is created and updates the lastUpdateTimestamp property when an Auditable is updated. i++ ) { if ( "lastUpdateTimestamp".Transaction.Serializable. updated.hibernate. Interceptors The Interceptor interface provides callbacks from the session to the application allowing the application to in- spect and/or manipulate properties of a persistent object before it is saved. } } } return false.Chapter 12. Object[] previousState. import org. private int creates. return true. Serializable id.Type. Interceptors and events It is often useful for the application to react to certain events that occur inside Hibernate. For example.equals( propertyNames[i] ) ) { currentState[i] = new Date().1. import org. This allows imple- mentation of certain kinds of generic functionality. One pos- sible use for this is to track auditing information. and extension of Hibernate functionality.Date. import java. Object[] currentState. private int loads.

You have a LoadEvent. this is true unless a session is opened explicitly specifying the interceptor to use. } updates=0. i++ ) { if ( "createTimestamp". these listeners implement the same processing in which those methods always resulted. Session session = sf.length.openSession( new AuditInterceptor() ). Out-of-the-box.2.e.setInterceptor( new AuditInterceptor() ). Interceptors and events loads++. the supplied interceptor will be applied to all sessions opened from that Session- Factory. } return false.openSession() methods accepting an Interceptor. taking care to not store session-specific state since multiple sessions will use this interceptor (potentially) concurrently.equals( propertyNames[i] ) ) { state[i] = new Date(). The event system can be used in addition or as a replacement for interceptors.println("Creations: " + creates + ". for ( int i=0. Updates: " + updates. Object[] state.wasCommitted() ) { System. Essentially all of the methods of the Session interface correlate to an event. new Configuration(). } public void afterTransactionCompletion(Transaction tx) { if ( tx. i<propertyNames. } } Interceptors come in two flavors: Session-scoped and SessionFactory-scoped. etc (consult the XML configuration-file DTD or the org. In this case. } } } return false. creates=0. When a request is made of one of these methods.event package for the full list of defined event types).. However. SessionFactory- scoped interceptors must be thread safe. a FlushEvent.7 140 . 12. String[] propertyNames. A Session-scoped interceptor is specified when a session is opened using one of the overloaded SessionFact- ory. } public boolean onSave(Object entity.out. "Loads: " + loads). the LoadEvent is processed by the registered implemenation Hibernate 3. Serializable id. you may also use the Hibernate3 event archi- tecture.hibernate. you are free to implement a customization of one of the listener interfaces (i. A SessionFactory-scoped interceptor is registered with the Configuration object prior to building the Ses- sionFactory. the Hibernate Session generates an appropriate event and passes it to the configured event listeners for that type. return true. Event system If you have to react to particular events in your persistence layer. loads=0. Type[] types) { if ( entity instanceof Auditable ) { creates++.2.

a listener implementation could implement multiple event listener interfaces. A custom listener should implement the appropriate interface for the event it wants to process and/or extend one of the convenience base classes (or even the default event listeners used by Hibernate out-of-the-box as these are declared non-final for this purpose).. <listener type="pre-delete" class="org.setLoadEventListeners(stack).EventListeners(). If you need the capability to share listener instances between listener types you must use the programmatic registration approach.3. in which case their implementation would be responsible for processing any load() requests made of the Session. <event type="load"> <listener class="com. Custom listeners can either be registered programmatically through the Configuration object. LoadEventListener.isAuthorized( event.def. new DefaultLoadEventListener() }. cfg. and thus should not save any state as instance variables.JACCPreDeleteEventListener"/> <listener type="pre-update" class="org.hibernate. Now. The listeners should be considered effectively singletons.secure..hibernate. you may register it programmatically: Configuration cfg = new Configuration(). 12.secure.getEntityClassName(). each reference will result in a separate instance of that class. or specified in the Hibernate configuration XML (declarative configuration through the properties file is not supported). First.event.secure.7 141 .LoadType loadType) throws HibernateException { if ( !MySecurity. and authorized via JAAS. you must configure the appropriate event listeners. Interceptors and events of the LoadEventListener interface).getEntityId() ) ) { throw MySecurityException("Unauthorized access"). This is optional functionality built on top of the event architecture. Hibernate3 allows certain actions to be permissioned via JACC.MyLoadListener"/> <listener class="org.JACCPreInsertEventListener"/> Hibernate 3. If the same class name is used in multiple <listener/> elements. Hibernate declarative security Usually. } } } You also need a configuration entry telling Hibernate to use the listener in addition to the default listener: <hibernate-configuration> <session-factory> .hibernate.DefaultLoadEventListener"/> </event> </session-factory> </hibernate-configuration> Instead. Listeners registered declaratively cannot share instances. declarative security in Hibernate applications is managed in a session facade layer. meaning. to enable the use of JAAS authorization. Having the type additionally defined during registration makes it easier to turn custom listeners on or off during configuration.JACCPreUpdateEventListener"/> <listener type="pre-insert" class="org. Here's an example of a custom load event listener: public class MyLoadListener implements LoadEventListener { // this is the single method defined by the LoadEventListener interface public void onLoad(LoadEvent event. LoadEventListener[] stack = { new MyLoadListener().hibernate. event.eg. Why implement an interface and define the specific type during configuration? Well. they are shared between requests.2.

"/> is just a shorthand for <event type=".update.JACCPreLoadEventListener"/> Note that <listener type="..hibernate.secure.7 142 . bind the permissions to roles: <grant role="admin" entity-name="User" actions="insert.." class="..2. Hibernate 3. Interceptors and events <listener type="pre-load" class="org.."><listener class=". still in hibernate...."/></event> when there is exactly one listener for a particular event type.read"/> <grant role="su" entity-name="User" actions="*"/> The role names are the roles understood by your JACC provider..xml. Next.cfg.

You also might like to do this kind of work in a process where interaction with the second-level cache is com- pletely disabled: hibernate.2. i<100000. if ( i % 20 == 0 ) { //20.jdbc.cache. } } tx.Chapter 13.close().openSession(). Set the JDBC batch size to a reasonable number (say. 10-50): hibernate. session.beginTransaction(). you must flush() and then clear() the session regularly.. Batch inserts When making new objects persistent.. Session session = sessionFactory.. Batch processing A naive approach to inserting 100 000 rows in the database using Hibernate might look like this: Session session = sessionFactory. That's because Hi- bernate caches all the newly inserted Customer instances in the session-level cache. 13. same as the JDBC batch size //flush a batch of inserts and release memory: session. In this chapter we'll show you how to avoid this problem.. session.).use_second_level_cache false However.7 143 .commit(). if you intend to achieve reasonable performance. this is not absolutely necessary. however. for ( int i=0. This would fall over with an OutOfMemoryException somewhere around the 50 000th row.flush(). session.. } tx. First. Transaction tx = session.openSession().. session.clear(). 13. i++ ) { Customer customer = new Customer(..save(customer).commit().. for ( int i=0. since we can explicitly set the CacheMode to disable interaction with the second-level cache. if you are doing batch processing.batch_size 20 Note that Hibernate disables insert batching at the JDBC level transparently if you use an identiy identifier generator.save(customer). Batch updates Hibernate 3. Transaction tx = session. it is absolutely critical that you enable the use of JDBC batching.1. session.close(). to control the size of the first-level cache. i<100000. i++ ) { Customer customer = new Customer(.).2.beginTransaction().

Batch processing For retrieving and updating data the same ideas apply.next() ) { Customer customer = (Customer) customers. In particular. due to the lack of a first-level cache. the Customer instances returned by the query are immediately detached.close().openSession().commit().).clear(). they have very different semantics to the save(). Collections are ignored by a stateless session. Thus.close(). ScrollableResults customers = session. UPDATE or DELETE respectively.scroll(ScrollMode.. DML-style operations Hibernate 3. } tx.. Note that in this code example. much closer to the underly- ing JDBC.FORWARD_ONLY).get(0). 13.3.4. Operations performed using a stateless session do not ever cascade to associated instances.next() ) { Customer customer = (Customer) customers. customer.beginTransaction(). session.FORWARD_ONLY).update(customer). session. customer. Session session = sessionFactory. saveOrUpdate() and delete() operations defined by the Session interface.get(0). Operations performed via a stateless ses- sion bypass Hibernate's event model and interceptors. which result in immediate execution of a SQL INSERT. In addition. 13. The StatelessSession interface Alternatively. It does not implement transaction- al write-behind or automatic dirty checking..updateStuff(.).7 144 . session.commit(). a stateless session does not im- plement a first-level cache nor interact with any second-level or query cache. The insert().updateStuff(. session. Transaction tx = session. you need to use scroll() to take advantage of server-side cursors for queries that return many rows of data.2.getNamedQuery("GetCustomers") .beginTransaction(). StatelessSession session = sessionFactory. A stateless session is a lower-level abstraction. if ( ++count % 20 == 0 ) { //flush a batch of updates and release memory: session. } } tx.scroll(ScrollMode. while ( customers. update() and delete() operations defined by the StatelessSession interface are considered to be direct database row-level operations.IGNORE) . ScrollableResults customers = session. They are never associated with any persistence context.setCacheMode(CacheMode.flush(). while ( customers.. Transaction tx = session.openStatelessSession(). int count=0. Hibernate provides a command-oriented API that may be used for streaming data to and from the database in the form of detached objects.getNamedQuery("GetCustomers") . A StatelessSession has no persistence context associated with it and does not provide many of the higher-level lifecycle semantics. Stateless sessions are vulnerable to data aliasing effects.

Sub-queries may be used in the where-clause.setString( "oldName". by default do not effect the Section 5. use the same Query. tx.name = :oldName". Transaction tx = session. this is in keeping with the EJB3 specification. As an example. Session session = sessionFactory.close(). oldName ) Hibernate 3.createQuery( hqlUpdate ) . int updatedEntities = s. hence manipulating (using the SQL Data Manipulation Language (DML) statements: INSERT. This implies that the object state is available in memory.executeUpdate() method: Session session = sessionFactory.close().openSession().7 145 . oldName ) . Some points to note: • In the from-clause. if the entity name is not aliased.name = :oldName". then any property references must be qualified using that alias.setString( "newName".executeUpdate().beginTransaction().1. Transaction tx = session.hibernate. int updatedEntities = s. If the entity name is aliased. Batch processing As already discussed. Note that custom version types (org.1. use the Query. int deletedEntities = s. session. Hibernate provides methods for bulk SQL-style DML statement execu- tion which are performed through the Hibernate Query Language (Chapter 14.usertype.beginTransaction(). “Forms of join syntax” (either implicit or explicit) can be specified in a bulk HQL query. may contain joins. String hqlDelete = "delete Customer c where c.openSession().setString( "oldName". Transaction tx = session.createQuery( hqlUpdate ) .executeUpdate() method (the method is named for those familiar with JDBC's PreparedStatement.4. // or String hqlDelete = "delete Customer where name = :oldName". you can force Hibernate to properly reset the version or timestamp property values through the use of a versioned update.executeUpdate(). To execute an HQL DELETE. HQL UPDATE statements. The pseudo-syntax for UPDATE and DELETE statements is: ( UPDATE | DELETE ) FROM? EntityName (WHERE where_conditions)?. UPDATE.createQuery( hqlDelete ) . newName ) . • The where-clause is also optional. automatic and transparent object/relational mapping is concerned with the management of object state. This is achieved by adding the VERSIONED keyword after the UPDATE keyword. it can optionally be aliased. String hqlVersionedUpdate = "update versioned Customer set name = :newName where name = :oldName". to execute an HQL UPDATE.beginTransaction().setString( "newName". However. themselves. session. then it is illegal for any property references to be qualified. However.10.commit(). tx. • No Section 14. newName ) . the subqueries.commit(). // or String hqlUpdate = "update Customer set name = :newName where name = :oldName". String hqlUpdate = "update Customer c set c. “version (optional)” or the Section 5.2.openSession().setString( "oldName".executeUpdate()): Session session = sessionFactory.UserVersionType) are not allowed in conjunction with a update versioned statement. oldName ) . “timestamp (optional)” property values for the affected entities. the FROM keyword is optional • There can only be a single entity named in the from-clause.name = :newName where c. DELETE) data directly in the database will not affect in-memory state.9. HQL: The Hibernate Query Language).

The pseudo-syntax for INSERT statements is: INSERT INTO EntityName properties_list select_statement.hibernate. this is checked during query compilation rather than allowing the check to relegate to the database. attempting to use this option with any "in memory" type generators will cause an exception during parsing..TableHiLoGenerator..DateType and a property defined as a org.executeUpdate().hibernate.id. form is supported.2. This later option is only available when using id generators that operate in the database. tx. Superclass properties are not allowed. An HQL bulk operation might result in multiple actual SQL statements being executed. Consider this may or may not correlate to the number of rows effected in the database.executeUpdate() method indicate the number of entities effected by the operation. Note however that this might cause problems between Hibernate Types which are equivalent as opposed to equal.executeUpdate(). For entities in- volved in mapped inheritence.close(). for example..hibernate. session. You can either explicitly specify the id prop- erty in the properties_list (in which case its value is taken from the corresponding select expression) or omit it from the properties_list (in which case a generated value is used).SequenceGenerator (and its subclasses) and any imple- mentors of org.id. a delete against one of the subclasses may actually result in deletes against not just the table to which that subclass is mapped. SELECT .PostInsertIdentifierGenerator.7 146 .type.. the insert statement gives you two options. • For properties mapped as either version or timestamp. The most notable exception here is org. • For the id property.TimestampType. form. but also the "root" table and potentially joined-subclass tables further down the inheritence hierarchy. only properties directly defined on that given class-level can be used in the properties_list. Currently. • select_statement can be any valid HQL select query. with the caveat that the return types must match the types expected by the insert. for joined-subclass. This might cause issues with mismatches between a property defined as a org. not the INSERT INTO . c..hibernate. even though the database might not make a distinction or might be able to handle the conversion. Transaction tx = session.createQuery( hqlInsert ) .name from Customer c where int createdEntities = s. Going back to the example of joined-subclass. Some points to note: • Only the INSERT INTO ..hibernate..commit(). An example HQL INSERT statement execution: Session session = sessionFactory. You can either specify the property in the properties_list (in which case its value is taken from the corresponding se- lect expressions) or omit it from the properties_list (in which case the seed value defined by the org. In other words. Note that for the purposes of this discussion.openSession(). VALUES . INSERT statements are inherently non-polymorphic.type.. in-database generators are considered to be org.VersionType is used). name) select c.close(). and subclass properties do not make sense.id. which cannot be used because it does not expose a selectable way to get its values. tx. The int value returned by the Query. String hqlInsert = "insert into DelinquentAccount (id.beginTransaction().type. The returned number indicates the number of actual entities affected by the statement. Hibernate 3.commit(). Batch processing .id. the insert statement gives you two options. session. The properties_list is analogous to the column speficiation in the SQL INSERT statement.hibernate.

Some users find queries with uppercase keywords more readable. Parameter from Formula as form.hibernate. except for names of Java classes and properties. The as keyword is optional. So SeLeCT is the same as sELEct is the same as SELECT but org.2. Parameter as param It is considered good practice to name query aliases using an initial lowercase. Hibernate 3. from Cat as cat This query assigns the alias cat to Cat instances. 14.eg. consistent with Java naming standards for local variables (eg. This manual uses lowercase HQL keywords. polymorphism and association. HQL: The Hibernate Query Language Hibernate is equipped with an extremely powerful query language that (quite intentionally) looks very much like SQL. resulting in a cartesian product or "cross" join. Case Sensitivity Queries are case-insensitive.BARSET.1. you will need to assign an alias. Associations and joins We may also assign aliases to associated entities. domesticCat). HQL is fully object-oriented.Cat which simply returns all instances of the class eg. we could also write: from Cat cat Multiple classes may appear. since you will want to refer to the Cat in other parts of the query. since auto-import is the default. We don't usually need to qualify the class name. or even to elements of a collection of values.Chapter 14.barSet is not foo.7 147 . So we almost always just write: from Cat Most of the time.eg.FOO is not org.2.hibernate. 14. But don't be fooled by the syntax. understanding notions like inherit- ence.3. from Formula.Cat. so we could use that alias later in the query. The from clause The simplest possible Hibernate query is of the form: from eg.Foo and foo. using a join. 14. but we find this convention ugly when embedded in Java code.

If you are using property-level lazy fetching (with bytecode instrumentation). the associated objects are not returned directly in the query results.mate left join fetch cat.kittens Note that the fetch construct may not be used in queries called using iterate() (though scroll() can be used). Join fetching multiple collection roles also sometimes gives unexpected results for bag mappings. it is possible to force Hibernate to Hibernate 3. from Cat as cat inner join fetch cat. The only reason we might need an alias is if we are recurs- ively join fetching a further collection: from Cat as cat inner join fetch cat. because the associated objects should not be used in the where clause (or any other clause). from Cat as cat left join cat.1. using a single select. This is particularly useful in the case of a collection.bodyWeight > 10.mate as mate left join cat. Also. note that full join fetch and right join fetch are not meaningful. hence. which usually contain duplicates for eager collection fetching. “Fetching strategies” for more information. left outer join and right outer join constructs may be abbreviated.kittens as kitten from Cat as cat left join cat.mate as mate left outer join cat. See Section 19. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections. Finally. a "fetch" join allows associations or collections of values to be initialized along with their parent objects.0 In addition. HQL: The Hibernate Query Language from Cat as cat inner join cat. In- stead.kittens as kitten with kitten. Nor should fetch be used together with setMaxResults() or setFirstResult() as these operations are based on the result rows.kittens A fetch join does not usually need to assign an alias.kittens as kitten You may supply extra join conditions using the HQL with keyword. they may be accessed via the parent object.7 148 .mate. from Cat as cat join cat.parameter param The supported join types are borrowed from ANSI SQL • inner join • left outer join • right outer join • full join (not usually useful) The inner join. so take care in this case.kittens child left join fetch child. Nor may fetch be used together with an ad hoc with condition. It is possible to create a cartesian product by join fetching more than one collection in a query.2.kittens as kittens from Formula form full join form. so be careful about how you formulate your queries in this case.mate left join fetch cat. the number of rows is not what you'd expect.

The select clause The select clause picks which objects and properties to return in the query result set. If the entity has a non-identifier property named id. 14. Instead. from Document fetch all properties order by name from Document doc fetch all properties where lower(doc. This is the recommended form. References to composite identifier properties follow the same naming rules.mate as mate The query will select mates of other Cats.mate.name like '%s%' 14. HQL: The Hibernate Query Language fetch the lazy properties immediately (in the first query) using fetch all properties. Actually. from Cat as cat where cat. • If the entity defines a named identifier property. generally speaking.7 149 . implicit joins can appear in any of the HQL clauses. the associations are "dereferenced" using dot- notation. the composite identifier property can only be referenced by its defined named. 2 ways to refer to an entity's identifier property: • The special property (lowercase) id may be used to reference the identifier property of an entity provided that entity does not define a non-identifier property named id.name like 'fri%' Hibernate 3. id always referred to the identifier property no matter what its actual name. otherwise.6. Consider: select mate from Cat as cat inner join cat. you may use that property name. Forms of join syntax HQL supports two forms of association joining: implicit and explicit.4.5. implicit join result in inner joins in the result- ing SQL statement.name) like '%cats%' 14. In previous versions. A ramification of that decision was that non-identifier prop- erties named id could never be referenced in Hibernate queries. Refering to identifier property There are. The queries shown in the previous section all use the explicit form where the join keyword is explicitly used in the from clause. The implicit form does not use the join keyword.2.2.2.name from DomesticCat cat where cat. Note: this has changed significantly starting in version 3.mate from Cat cat Queries may return properties of any value type including properties of component type: select cat. you may express this query more compactly as: select cat. the special id property can be used to rerference the identifier property.

kittens as offspr assuming that the class Family has an appropriate constructor.. offspr. select new Family(mother. count(*) as n ) from Cat cat This query returns a Map from aliases to selected values. mate.. count(all. min(.. max(cat.weight + sum(kitten.id.. mate.. offspr) from DomesticCat as mother join mother. max(.mate as mate left join mother. min(bodyWeight) as min..weight).firstName from Customer as cust Queries may return multiple objects and/or properties as an array of type Object[]. sum(cat...weight Hibernate 3. cat.). Aggregate functions HQL queries may even return the results of aggregate functions on properties: select avg(cat. HQL: The Hibernate Query Language select cust..).) You may use arithmetic operators.) • count(*) • count(.7 150 .. select new list(mother. mate. count(distinct . min(bodyWeight) as min. You may assign aliases to selected expressions using as: select max(bodyWeight) as max..). and recognized SQL functions in the select clause: select cat.kittens as offspr or as an actual typesafe Java object. count(cat) from Cat cat The supported aggregate functions are • avg(.. 14. count(*) as n from Cat cat This is most useful when used together with select new map: select new map( max(bodyWeight) as max..mate as mate left outer join mother.mate as mate left outer join mother.name.7.weight).kittens as offspr or as a List.name) from DomesticCat as mother inner join mother. sum(.).2.kittens kitten group by cat..name from DomesticCat as mother inner join mother.weight).). select mother.weight) from Cat cat join cat. concatenation. offspr.

Polymorphic queries A query like: from Cat as cat returns instances not only of Cat. use a qualified property name: from Cat as cat where cat. select foo from Foo foo.Object o The interface Named might be implemented by various persistent classes: from Named n.name).mate.date will return all instances of Foo for which there exists an instance of bar with a date property equal to the startDate property of the Foo.2.9.name Note that these last two queries will require more than one SQL SELECT. count(cat) from Cat cat 14. you may refer to proper- ties by name: from Cat where name='Fritz' If there is an alias. HQL: The Hibernate Query Language select firstName||' '||initial||' '||upper(lastName) from Person The distinct and all keywords may be used and have the same semantics as in SQL. Hibernate queries may name any Java class or interface in the from clause. The following query would return all persistent objects: from java. If no alias exists.name='Fritz' returns instances of Cat named 'Fritz'. This means that the order by clause does not correctly order the whole result set. but also of subclasses like DomesticCat. (It also means you can't call these queries using Query.7 151 .) 14.startDate = bar. Con- sider: from Cat cat where cat. The where clause The where clause allows you to narrow the list of instances returned.scroll(). If you were to write something like Hibernate 3.8.name is not null This query translates to an SQL query with a table (inner) join.name from Cat cat select count(distinct cat. The query will return instances of all persistent classes that extend that class or implement the interface. Bar bar where foo. select distinct cat. Named m where n.lang. Compound path expressions make the where clause extremely powerful.name = m.

Account account where account.id.mate select cat.customer. HQL: The Hibernate Query Language from Foo foo where foo. from bank.address. Likewise.7 152 . The = operator may be used to compare not only properties. Suppose Person has a composite identifier consisting of country and medicareNumber.5.mate.owner. “Refering to identifier property” for more information regarding referencing identifier properties.country = 'AU' and person. An "any" type has the special properties id and class. from Cat cat where cat.item. see Section 14.id.Person person where person.item.class = 'Payment' and log.bar.country = 'AU' and account. but also instances: from Cat cat.item.class would refer to the values of completely different database columns in the above query. No table join is required! Properties of composite identifiers may also be used.baz.mate = rival.id Notice that log.medicareNumber = 123456 from bank. “Refering to identifier property” for more information. Cat mate where cat.item is a property mapped with <any>). the special property class accesses the discriminator value of an instance in the case of polymorphic persistence. the second query requires no table join.class and payment.id = 123 from Cat as cat where cat. from Cat as cat where cat. 14.city is not null you would end up with a query that would require four table joins in SQL. A Java class name embedded in the where clause will be translated to its discriminator value. Payment payment where log.id = 69 The second query is efficient. or properties of said component types. allowing us to express a join in the following way (where AuditLog. Cat rival where cat. Expressions Hibernate 3.2.class = DomesticCat You may also use components or composite user types. See ??? for more details.id = payment. mate from Cat cat.id. from AuditLog log.id.10. See Sec- tion 14.5.owner. Again.mate = mate The special property (lowercase) id may be used to reference the unique identifier of an object.medicareNumber = 123456 Once again.

HQL: The Hibernate Query Language

Expressions allowed in the where clause include most of the kind of things you could write in SQL:

• mathematical operators +, -, *, /
• binary comparison operators =, >=, <=, <>, !=, like
• logical operations and, or, not
• Parentheses ( ), indicating grouping
• in, not in, between, is null, is not null, is empty, is not empty, member of and not member of
• "Simple" case, case ... when ... then ... else ... end, and "searched" case, case when ... then
... else ... end
• string concatenation ...||... or concat(...,...)
• current_date(), current_time(), current_timestamp()
• second(...), minute(...), hour(...), day(...), month(...), year(...),
• Any function or operator defined by EJB-QL 3.0: substring(), trim(), lower(), upper(), length(),
locate(), abs(), sqrt(), bit_length(), mod()
• coalesce() and nullif()
• str() for converting numeric or temporal values to a readable string
• cast(... as ...), where the second argument is the name of a Hibernate type, and extract(... from
...) if ANSI cast() and extract() is supported by the underlying database
• the HQL index() function, that applies to aliases of a joined indexed collection
• HQL functions that take collection-valued path expressions: size(), minelement(), maxelement(),
minindex(), maxindex(), along with the special elements() and indices functions which may be quanti-
fied using some, all, exists, any, in.
• Any database-supported SQL scalar function like sign(), trunc(), rtrim(), sin()
• JDBC-style positional parameters ?
• named parameters :name, :start_date, :x1
• SQL literals 'foo', 69, 6.66E+2, '1970-01-01 10:00:01.0'
• Java public static final constants eg.Color.TABBY

in and between may be used as follows:

from DomesticCat cat where cat.name between 'A' and 'B'

from DomesticCat cat where cat.name in ( 'Foo', 'Bar', 'Baz' )

and the negated forms may be written

from DomesticCat cat where cat.name not between 'A' and 'B'

from DomesticCat cat where cat.name not in ( 'Foo', 'Bar', 'Baz' )

Likewise, is null and is not null may be used to test for null values.

Booleans may be easily used in expressions by declaring HQL query substitutions in Hibernate configuration:

<property name="hibernate.query.substitutions">true 1, false 0</property>

This will replace the keywords true and false with the literals 1 and 0 in the translated SQL from this HQL:

from Cat cat where cat.alive = true

You may test the size of a collection with the special property size, or the special size() function.

from Cat cat where cat.kittens.size > 0

Hibernate 3.2.7 153

HQL: The Hibernate Query Language

from Cat cat where size(cat.kittens) > 0

For indexed collections, you may refer to the minimum and maximum indices using minindex and maxindex
functions. Similarly, you may refer to the minimum and maximum elements of a collection of basic type using
the minelement and maxelement functions.

from Calendar cal where maxelement(cal.holidays) > current_date

from Order order where maxindex(order.items) > 100

from Order order where minelement(order.items) > 10000

The SQL functions any, some, all, exists, in are supported when passed the element or index set of a col-
lection (elements and indices functions) or the result of a subquery (see below).

select mother from Cat as mother, Cat as kit
where kit in elements(foo.kittens)

select p from NameList list, Person p
where p.name = some elements(list.names)

from Cat cat where exists elements(cat.kittens)

from Player p where 3 > all elements(p.scores)

from Show show where 'fizard' in indices(show.acts)

Note that these constructs - size, elements, indices, minindex, maxindex, minelement, maxelement - may
only be used in the where clause in Hibernate3.

Elements of indexed collections (arrays, lists, maps) may be referred to by index (in a where clause only):

from Order order where order.items[0].id = 1234

select person from Person person, Calendar calendar
where calendar.holidays['national day'] = person.birthDay
and person.nationality.calendar = calendar

select item from Item item, Order order
where order.items[ order.deliveredItemIndices[0] ] = item and order.id = 11

select item from Item item, Order order
where order.items[ maxindex(order.items) ] = item and order.id = 11

The expression inside [] may even be an arithmetic expression.

select item from Item item, Order order
where order.items[ size(order.items) - 1 ] = item

HQL also provides the built-in index() function, for elements of a one-to-many association or collection of
values.

select item, index(item) from Order order
join order.items item
where index(item) < 5

Hibernate 3.2.7 154

HQL: The Hibernate Query Language

Scalar SQL functions supported by the underlying database may be used

from DomesticCat cat where upper(cat.name) like 'FRI%'

If you are not yet convinced by all this, think how much longer and less readable the following query would be
in SQL:

select cust
from Product prod,
Store store
inner join store.customers cust
where prod.name = 'widget'
and store.location.name in ( 'Melbourne', 'Sydney' )
and prod = all elements(cust.currentOrder.lineItems)

Hint: something like

SELECT cust.name, cust.address, cust.phone, cust.id, cust.current_order
FROM customers cust,
stores store,
locations loc,
store_customers sc,
product prod
WHERE prod.name = 'widget'
AND store.loc_id = loc.id
AND loc.name IN ( 'Melbourne', 'Sydney' )
AND sc.store_id = store.id
AND sc.cust_id = cust.id
AND prod.id = ALL(
SELECT item.prod_id
FROM line_items item, orders o
WHERE item.order_id = o.id
AND cust.current_order = o.id
)

14.11. The order by clause
The list returned by a query may be ordered by any property of a returned class or components:

from DomesticCat cat
order by cat.name asc, cat.weight desc, cat.birthdate

The optional asc or desc indicate ascending or descending order respectively.

14.12. The group by clause
A query that returns aggregate values may be grouped by any property of a returned class or components:

select cat.color, sum(cat.weight), count(cat)
from Cat cat
group by cat.color

select foo.id, avg(name), max(name)
from Foo foo join foo.names name
group by foo.id

A having clause is also allowed.

Hibernate 3.2.7 155

HQL: The Hibernate Query Language

select cat.color, sum(cat.weight), count(cat)
from Cat cat
group by cat.color
having cat.color in (eg.Color.TABBY, eg.Color.BLACK)

SQL functions and aggregate functions are allowed in the having and order by clauses, if supported by the un-
derlying database (eg. not in MySQL).

select cat
from Cat cat
join cat.kittens kitten
group by cat.id, cat.name, cat.other, cat.properties
having avg(kitten.weight) > 100
order by count(kitten) asc, sum(kitten.weight) desc

Note that neither the group by clause nor the order by clause may contain arithmetic expressions. Also note
that Hibernate currently does not expand a grouped entity, so you can't write group by cat if all properties of
cat are non-aggregated. You have to list all non-aggregated properties explicitly.

14.13. Subqueries
For databases that support subselects, Hibernate supports subqueries within queries. A subquery must be sur-
rounded by parentheses (often by an SQL aggregate function call). Even correlated subqueries (subqueries that
refer to an alias in the outer query) are allowed.

from Cat as fatcat
where fatcat.weight > (
select avg(cat.weight) from DomesticCat cat
)

from DomesticCat as cat
where cat.name = some (
select name.nickName from Name as name
)

from Cat as cat
where not exists (
from Cat as mate where mate.mate = cat
)

from DomesticCat as cat
where cat.name not in (
select name.nickName from Name as name
)

select cat.id, (select max(kit.weight) from cat.kitten kit)
from Cat as cat

Note that HQL subqueries may occur only in the select or where clauses.

Note that subqueries can also utilize row value constructor syntax. See Section 14.18, “Row value con-
structor syntax” for more details.

14.14. HQL examples

Hibernate 3.2.7 156

effectiveDate from Catalog as cat where cat.timeStamp = ( select max(change.id. select order.amount) desc What a monster! Actually.product as product.name <> PaymentStatus.statusChanges as statusChange where payment. Note that most queries you will write are much simpler than these! The following query returns the order id.paid = false and order. ORDER_LINE.customer = :customer and price.effectiveDate < sysdate ) group by order having sum(price. Catalog as catalog join catalog.effectiveDate < sysdate and catalog.product = product and catalog.prices as price where order.payment = payment ) and statusChange. The resulting SQL query.AWAITING_APPROVAL or ( statusChange.sortOrder order by status. PRODUCT. select count(payment).amount).sortOrder Hibernate 3.name from Payment as payment join payment. status. In determining the prices. HQL: The Hibernate Query Language Hibernate queries can be quite powerful and complex. I'm not very keen on subqueries. it uses the current catalog.amount) > :minAmount order by sum(price.7 157 .amount).product = product and catalog = :currentCatalog group by order having sum(price.customer = :customer and price. ordering the results by total value. Here are some example queries very similar to queries that I used on a recent project.status. count(item) from Order as order join order. In fact.lineItems as item join item. against the ORDER.amount) > :minAmount order by sum(price. in real life.currentStatus as status join payment. sum(price. so my query was really more like this: select order. PAYMENT_STATUS and PAY- MENT_STATUS_CHANGE tables. count(item) from Order as order join order.name. number of items and total value of the order for all unpaid orders for a particular customer and given minimum total value. excluding all payments in the AWAIT- ING_APPROVAL status where the most recent status change was made by the current user.amount) desc The next query counts the number of payments in each status.paid = false and order. status. Catalog as catalog join catalog. sum(price.product as product. the power of the query language is one of Hi- bernate's main selling points. It translates to an SQL query with two inner joins and a correlated subselect against the PAYMENT.prices as price where order.timeStamp) from PaymentStatusChange change where change.id.user <> :currentUser ) group by status.2.lineItems as item join item. CATALOG and PRICE tables has four inner joins and an (uncorrelated) subselect.effectiveDate >= all ( select cat.

user <> :currentUser group by status.type.15.name.intValue() To order a result by the size of a collection. we would need to do away with the (correlated) subselect.name order by count(msg) If your database supports subselects.next() ).holder.currentStatus.name from User as usr left join usr.status.sortOrder The next query uses the MS SQL Server isNull() function to return all the accounts and unpaid payments for the organization to which the current user belongs. use the following query: select usr. instead of a set.dueDate 14.accountNumber.accountNumber.2.sortOrder.UNPAID) order by account. usr. It translates to an SQL query with three inner joins.name <> PaymentStatus.type. select count(payment).UNPAID = isNull(payment.statusChanges) ].id.. account. See Section 13.messages as msg group by usr. Tips & Tricks You can count the number of query results without actually returning them: ( (Integer) session. an outer join and a subselect against the ACCOUNT. account. status. usr.. select . PAYMENT_STATUS. payment.. you can place a condition upon selection size in the where clause of your query: from User usr where size(usr.name.4.name.name from Payment as payment join payment. payment. HQL: The Hibernate Query Language If I would have mapped the statusChanges collection as a list.AWAITING_APPROVAL or payment.7 158 .statusChanges[ maxIndex(payment.id.sortOrder.users) and PaymentStatus. statements.. 14.UNPAID) order by account. Bulk update and delete HQL now supports update.."). PAYMENT. payment from Account as account join account. ORGANIZATION and ORG_USER tables.users as user left outer join account.dueDate For some databases. delete and insert .payments as payment where :currentUser in elements(account. status. the query would have been much simpler to write. select account.currentStatus. select account. payment from Account as account left outer join account.messages) >= 1 Hibernate 3..UNPAID = isNull(payment.holder. ACCOUNT_TYPE. “DML-style op- erations” for details.16.. PaymentStatus.currentStatus as status where payment.sortOrder order by status. PaymentStatus.payments as payment where :currentUser = user and PaymentStatus.iterate("select count(*) from .

name from from Person p select p.id. use the following query: select usr.filter( collection.first from from Person p where the Person's name property is a component.id.next() )..setMaxResults(PAGE_SIZE). They can appear in the select clause: select p.name from User as usr left join usr.createFilter( collection.17. Components Components might be used in just about every way that simple value types can be used in HQL queries.setProperties(fooBean).iterate("select count(*) from .filter( collection.id. count(this) group by this. usr.name join usr. q.size=:size").name. List page = q. Collection elements may be ordered or grouped using a query filter: Collection orderedCollection = s.amount" ). 14.messages as msg group by usr.name having count(msg) >= 1 As this solution can't return a User with zero messages because of the inner join. Components can also be used in the where clause: from from Person p where p.2. You can find the size of a collection without initializing it: ( (Integer) session. q. "order by this. HQL: The Hibernate Query Language If your database doesn't support subselects..id."). Collection counts = s.name from User usr..name=:name and foo.name. the following form is also use- ful: select usr.list().createQuery("from foo Foo as foo where foo.7 159 . usr. // the trivial filter q.name = :name from from Person p where p.list(). // fooBean has getName() and getSize() List foos = q.setFirstResult(PAGE_SIZE * pageNumber). Collections are pageable by using the Query interface with a filter: Query q = s.messages msg group by usr.type.name having count(msg) = 0 Properties of a JavaBean can be bound to named query parameters: Query q = s.intValue(). usr. usr. "select this. "" ).type" ).first = :firstName Components can also be used in the order by clause: Hibernate 3.

first='John' and p. It be nice to make this a bit more concise and use row value con- structor syntax: from Person p where p. cat.name from from Person p Another time using row value constructor syntax can be beneficial is when using subqueries needing to compare against multiple values: from Cat as cat where not ( cat.name. HQL: The Hibernate Query Language from from Person p order by p.18. 14.7 160 . 'Jingleheimer-Schmidt') It can also be useful to specify this in the select clause: select p. Here we are generally referring to multi-valued comparisons. “Row value constructor syntax”.name.color from DomesticCat cat ) One thing to consider when deciding if you want to use this syntax is that the query will be dependent upon the ordering of the component sub-properties in the metadata. Row value constructor syntax HQL supports the use of ANSI SQL row value constructor syntax (sometimes called tuple syntax).name. Consider an entity Person which defines a name compon- ent: from Person p where p. cat. although a little verbose. even though the underlying database may not support that notion.name=('John'.name.last='Jingleheimer-Schmidt' That's valid syntax. Hibernate 3. typically associated with components.18.color ) in ( select cat.2.name from from Person p order by p.name.first Another common use of components is in Section 14.

add( Restrictions. "Fritz%") ) .list(). Restrictions may be grouped logically.list(). "Fritz%".createCriteria(Cat.isNull("age") ) ) . Restrictions.add( Restrictions.sqlRestriction("lower({alias}. Criteria crit = sess. The class org.forName().STRING) .eq("age". new Integer(2) ) ) ) ) . Hibernate 3.add( Restrictions.createCriteria(Cat.like("name". List cats = sess.like("name".list(). The Session is a factory for Criteria instances.add( Restrictions.Restrictions defines factory methods for obtaining certain built-in Criterion types. "Izi". You can create a Prop- erty by calling Property.hibernate.or( Restrictions. "Pk" } ) ) .createCriteria(Cat.eq("age".criterion.add( Restrictions.hibernate.in( "name".createCriteria(Cat.add( Restrictions.hibernate.class).list().Criterion. minWeight. "Fritz%") ) .class) .eq( "age".Criteria represents a query against a particular persistent class. There are quite a range of built-in criterion types (Restrictions subclasses). 15. crit. new Integer(0) ) ) .Chapter 15.createCriteria(Cat.7 161 . but one that is especially useful lets you specify SQL directly. Narrowing the result set An individual query criterion is an instance of the interface org.1.criterion. List cats = sess.class) . Criteria Queries Hibernate features an intuitive. maxWeight) ) .isNull("age") ) .2.list().2. new Integer(1) ) ) .setMaxResults(50). Creating a Criteria instance The interface org.add( Restrictions.class) .add( Restrictions. new String[] { "Fritz".class) .disjunction() .name) like lower(?)". 15. List cats = crit.add( Restrictions. new Integer(0) ). Hibernate. List cats = sess.add( Restrictions.between("weight". extensible criteria query API. List cats = sess. An alternative approach to obtaining a criterion is to get it from a Property instance.add( Restrictions.eq("age". The {alias} placeholder with be replaced by the row alias of the queried entity.

class) .addOrder( Property.forName("age"). List cats = sess.add( age. The following.like("name". "kt") .like("name". "F%") ) .add( Restrictions. "Pk" } ) ) .add( Restrictions.asc("name") ) .addOrder( Order.Order. "mt") .createCriteria(Cat. List cats = sess.eq( new Integer(2) ) ) ) ) .name") ) .list().list(). "mt.class) .add( age.list().eq( new Integer(0) ) ) . "F%") . note that the second createCriteria() returns a new instance of Criteria.) Note that the kittens collections held by the Cat instances returned by the previous two queries are not pre- filtered by the criteria! If you wish to retrieve just the kittens that match the criteria.createCriteria(Cat.hibernate.createCriteria(Cat.like("F%") ) . you must use a Result- Transformer.setMaxResults(50) .add( Restrictions.desc("age") ) .setMaxResults(50) . which refers to the elements of the kittens collection. "Izi".disjunction() .createAlias("kittens".add( Restrictions. Criteria Queries Property age = Property.isNull() ) .addOrder( Order.addOrder( Property.asc() ) .createCriteria(Cat.forName("name").eqProperty("kt. List cats = sess.eq( new Integer(1) ) ) . alternate form is useful in certain circumstances.class) Hibernate 3.3.class) . "F%") ) . List cats = sess.list().like("name".2.add( age.createCriteria(Cat.list(). List cats = sess.4.criterion.class) .forName("name").desc() ) .add( Property. Associations You may easily specify constraints upon related entities by navigating associations using createCriteria(). (createAlias() does not create a new instance of Criteria.forName("age").add( Restrictions. Ordering the results You may order the results using org.forName("name"). List cats = sess.name".createAlias("mate".class) . 15.in( new String[] { "Fritz".7 162 . 15.add( Property.createCriteria("kittens") .add( age.createCriteria(Cat.

setColor(Color. List cats = sess.eq("name". List results = session. FetchMode.add( Example. } 15. Example example = Example.enableLike().add( Restrictions.EAGER) . Example queries The class org.excludeProperty("color") //exclude the property named "color" .7 163 .create( cat. "Fritz%") ) .createCriteria("kittens".list(). 15. Iterator iter = cats.ALIAS_TO_ENTITY_MAP) . Dynamic association fetching You may specify association fetching semantics at runtime using setFetchMode(). FetchMode.class) .criterion.create(cat) ) . identifiers and associations are ignored. //use like for string comparisons List results = session.list().get(Criteria. See Section 19.createCriteria(Cat. “Fetching strategies” for more in- formation.ROOT_ALIAS).setFetchMode("kittens". cat. Cat kitten = (Cat) map.6.setResultTransformer(Criteria.getMate() ) ) . Cat cat = new Cat(). null valued properties are excluded. Version properties. "kt") .list(). By default.createCriteria("mate") .setSex('F').EAGER) .Example allows you to construct a query criterion from a given instance.class) .create(cat) ) .setFetchMode("mate". "F%") ) .createCriteria(Cat.createCriteria(Cat.BLACK).excludeZeroes() //exclude zero valued properties .hibernate. Hibernate 3.create(cat) .list(). while ( iter.like("name".ignoreCase() //perform case insensitive string comparisons .class) . cat.get("kt").createCriteria(Cat.add( Example. Criteria Queries .add( Example.next().class) .add(example) .hasNext() ) { Map map = (Map) iter.5. Cat cat = (Cat) map.2. You can adjust how the Example is applied.list().1. You can even use examples to place criteria upon associated objects.add( Restrictions.iterator(). List results = session. This query will fetch both mate and kittens by outer join.

Color.add( Projections.projectionList() .add( Projections.max("weight") ) .class) .addOrder( Order. You can also use Property. "avgWeight" ) .eq("color". Certain projection types are defined to be grouping projections.addOrder( Order.rowCount() ) .add( Projections.addOrder( Order.asc("colr") ) .asc("kitName") ) .addOrder( Order.2.add( Projections.class) .name"). List results = session.setProjection( Projections. An alias may optionally be assigned to a projection.addOrder( Order.class) .createCriteria(Cat.groupProperty("color") ) ) . List results = session.add( Projections. List results = session. As a shortcut. which also appear in the SQL group by clause.BLACK) ) .7 164 .createCriteria(Cat.list().as("colr") ) .hibernate.property("kit. We apply a projec- tion to a query by calling setProjection(). "cat") .avg("weight").max("weight"). "kitName" ) ) .list().setProjection( Projections.list().setProjection( Projections.add( Projections.asc("catName") ) . Criteria Queries 15. so that the projected value may be referred to in restrictions or orderings. "catName" ) .createCriteria(Cat.groupProperty("color").groupProperty("color"). aliased.name").list(). you can assign an alias when you add the projection to a projection list: List results = session.class) .projectionList() .add( Projections. Here are two different ways to do this: List results = session.alias( Projections.createCriteria(Domestic.projectionList() .add( Projections.createCriteria(Cat. "maxWeight" ) .Projections is a factory for Projection instances.class) . There is no explicit "group by" necessary in a criteria query.class.property("cat.add( Restrictions.list().asc("colr") ) . instance of Projection.desc("catCountByColor") ) . "color" ) ) . "catCountByColor" ) .rowCount().desc("avgWeight") ) .7.createAlias("kittens". List results = session.createCriteria(Cat.criterion.avg("weight") ) . aggregation and grouping The class org.groupProperty("color").forName() to express projections: Hibernate 3. The alias() and as() methods simply wrap a projection instance in another.add( Projections.add( Projections. Projections. "kit") .setProjection( Projections.setProjection( Projections.list().rowCount() ) .setProjection( Projections.addOrder( Order. "colr" ) ) .

createCriteria(Cat.forClass(Cat.class) .forClass(Cat.BLACK) ) .group().add( Property. the query cache is not very efficient.list().class) . "cat") . including criteria queries. and then later execute it us- ing some arbitrary Session.createCriteria(Cat.list().setProjection( Property.class) . List results = query.desc("catCountByColor") ) .2.as("maxWeight") ) ..forName("sex"). 15. Transaction txn = session.gt(avgWeight) ) .eqProperty("cat.class) . there is one special kind of query where we can optimize the cache inval- Hibernate 3. List results = session. Criterion instances involving subqueries may be obtained via Subqueries or Property.forClass(Cat.addOrder( Order.avg() ). DetachedCriteria query = DetachedCriteria.getExecutableCriteria(session).forName("weight"). session.as("color" ) ) . Even correlated subqueries are possible: DetachedCriteria avgWeightForSex = DetachedCriteria. A DetachedCriteria may also be used to express a subquery.7 165 .avg() ) .8.forName("weight").list().list().eq('F') ).add( Property.as("catCountByColor") ) .setProjection( Property.forClass(Cat..createCriteria(Cat.. session.max().setProjection( Property.desc("avgWeight") ) . DetachedCriteria avgWeight = DetachedCriteria.sex"). However.add( Subqueries.list().as("avgWeight") ) . txn.class) . session.close().forName("color"). 15.forName("weight).add( Property.setProjection( Projections.class) . because query cache invalida- tion occurs too frequently.forName("weight").9.class) .forName("weight).geAll("weight".createCriteria(Cat..setProjection( Property. "cat2") .commit().addOrder( Order.class.avg(). Detached queries and subqueries The DetachedCriteria class lets you create a query outside the scope of a session.rowCount().forName("name") ) .projectionList() .add( Property.gt(avgWeightForSex) ) .forName("color").add( Projections. DetachedCriteria weights = DetachedCriteria.forName("cat2.add( Property. Queries by natural identifier For most queries.add( Property.beginTransaction(). Criteria Queries List results = session.createCriteria(Cat.setMaxResults(100). session.add( Property.eq(Color. weights) ) .sex") ). Session session = .list().forName("weight").forName("weight") ).class.add( Property.

2.set("org".7 166 . this kind of query occurs frequently.naturalId() allows us to make use of the more efficient cache algorithm. Restrictions. Next.set("name". The criteria API provides special provision for this use case. Criteria Queries idation algorithm: lookups by a constant natural key.class) . <class name="User"> <cache usage="read-write"/> <id name="id"> <generator class="increment"/> </id> <natural-id> <property name="name"/> <property name="org"/> </natural-id> <property name="password"/> </class> Note that this functionality is not intended for use with entities with mutable natural keys. "gavin") .setCacheable(true) . Hibernate 3.createCriteria(User. In some applications.add( Restrictions. First. and enable use of the second-level cache.uniqueResult(). you should map the natural key of your entity using <natural-id>. "hb") ). Now. enable the Hibernate query cache.naturalId() . session.

but now ResultSetMetaData is used to decide the type of NAME and BIRTHDATE where as the type of ID is explicitly specified. NAME. sess.LONG) .1.createSQLQuery("SELECT ID.addScalar("NAME". It also provides a clean migra- tion path from a direct SQL/JDBC based application to Hibernate. BIRTHDATE FROM CATS"). Scalar queries The most basic SQL query is to get a list of scalars (values).list(). sess.STRING) . 16.list(). sess.createSQLQuery(). Hibernate. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.addScalar("NAME") . even though the query is using * and could re- turn more than the three listed columns. Hibernate. update. Hibernate 3. Hibernate.addScalar("BIRTHDATE") This is essentially the same query as before. String and a Short from the underlying resultset. It is possible to leave out the type information for all or some of the scalars.2. The following describes how to use this API for querying.createSQLQuery("SELECT * FROM CATS"). 16.addScalar("BIRTHDATE". These will both return a List of Object arrays (Object[]) with scalar values for each column in the CATS table. but now it will not use ResultSetMetdata but will instead explicitly get the ID. Hibernate.addScalar("ID". Using a SQLQuery Execution of native SQL queries is controlled via the SQLQuery interface.7 167 . To avoid the overhead of using ResultSetMetadata or simply to be more explicit in what is returned one can use addScalar().createSQLQuery("SELECT * FROM CATS") . This also means that only these three columns will be returned. NAME and BIRTHDATE column as respectively a Long.1.Chapter 16. which is obtained by calling Ses- sion. delete.1. and load operations. Native SQL You may also express queries in the native SQL dialect of your database.DATE) This query specified: • the SQL query string • the columns and types to return This will still return Object arrays. This is useful if you want to utilize database specific features such as query hints or the CONNECT keyword in Oracle. Hibernate3 allows you to specify handwritten SQL (including stored procedures) for all create.LONG) .addScalar("ID". sess.createSQLQuery("SELECT * FROM CATS") .

Entity queries The above queries were all about returning scalar values. which allows you to join in an association or collection.4. DOG_ID FROM CATS"). D_NAME. This is done via the addJoin() method. BIRTHDATE. NAME.addJoin("cat. Native SQL How the java. sess.addEntity(Cat.createSQLQuery("SELECT c. Returning multiple entities Hibernate 3. NAME.2. NAME. DOGS d WHERE c.createSQLQuery("SELECT ID. Notice that we added a alias name ("cat") to be able to specify the target property path of the join.7 168 .</p> 16. <p>At this stage we are reaching the limits of what is possible with native queries without starting to enhance the sql queries to make them usable in Hibernate.ID = . The additional columns will automatically be returned when using the * notation.Types returned from ResultSetMetaData is mapped to Hibernate types is controlled by the Dialect. BIRTHDATE FROM CATS"). the problems starts to arise when returning multiple entities of the same type or when the default alias/column names are not enough.1. Cat.2.class) . NAME and BIRTHDATE the above queries will both return a List where each element is a Cat entity.addEntity(Cat. The following shows how to get entity objects from a native sql query via addEntity(). if the Cat had a one-to-many to Dog instead. DOGS d WHERE c. Handling associations and collections It is possible to eagerly join in the Dog to avoid the possible extra roundtrip for initializing the proxy.addEntity("cat". This will allow cat.1.class).class). but we prefer to be explicit as in the following ex- ample for a many-to-one to a Dog: sess.dogs"). DOG_ID. 16. In this example the returned Cat's will have their dog property fully initialized without any extra roundtrip to the database. NAME. e.class).createSQLQuery("SELECT * FROM CATS"). If a specific type is not mapped or does not result in the expected type it is possible to customize it via calls to registerHibernateType in the Dialect.addJoin("cat.sql. basically returning the "raw" values from the result- set.ID. If the entity is mapped with a many-to-one to another entity it is required to also return this when performing the native query.dog").createSQLQuery("SELECT ID.addEntity(Cat.createSQLQuery("SELECT ID.class) .DO . It is possible to do the same eager joining for collections. 16. CAT_ID FROM CATS c.1. sess. otherwise a database specific "column not found" error will occur.3. BIRTHDATE.g. D_NAME FROM CATS c. D_ID. Cat.addEntity("cat". This query specified: • the SQL query string • the entity returned by the query Assuming that Cat is mapped as a class with the columns ID. BIRTHDATE. D_ID. sess. sess.getDog() to function properly.

class) This query specified: • the SQL query string.id}. List loggedCats = sess. inheritance discriminators. The following form is not vulnerable to column name duplication: sess.* FROM CATS c. Alias injection names Description Syntax Example A simple property {[aliasname]. CAT_LOG m WHERE {c. since the same column names may appear in more than one table.ID". Cat.class).class) . with placeholders for Hibernate to inject column aliases • the entities returned by the query The {cat.ID") .class) . Native SQL Until now the result set column names are assumed to be the same as the column names specified in the map- ping document.class) .name} rtyname] Hibernate 3. MOTHER_ID as {c.*} notation used above is a shorthand for "all properties". Cat. CATS m WHERE c. " + "BIRTHDATE as {c.ID".createSQLQuery(sql) .*}.addEntity("mother".name}. This will fail since there is a conflict of names since they are mapped to the same column names and on some databases the returned column aliases will most likely be on the form "c.class) The intention for this query is to return two Cat instances per row. Column alias injection is needed in the following query (which most likely will fail): sess.addEntity("cat". {mother. etc.createSQLQuery("SELECT {cat. The following table shows the different possibilities of using the alias injection. NAME as {c.MOTHER_ID = c. Alternatively.createSQLQuery("SELECT c. {mother.*. String sql = "SELECT ID as {c. collections etc.1. This can be problematic for SQL queries which join multiple tables. there are some specific aliases to use to allow Hi- bernate to inject the proper aliases. a cat and its mother.mother} = c.ID") .*} " + "FROM CAT_LOG c.*} and {mother. each alias will have a unique and probably different name when used. "c.addEntity("mother". The placeholder for a column alias is just the property name qualified by the table alias. Cat. Table 16.addEntity("cat". which are not equal to the columns spe- cificed in the mappings ("ID" and "NAME"). m.list() Alias and property references For most cases the above alias injection is needed.[prope A_NAME as {item.*} FROM CATS c.MOTHER_ID = c.addEntity("cat". In the following ex- ample. we retrieve Cats and their mothers from a different table (cat_log) to the one declared in the mapping metadata. Notice that we may even use the property aliases in the where clause if we like. Cat.addEntity("mother". CATS m WHERE c. but for queries relating to more complex mappings like com- posite properties. you may list the columns explicity.NAME". but even in this case we let Hibernate inject the SQL column aliases for each property. Cat.2. Note: the alias names in the result are examples.mother}.birthDate}. Cat.7 169 .

createSQLQuery("SELECT NAME.class} entity All properties of an {[aliasname].element. Handling inheritance Native sql queries which query for entities that is mapped as part of an inheritance must include all properties for the baseclass and all it subclasses.6.*} element in the collec.elemen NAME as {coll. VALUE as nent.7 170 .*} the collection 16.*} {item.5.key} The id of an collection {[aliasname].1.elemen XID as {coll. sess. {item.setResultTransformer(Transformers.1.{[aliasname].element.t.key} ORGID as {coll.amount. Parameters Hibernate 3. Returning non-managed entities It is possible to apply a ResultTransformer to native sql queries.[compo CURRENCY as {item.[propertyname ]} Discriminator of an {[aliasname].*} {coll.name} in the collection t. 16. Native SQL Description Syntax Example A composite property {[aliasname].id} The element of an col.g.currency}.*} tion All properties of the {[aliasname].2. 16.aliasToBean(CatDTO.amount. BIRTHDATE FROM CATS") .*} entity A collection key {[aliasname].elemen {coll.[propertyname]} All properties of the {[aliasname].class} DISC as {item.class)) This query specified: • the SQL query string • a result transformer The above query will return a list of CatDTO which has been instantiated and injected the values of NAME and BIRTHNAME into its corresponding properties or fields. Allowing it to e.1. return non-managed entit- ies.id} EMPID as {coll.element} lection t} roperty of the element {[aliasname].value} name].7.

Person"/> <return-join alias="address" property="person.state}.NAME LIKE :namePattern </sql-query> List people = sess.7 171 . "Pus%"). "Pus%").SEX AS {person.NAME AS name.list(). List pusList = query.NAME AS {person.age}.NAME LIKE 'Hiber%' </sql-query> You can externalize the resultset mapping informations in a <resultset> element to either reuse them accross several named queries or through the setResultSetMapping() API.Person"/> SELECT person. adddress.setMaxResults(50) .NAME LIKE :namePattern </sql-query> A named SQL query may return a scalar value.sex} FROM PERSON person WHERE person.ZIP AS {address.AGE AS {person.list(). adddress. adddress.CITY AS {address. 16. namePattern) . The <return-join> and <load-collection> elements are used to join associations and define queries which initialize collections. List pusList = query.SEX AS {person.mailingAddress"/> SELECT person.name}.createSQLQuery("SELECT * FROM CATS WHERE NAME like ?").class).addEntity(Cat.ID = address.setString("name".sex}.TYPE='MAILING' WHERE person. <resultset name="personAddress"> Hibernate 3. query = sess. person.class). person. Named SQL queries Named SQL queries may be defined in the mapping document and called in exactly the same way as a named HQL query.AGE AS {person.AGE AS age. <sql-query name="personsWith"> <return alias="person" class="eg. FROM PERSON p WHERE p.name}.getNamedQuery("persons") . In this case. person.STREET AS {address. we do not need to call addEntity().street}.list(). p.2.NAME AS {person.addEntity(Cat.STATE AS {address.zip} FROM PERSON person JOIN ADDRESS adddress ON person.PERSON_ID AND address.setString(0.createSQLQuery("SELECT * FROM CATS WHERE NAME like :name").2.age}. You must declare the column alias and Hibernate type using the <return-scalar> element: <sql-query name="mySqlQuery"> <return-scalar column="name" type="string"/> <return-scalar column="age" type="long"/> SELECT p. person. respectively. <sql-query name="persons"> <return alias="person" class="eg.setString("namePattern". adddress.city}. Native SQL Native sql queries support positional as well as named parameters: Query query = sess.

endDate}.1.mother = cat. <sql-query name="mySqlQuery"> <return alias="person" class="eg. List cats = sess.startDate}. ENDDATE AS {emp.Person"/> <return-join alias="address" property="person. person.state}.AGE AS myAge. FROM PERSON person WHERE person. adddress.SEX AS mySex. {kitten. Al- Hibernate 3.street}. Using return-property to explicitly specify column/alias names With <return-property> you can explicitly tell Hibernate what column aliases to use.zip} FROM PERSON person JOIN ADDRESS adddress ON person. adddress. EID AS {emp.id}.NAME LIKE :namePattern </sql-query> You can alternatively use the resultset mapping information in your hbm files directly in java code.age}.STREET AS {address.setResultSetMapping("catAndKitten") .Person"> <return-property name="name" column="myName"/> <return-property name="age" column="myAge"/> <return-property name="sex" column="mySex"/> </return> SELECT person. <sql-query name="organizationCurrentEmployments"> <return alias="emp" class="Employment"> <return-property name="salary"> <return-column name="VALUE"/> <return-column name="CURRENCY"/> </return-property> <return-property name="endDate" column="myEndDate"/> </return> SELECT EMPLOYEE AS {emp.employer}. person.2.NAME AS myName.employee}. STARTDATE AS {emp. 16.SEX AS {person.7 172 . CURRENCY FROM EMPLOYMENT WHERE EMPLOYER = :id AND ENDDATE IS NULL ORDER BY STARTDATE ASC </sql-query> Notice that in this example we used <return-property> in combination with the {}-syntax for injection. VALUE.STATE AS {address.mailingAddress"/> </resultset> <sql-query name="personsWith" resultset-ref="personAddress"> SELECT person. person. REGIONCODE as {emp.city}.TYPE='MAILING' WHERE person.*} from cats cat.2. Native SQL <return alias="person" class="eg. instead of using the {}- syntax to let Hibernate inject its own aliases.NAME AS {person.AGE AS {person. adddress.regionCode}.*}.ZIP AS {address.id" ) . This solves a limitation with the {}-syntax which can not allow fine grained control of multi-column properties.CITY AS {address.createSQLQuery( "select {cat. adddress.sex}. EMPLOYER AS {emp.list(). person.name}.NAME LIKE :name </sql-query> <return-property> also works with multiple columns.ID = address.PERSON_ID AND address. cats kitten where kitten.

Stored procedure queries can't be paged with setFirstResult()/setMaxResults(). ENDDATE. If your mapping has a discriminator you must use <return-discriminator> to specify the discriminator column. 16.2. EMPLOYER. since database vendors have differ- ent stored procedure semantics/syntax. Native call syntax is not supported. END. <sql-query name="selectAllEmployees_SP" callable="true"> <return alias="emp" class="Employment"> <return-property name="employee" column="EMPLOYEE"/> <return-property name="employer" column="EMPLOYER"/> <return-property name="startDate" column="STARTDATE"/> <return-property name="endDate" column="ENDDATE"/> <return-property name="regionCode" column="REGIONCODE"/> <return-property name="id" column="EID"/> <return-property name="salary"> <return-column name="VALUE"/> <return-column name="CURRENCY"/> </return-property> </return> { ? = call selectAllEmployments() } </sql-query> Notice stored procedures currently only return scalars and entities. An example of such a stored function in Oracle 9 and higher is as follows: CREATE OR REPLACE FUNCTION selectAllEmployments RETURN SYS_REFCURSOR AS st_cursor SYS_REFCURSOR. The rules are different for each database. RETURN st_cursor. Most of the following docu- mentation is equivalent for both. STARTDATE. REGIONCODE. If they do not fol- low those rules they are not usable with Hibernate. Native SQL lowing users to choose how they want to refer column and properties. BEGIN OPEN st_cursor FOR SELECT EMPLOYEE. EID.2. Rules/limitations for using stored procedures To use stored procedures with Hibernate the procedures/functions have to follow some rules. For Oracle the following rules apply: • A function must return a result set. The first parameter of a procedure must be an OUT that returns a result Hibernate 3. Recommended call form is standard SQL92: { ? = call functionName(<parameters>) } or { ? = call procedureName(<parameters>}. To use this query in Hibernate you need to map it via a named query. Using stored procedures for querying Hibernate 3 introduces support for queries via stored procedures and functions. <return-join> and <load-collection> are not supported. VALUE. If you still want to use these procedures you have to execute them via session. CURRENCY FROM EMPLOYMENT.7 173 . The stored procedure/function must return a resultset as the first out-parameter to be able to work with Hibernate.2.connection().

so you are free to use any dialect you like. Hibernate will iterate the results and take the first result that is a result set as its return value. This will of course reduce the portability of your mapping if you use database specific SQL. ? )</sql-insert> <sql-update>UPDATE PERSON SET NAME=UPPER(?) WHERE ID=?</sql-update> <sql-delete>DELETE FROM PERSON WHERE ID=?</sql-delete> </class> The SQL is directly executed in your database. as Hibernate has some runtime checks for the success of the statement. Note that since these servers can/will return multiple result sets and update counts. Custom SQL for create. and delete operations. updat- esql etc. Hibernate always registers the first statement parameter as a numeric output parameter for the CUD operations: CREATE OR REPLACE FUNCTION updatePerson (uid IN NUMBER. deletesql.7 174 .2. Stored procedures are supported if the callable attribute is set: <class name="Person"> <id name="id"> <generator class="increment"/> </id> <property name="name" not-null="true"/> <sql-insert callable="true">{call createPerson (?. ?)}</sql-update> </class> The order of the positional parameters are currently vital. You can see the expected order by enabling debug logging for the org. This is done by using a SYS_REFCURSOR type in Oracle 9 or 10. update. remember to not include your custom SQL in the mapping files as that will override the Hibernate generated static sql. and <sql-update> override these strings: <class name="Person"> <id name="id"> <generator class="increment"/> </id> <property name="name" not-null="true"/> <sql-insert>INSERT INTO PERSON (NAME. ?)}</sql-insert> <sql-delete callable="true">{? = call deletePerson (?)}</sql-delete> <sql-update callable="true">{? = call updatePerson (?. <sql-delete>.entity level.hibernate. update and delete Hibernate3 can use custom SQL statements for create. The mapping tags <sql-insert>. update.persister. The class and collection persisters in Hibernate already contain a set of configuration time generated strings (insertsql. In Oracle you need to define a REF CURSOR type. Native SQL set. delete etc. but this is not a re- quirement. With this level enabled Hibernate will print out the static SQL that is used to create. Everything else will be discarded. 16. ID) VALUES ( UPPER(?).) The stored procedures are in most cases (read: better do it than not) required to return the number of rows inser- ted/updated/deleted. uname IN VARCHAR2) RETURN NUMBER IS BEGIN update PERSON Hibernate 3. see Oracle literature.).3. For Sybase or MS SQL server the following rules apply: • The procedure must return a result set. as they must be in the same sequence as Hibernate expects them. • If you can enable SET NOCOUNT ON in your procedure it will probably be more efficient. (To see the expected sequence. entities.

id} FROM PERSON WHERE ID=? FOR UPDATE </sql-query> This is just a named query declaration. where ID = uid. END updatePerson. {emp.*} FROM PERSON pers LEFT OUTER JOIN EMPLOYMENT emp ON pers.*}.PERSON_ID WHERE ID=? </sql-query> Hibernate 3. return SQL%ROWCOUNT. You may even define a query for collection loading: <set name="employments" inverse="true"> <key/> <one-to-many class="Employment"/> <loader query-ref="employments"/> </set> <sql-query name="employments"> <load-collection alias="emp" role="Person.2.4.ID = emp.*} FROM EMPLOYMENT emp WHERE EMPLOYER = :id ORDER BY STARTDATE ASC.name}. You may reference this named query in a class mapping: <class name="Person"> <id name="id"> <generator class="increment"/> </id> <property name="name" not-null="true"/> <loader query-ref="person"/> </class> This even works with stored procedures.employments"/> SELECT NAME AS {pers.7 175 . Custom SQL for loading You may also declare your own SQL (or HQL) queries for entity loading: <sql-query name="person"> <return alias="pers" class="Person" lock-mode="upgrade"/> SELECT NAME AS {pers. EMPLOYEE ASC </sql-query> You could even define an entity loader that loads a collection by join fetching: <sql-query name="person"> <return alias="pers" class="Person"/> <return-join alias="emp" property="pers. 16. Native SQL set NAME = uname. as discussed earlier. ID AS {pers.employments"/> SELECT {emp.

. A full example.. Note that methods on the org. <filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/> </class> or. To define a filter.. this would look like: session.2.7 176 .. but parameterized inside the application. filters are not enabled for a given session.hibernate.. to a collection: <set . which returns an instance of the Filter interface. In order to use filters.setParameter("myFilterParam". Filtering data Hibernate3 provides an innovative new approach to handling data with "visibility" rules. A filter criteria is the ability to define a restriction clause very similiar to the existing "where" attribute available on the class and various collection elements.. use the <filter-def/> element within a <hibernate-mapping/> element: <filter-def name="myFilter"> <filter-param name="myFilterParam" type="string"/> </filter-def> Then. getEnabledFilter(String filterName). By default. Except these filter conditions can be parameterized. <many-to-one name="department" column="dept_id" class="Department"/> <property name="effectiveStartDate" type="date" column="eff_start_dt"/> <property name="effectiveEndDate" type="date" column="eff_end_dt"/> Hibernate 3. this filter can be attached to a class: <class name="myClass" ..> .> <filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/> </set> or. even to both (or multiples of each) at the same time.Chapter 17. "some-value"). Using the simple filter defined above.1. The methods on Session are: enableFilter(String filterName). A Hibernate filter is a global. using temporal data with an effective record date pattern: <filter-def name="effectiveDate"> <filter-param name="asOfDate" type="date"/> </filter-def> <class name="Employee" . Hibernate filters Hibernate3 adds the ability to pre-define filter criteria and attach those filters at both a class and a collection level. and disableFilter(String filterName)..Filter interface do allow the method-chaining common to much of Hi- bernate. they must first be defined and then attached to the appropriate mapping elements. named.> . Filters can be used like database views. they must be explcitly enabled through use of the Session.enableFilter() method.. The application can then make the decision at runtime whether given filters should be enabled and what their para- meter values should be.. 17. parameterized filter that may be enabled or disabled for a particular Hibernate session.enableFilter("myFilter").

Note: if you plan on using filters with outer joining (either through HQL or load fetching) be careful of the dir- ection of the condition expression.</filter-def> <filter-def name="myOtherFilter">abc=xyz</filter-def> This default condition will then be used whenever the filter is attached to something without specifying a con- dition.salary > :targetSalary") ....enabledFilter("effectiveDate"). new Date()).. even though we only explicitly mentioned a salary constraint on the results. Filtering data .2. either as an attribute or CDATA: <filter-def name="myFilter" condition="abc > xyz">. new Long(1000000)) . Hibernate 3.. <set name="employees" lazy="true"> <key column="dept_id"/> <one-to-many class="Employee"/> <filter name="effectiveDate" condition=":asOfDate BETWEEN eff_start_dt and eff_end_dt"/> </set> </class> Then. List results = session. simply enable the filter on the ses- sion prior to retrieving employee data: Session session = . in general. because of the enabled filter the query will return only currently active employees who have a salary greater than a million dollars.7 177 .> ... Note that this means you can give a specific condition as part of the attachment of the filter which over- rides the default condition in that particular case.. In the HQL above. After being defined a filter might be attached to multiple entities and/or collections each with its own condition.createQuery("from Employee as e where e.list().. That can be tedious when the conditions are the same each time. place the parameter first followed by the column name(s) after the operator. <!-- Note that this assumes non-terminal records have an eff_end_dt set to a max db date for simplicity-sake --> <filter name="effectiveDate" condition=":asOfDate BETWEEN eff_start_dt and eff_end_dt"/> </class> <class name="Department" . Thus <filter-def/> allows defining a default condition. Its safest to set this up for left outer joining.setLong("targetSalary".setParameter("asOfDate". session.. in order to ensure that you always get back currently effective records..

1. You can write queries that retrieve dom4j trees from the database and have any modification you make to the tree automatically synchronized to the database. Hibernate supports dom4j as API for manipulating XML trees. parse it using dom4j. </class> 18. A single mapping may be used to simultaneously map properties of a class and nodes of an XML document to the database. XML Mapping Note that this is an experimental feature in Hibernate 3. it may be used to map just the XML.1. merge().. replicate() (merging is not yet sup- ported).Chapter 18.0 and is under extremely active development.2. Working with XML data Hibernate lets you work with persistent XML data in much the same way you work with persistent POJOs. in- stead of POJOs. and write it to the database with any of Hibernate's basic operations: persist(). saveOrUpdate(). 18. or.2. This feature has many applications including data import/export. externalization of entity data via JMS or SOAP and XSLT-based reporting.1. You can even take an XML document.. delete(). Specifying XML and class mapping together Here is an example of mapping a POJO and XML simultaneously: <class name="Account" table="ACCOUNTS" node="account"> <id name="accountId" column="ACCOUNT_ID" node="@id"/> <many-to-one name="customer" column="CUSTOMER_ID" node="customer/@id" embed-xml="false"/> <property name="balance" column="BALANCE" node="balance"/> . A parsed XML tree can be thought of as just another way to represent the relational data at the object level.1. if there is no class to map. Specifying only an XML mapping Here is an example where there is no POJO class: <class entity-name="Account" table="ACCOUNTS" node="account"> <id name="id" column="ACCOUNT_ID" Hibernate 3. 18.7 178 .

XML Mapping

node="@id"
type="string"/>

<many-to-one name="customerId"
column="CUSTOMER_ID"
node="customer/@id"
embed-xml="false"
entity-name="Customer"/>

<property name="balance"
column="BALANCE"
node="balance"
type="big_decimal"/>

...

</class>

This mapping allows you to access the data as a dom4j tree, or as a graph of property name/value pairs (java
Maps). The property names are purely logical constructs that may be referred to in HQL queries.

18.2. XML mapping metadata
Many Hibernate mapping elements accept the node attribute. This let's you specify the name of an XML attrib-
ute or element that holds the property or entity data. The format of the node attribute must be one of the follow-
ing:

• "element-name" - map to the named XML element
• "@attribute-name" - map to the named XML attribute
• "." - map to the parent element
• "element-name/@attribute-name" - map to the named attribute of the named element

For collections and single valued associations, there is an additional embed-xml attribute. If embed-xml="true",
the default, the XML tree for the associated entity (or collection of value type) will be embedded directly in the
XML tree for the entity that owns the association. Otherwise, if embed-xml="false", then only the referenced
identifier value will appear in the XML for single point associations and collections will simply not appear at
all.

You should be careful not to leave embed-xml="true" for too many associations, since XML does not deal well
with circularity!

<class name="Customer"
table="CUSTOMER"
node="customer">

<id name="id"
column="CUST_ID"
node="@id"/>

<map name="accounts"
node="."
embed-xml="true">
<key column="CUSTOMER_ID"
not-null="true"/>
<map-key column="SHORT_DESC"
node="@short-desc"
type="string"/>
<one-to-many entity-name="Account"
embed-xml="false"
node="account"/>
</map>

Hibernate 3.2.7 179

XML Mapping

<component name="name"
node="name">
<property name="firstName"
node="first-name"/>
<property name="initial"
node="initial"/>
<property name="lastName"
node="last-name"/>
</component>

...

</class>

in this case, we have decided to embed the collection of account ids, but not the actual account data. The fol-
lowing HQL query:

from Customer c left join fetch c.accounts where c.lastName like :lastName

Would return datasets such as this:

<customer id="123456789">
<account short-desc="Savings">987632567</account>
<account short-desc="Credit Card">985612323</account>
<name>
<first-name>Gavin</first-name>
<initial>A</initial>
<last-name>King</last-name>
</name>
...
</customer>

If you set embed-xml="true" on the <one-to-many> mapping, the data might look more like this:

<customer id="123456789">
<account id="987632567" short-desc="Savings">
<customer id="123456789"/>
<balance>100.29</balance>
</account>
<account id="985612323" short-desc="Credit Card">
<customer id="123456789"/>
<balance>-2370.34</balance>
</account>
<name>
<first-name>Gavin</first-name>
<initial>A</initial>
<last-name>King</last-name>
</name>
...
</customer>

18.3. Manipulating XML data
Let's rearead and update XML documents in the application. We do this by obtaining a dom4j session:

Document doc = ....;

Session session = factory.openSession();
Session dom4jSession = session.getSession(EntityMode.DOM4J);
Transaction tx = session.beginTransaction();

List results = dom4jSession
.createQuery("from Customer c left join fetch c.accounts where c.lastName like :lastName")

Hibernate 3.2.7 180

XML Mapping

.list();
for ( int i=0; i<results.size(); i++ ) {
//add the customer data to the XML document
Element customer = (Element) results.get(i);
doc.add(customer);
}

tx.commit();
session.close();

Session session = factory.openSession();
Session dom4jSession = session.getSession(EntityMode.DOM4J);
Transaction tx = session.beginTransaction();

Element cust = (Element) dom4jSession.get("Customer", customerId);
for ( int i=0; i<results.size(); i++ ) {
Element customer = (Element) results.get(i);
//change the customer name in the XML and database
Element name = customer.element("name");
name.element("first-name").setText(firstName);
name.element("initial").setText(initial);
name.element("last-name").setText(lastName);
}

tx.commit();
session.close();

It is extremely useful to combine this feature with Hibernate's replicate() operation to implement XML-
based data import/export.

Hibernate 3.2.7 181

Chapter 19. Improving performance

19.1. Fetching strategies
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to
navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a
particular HQL or Criteria query.

Hibernate3 defines the following fetching strategies:

• Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER
JOIN.

• Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly
disable lazy fetching by specifying lazy="false", this second select will only be executed when you actu-
ally access the association.

• Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in
a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this
second select will only be executed when you actually access the association.

• Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances
or collections in a single SELECT, by specifying a list of primary keys or foreign keys.

Hibernate also distinguishes between:

• Immediate fetching - an association, collection or attribute is fetched immediately, when the owner is
loaded.

• Lazy collection fetching - a collection is fetched when the application invokes an operation upon that collec-
tion. (This is the default for collections.)

• "Extra-lazy" collection fetching - individual elements of the collection are accessed from the database as
needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed (suitable for
very large collections)

• Proxy fetching - a single-valued association is fetched when a method other than the identifier getter is in-
voked upon the associated object.

• "No-proxy" fetching - a single-valued association is fetched when the instance variable is accessed. Com-
pared to proxy fetching, this approach is less lazy (the association is fetched even when only the identifier is
accessed) but more transparent, since no proxy is visible to the application. This approach requires build-
time bytecode instrumentation and is rarely necessary.

• Lazy attribute fetching - an attribute or single valued association is fetched when the instance variable is ac-
cessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.

We have two orthogonal notions here: when is the association fetched, and how is it fetched (what SQL is
used). Don't confuse them! We use fetch to tune performance. We may use lazy to define a contract for what
data is always available in any detached instance of a particular class.

Hibernate 3.2.7 182

These defaults make sense for almost all associations in almost all applications. Access to a lazy association outside of the context of an open Hibernate session will result in an exception.1.close().get("accounts"). Hibernate3 uses lazy select fetching for collections and lazy proxy fetching for single-valued asso- ciations. it is intended that lazy initialization be used for almost all collections and associ- ations. Alternatively.1. Tuning fetch strategies Select fetching (the default) is extremely vulnerable to N+1 selects problems. The fix is to move the code that reads from the collection to just before the transaction is committed. the collection will not be able to load its state.commit(). User u = (User) s. lazy fetching poses one problem that you must be aware of.name=:userName") . the mech- anisms for choosing a fetch strategy are identical for single-valued associations and collections. In Hibernate3. Note: if you set hibernate. Hibernate will use the batch fetch optimization for lazy fetching (this optimization may also be enabled at a more granular level). Improving performance 19.2. However. Transaction tx = s. we could use a non-lazy collection or association. // Error! Since the permissions collection was not initialized when the Session was closed. Map permissions = u. tx. s.1. We'll now see how to customize the fetching strategy. If you define too many non-lazy associations in your object model. Working with lazy associations By default. Integer accessLevel = (Integer) permissions.beginTransaction(). so we might want to enable join fetching in the mapping document: <set name="permissions" fetch="join"> <key column="userId"/> <one-to-many class="Permission"/> </set <many-to-one name="mother" class="Cat" fetch="join"/> The fetch strategy defined in the mapping document affects: • retrieval via get() or load() • retrieval that happens implicitly when an association is navigated • Criteria queries Hibernate 3.setString("userName". by specifying lazy="false" for the associ- ation mapping. 19. For example: s = sessions.2.uniqueResult(). Hibernate will end up needing to fetch the entire database into memory in every transaction! On the other hand.getPermissions(). userName).7 183 .createQuery("from User u where u. However.default_batch_fetch_size. we often want to choose join fetching (which is non-lazy by nature) instead of select fetch- ing in a particular transaction.openSession(). Hibernate does not support lazy initialization for detached objects.

In the Criteria query API. eg.load(Cat. simply use a Criteria query..class. id).. The target entity of the association must be proxied.class) . Instead.2. with the proxy attribute. If you ever feel like you wish you could change the fetching strategy used by get() or load(). // instantiate a proxy (does not hit the db) if ( cat. id). even if the underlying instance is an instance of DomesticCat: Cat cat = (Cat) session.createCriteria(User.. (This is Hibernate's equivalent of what some ORM solutions call a "fetch plan". Usually.JOIN) .) A completely different way to avoid problems with N+1 selects is to use the second-level cache.. The mapping file may declare an interface to use as the proxy interface for that class. for example: User user = (User) session. Note that this might result in several immediate selects being used to execute a particular HQL query. Hibernate implements lazy initializing proxies for persistent objects using runtime bytecode enhancement (via the excellent CGLIB library).1.. instances of Cat will never be castable to DomesticCat. we don't use the mapping document to customize fetching.. we keep the default behavior.. <subclass name="DomesticCat"> ..3. Single-ended association proxies Lazy fetching for collections is implemented using Hibernate's own implementation of persistent collections.load(Cat.. you would use setFetch- Mode(FetchMode. <class name="Cat" proxy="Cat"> . the defined non-lazy graph is guaranteed to be loaded into memory. a different mechanism is needed for lazy behavior in single-ended associations. and override it for a particular transaction. using left join fetch in HQL. Hibernate uses a subclass of the class. it is possible to break proxy ==. However.. using an outer join. Hibernate3 generates proxies (at startup) for all persistent classes and uses them to enable lazy fetching of many-to-one and one-to-one associations. // Error! .idEq(userId) ) . 19. Note that the proxied class must implement a default con- structor with at least package visibility..uniqueResult(). By default. Improving performance • HQL queries if subselect fetching is used No matter what fetching strategy you use. This tells Hibernate to fetch the associ- ation eagerly in the first select.JOIN). We recommend this constructor for all persistent classes! There are some gotchas to be aware of when extending this approach to polymorphic classes. Cat cat = (Cat) session. } Secondly. </subclass> </class> Firstly.class.isDomesticCat() ) { // hit the db to initialize the proxy DomesticCat dc = (DomesticCat) cat.add( Restrictions. FetchMode..7 184 . // instantiate a Cat proxy Hibernate 3.setFetchMode("permissions". By default.

name='fritz'").println( dc. // false However. The proxy class is an actual subclass of the persistent class.. if the persistent class does not override equals() • hashCode(). when the entity owning the collection or having the reference to the proxy is in the detached state. // hit the db to initialize the proxy System.out. in initializers or default con- structor). we can avoid the problems associated with typecasting.. Then proxies for instances of Cat and DomesticCat may be returned by load() or iterate(). Relationships are also lazily initialized.. If you wish to avoid these problems your persistent classes must each implement an interface that declares its business methods. ie. Initializing collections and proxies A LazyInitializationException will be thrown by Hibernate if an uninitialized collection or proxy is ac- cessed outside of the scope of the Session. <subclass name="DomesticCatImpl" proxy="DomesticCat"> . you may not use a CGLIB proxy for a final class or a class with any final methods. Iterator iter = session. eg. Even though we now have two references to different proxy objects. // 11.) Cat cat = (Cat) session.. These problems are all due to fundamental limitations in Java's single inheritance model. catid).println(cat==dc).getWeight() ).. Improving performance DomesticCat dc = (DomesticCat) session.. Cat fritz = (Cat) iter.load(DomesticCat.class. (Note that list() does not usually return proxies. we will require buildtime bytecode instrumentation.iterate("from CatImpl as cat where cat. Hibernate 3. and all operations will result in im- mediate proxy initialization. However. Certain operations do not require proxy initialization • equals().2. By choosing lazy="no-proxy" instead of the default lazy="proxy". // acquire new DomesticCat proxy! System.setWeight(11. Finally. the situation is not quite as bad as it looks.. </subclass> </class> where CatImpl implements the interface Cat and DomesticCatImpl implements the interface DomesticCat.next(). if your persistent object acquires any resources upon instantiation (eg. 19.4. then those resources will also be acquired by the proxy.0).. if the persistent class does not override hashCode() • The identifier getter method Hibernate will detect persistent classes that override equals() or hashCode().class. not CatImpl.0 Third.out.1.load(CatImpl..7 185 . <class name="CatImpl" proxy="Cat"> . You should specify these interfaces in the mapping file. This means you must declare any properties to be of type Cat. the underlying instance will still be the same object: cat. id).

This is usually easier if you adopt the Command pattern instead of a Session Facade.7 186 .intValue() The createFilter() method is also used to efficiently retrieve subsets of a collection without needing to ini- tialize the whole collection: s. for example.initialize(cat) will force the initialization of a proxy. Hibernate. even when an exception occurs during rendering of the view.setMaxResults(10). this places heavy demands on the correctness of the exception handling of your application infrastructure. 19. once the rendering of the view is complete (the Open Session in View pattern). but still need some information about it (like its size) or a subset of the data. Batch fetching for classes/entities is easier to understand.initialize( cat. Imagine you have the following situation at runtime: Hibernate 3.list().5. and certainly should not do this auto- matically.setFirstResult(0). You can use a collection filter to get the size of a collection without initializing it: ( (Integer) s. There are two ways you can tune batch fetching: on the class and the collection level.JOIN in Criteria.getKittens().createFilter( collection. Usually. that is.isInitialized() provide the application with a convenient way of working with lazily initialized collections or proxies. Another option is to keep the Session open until all needed collections and proxies have been loaded.createFilter( lazyCollection. See the Hibernate Wiki for examples of this "Open Session in View" pattern. as long as its Session is still open. Batch fetching is an optimization of the lazy select fetching strategy. There are two basic ways to deal with this issue: • In a web-based application. the business logic must "prepare" all collections that will be needed by the web tier before returning.get(0) ). and the code that uses it are in different application layers or different physical processes.initialize() and Hibernate. Hibernate can load several uninitialized proxies if one proxy is accessed (or collections. the application calls Hibernate. It is vitally important that the Session is closed and the transaction ended before returning to the user.getKittens() ) has a similar effect for the collection of kittens. • In an application with a separate business tier.2. Hibernate does not.getSex() or cat. a servlet filter can be used to close the Session only at the very end of a user request. ""). since it would introduce ad hoc transaction semantics! Sometimes you don't want to initialize a large collection. Hibernate. Improving performance Sometimes we need to ensure that a proxy or collection is initialized before closing the Session. This means that the business tier should load all the data and return all the data already initialized to the presentation/web tier that is required for a particular use case. No.list(). Of course. Using batch fetching Hibernate can make efficient use of batch fetching. • You may also attach a previously loaded object to a new Session with merge() or lock() before accessing uninitialized collections (or other proxies). But that is confusing to readers of the code and is not convenient for generic code. particularly where the code that accesses data using Hibernate. The static methods Hibernate. it can be a problem to ensure that the Ses- sion is open when a collection is initialized.initialize() for each collection that will be needed in the web tier (this call must occur before the session is closed) or retrieves the collection eagerly using a Hibernate query with a FETCH clause or a FetchMode. "select count(*)" ). cat.size(). we can alway force initialization by calling cat. In some application architectures.1. Of course.

However. 3. For example. If you now iterate through all cats and call getOwner() on each. and 10 persons are currently loaded in the Sesssion.6. This optimization technique is also known as fetch groups..1.2. The Person class is mapped with a proxy. the value of the at- tribute depends on the expected number of uninitialized collections in a particular Session. </set> </class> With a batch-size of 8. use the following Ant task: <target name="instrument" depends="compile"> Hibernate 3. Please note that this is mostly a marketing feature... Using subselect fetching If one lazy collection or single-valued proxy has to be fetched.7 187 . 5. ie. For bytecode instrumentation. To enable lazy property loading. when legacy tables have hundreds of columns and the data model can not be improved. Using lazy property fetching Hibernate3 supports the lazy fetching of individual properties. optimizing row reads is much more important than optimization of column reads.. Hi- bernate can pre-fetch collections: <class name="Person"> <set name="cats" batch-size="3"> . (Although a nested set or a materialized path might be a better option for read-mostly trees. only loading some properties of a class might be useful in extreme cases. lazy="true". Hibernate will load 3.</class> Hibernate will now execute only three queries. to retrieve the proxied owners. 1 collections in four SELECTs. Again. if each Person has a lazy collection of Cats. If you enable batch fetching for the cats collection in the mapping of Person. Batch fetching of collections is particularly useful if you have a nested tree of items. re-running the ori- ginal query in a subselect. 10. Improving performance You have 25 Cat instances loaded in a Session. without the piecemeal loading. the typical bill- of-materials pattern. Hibernate will silently ignore lazy property settings and fall back to immediate fetching. as in practice. You can tune this beha- vior by specifying a batch-size in the mapping of Person: <class name="Person" batch-size="10">. 19. This works in the same way as batch-fetching. a Person. 3.) 19.1. You may also enable batch fetching of collections. each Cat has a reference to its owner. the pattern is 10. one for every call to getCats(). set the lazy attribute on your particular property mappings: <class name="Document"> <id name="id"> <generator class="native"/> </id> <property name="name" not-null="true" length="50"/> <property name="summary" not-null="true" length="200" lazy="true"/> <property name="text" not-null="true" length="2000" lazy="true"/> </class> Lazy property loading requires buildtime bytecode instrumentation! If your persistent classes are not enhanced. Hibernate loads all of them. iterating through all persons will generate 10 SELECTs.7. Hibernate will by default execute 25 SELECT statements.

hibernate.OSCacheProvider memory. The Second Level Cache A Hibernate Session is a transaction-level cache of persistent data.cache.) transactional Hibernate 3.2.1.hibernate.class. It is possible to configure a cluster or JVM- level (SessionFactory-level) cache on a class-by-class and collection-by-collection basis.instrument.2.hibernate. you could implement your own and plug it in as out- lined above.2. Caches are never aware of changes made to the persistent store by another ap- plication (though they may be configured to regularly expire cached data).cache.path"/> </taskdef> <instrument verbose="true"> <fileset dir="${testclasses.HashtableCacheProv memory yes (not intended ider for produc- tion use) EHCache org. disk yes SwarmCache org.hibernate. Improving performance <taskdef name="instrument" classname="org.dir}/org/hibernate/auction/model"> <include name="*.hibernate. that is no longer the case as of 3. (replication) sync req. Table 19.cache.class"/> </fileset> </instrument> </target> A different (better?) way to avoid unnecessary column reads.cache.provider_class. additionally.path}"/> <classpath path="${classes.dir}"/> <classpath refid="lib. You may even plug in a clustered cache. at least for read-only transactions is to use the projection features of HQL or Criteria queries.hibernate.TreeCacheProvider clustered (ip yes yes (clock TreeCache multicast).CacheProvider using the property hibernate.EhCacheProvider memory.7 188 .tool. 19. disk yes OSCache org.hibernate. Cache Providers Cache Provider class Type Cluster Safe Query Cache Supported Hashtable org. You may force the usual eager fetching of properties using fetch all properties in HQL.InstrumentTask"> <classpath path="${jar.cache. You have the option to tell Hibernate which caching implementation to use by specifying the name of a class that implements org.cache. Hibernate comes bundled with a number of built-in integrations with open-source cache providers (listed below).SwarmCacheProvider clustered (ip yes (clustered multicast) invalidation) JBoss org.cache. Be careful.2 defaulted to use EhCache as the default cache provider. Note that versions prior to 3. This avoids the need for buildtime bytecode processing and is certainly a prefered solution.

... If the cache is used in a JTA environment.1.2. <class name="eg. you should ensure that the transaction is completed when Session.... If the cache is used in a JTA environment. <class name="eg. a read-only cache may be used. The built-in cache providers do not.. you must specify the property hibernate. Strategy: read/write If the application needs to update data.close() or Session. you should ensure that the underlying cache implementation supports locking.3.2. This is the simplest and best performing strategy.transaction.disconnect() is called. if it is extremely unlikely that two transactions would try to update the same item simultaneously) and strict transaction isolation is not required..2. a read-write cache might be appropriate.cfg.. Strategy: nonstrict read/write If the application only occasionally needs to update data (ie. > <cache usage="read-write"/> . nonstrict-read-write or read-only (2) region (optional.Immutable" mutable="false"> <cache usage="read-only"/> . This cache strategy should never be used if serializable transaction isolation level is required. Improving performance 19.2...xml. It's even perfectly safe for use in a cluster.2. In other environments. </set> </class> 19.manager_lookup_class. 19.2. The usage attribute specifies a cache concurrency strategy. naming a strategy for obtain- ing the JTA TransactionManager. defaults to all) non-lazy specifies that properties of the entity mapped with lazy="true" may not be cached when attribute-level lazy fetching is enabled Alternatively (preferrably?). </class> 19. Strategy: read only If your application needs to read but never modify instances of a persistent class..Cat" . a nonstrict- read-write cache might be appropriate. If you wish to use this strategy in a cluster. you may specify <class-cache> and <collection-cache> elements in hibern- ate. Cache mappings The <cache> element of a class or collection mapping has the following form: <cache usage="transactional|read-write|nonstrict-read-write|read-only" (1) region="RegionName" (2) include="all|non-lazy" (3) /> (1) usage (required) specifies the caching strategy: transactional. defaults to the class or collection role name) specifies the name of the second level cache region (3) include (optional.7 189 . > <cache usage="read-write"/> .4. read-write.. you must specify hibern- Hibernate 3. <set name="kittens" ..

2. Improving performance ate.2.2. To completely evict all objects from the session cache. the evict() method may be used to remove the object and its collections from the first- level cache.5.next() ) { Cat cat = (Cat) cats. entire class. there are methods defined on SessionFactory for evicting the cached state of an instance. read-write transactional read-write Hashtable (not in.get(0).7 190 .manager_lookup_class.transaction. //evict a particular Cat sessionFactory.evict(cat). None of the cache providers support all of the cache concurrency strategies. call Session. you should ensure that the transaction is completed when Session. sess. Strategy: transactional The transactional cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. ScrollableResult cats = sess.close() or Session. //a huge result set while ( cats. that object is added to the internal cache of the Session. The following table shows which providers are compatible with which concurrency strategies. catId). In other environments. iterate() or scroll(). update() or saveOrUpdate() and whenever you retrieve an object us- ing load().3. yes yes yes tended for produc- tion use) EHCache yes yes yes OSCache yes yes yes SwarmCache yes yes JBoss TreeCache yes yes 19.createQuery("from Cat as cat"). When flush() is subsequently called. } The Session also provides a contains() method to determine if an instance belongs to the session cache.manager_lookup_class. sessionFactory. If you do not want this synchronization to occur or if you are processing a huge number of objects and need to manage memory efficiently.class). Table 19. //evict all Cats Hibernate 3. get(). Such a cache may only be used in a JTA environment and you must specify hibern- ate. doSomethingWithACat(cat). 19.clear() For the second-level cache.disconnect() is called. Cache Concurrency Strategy Support Cache read-only nonstrict. list().scroll().evict(Cat.evict(Cat. Managing the caches Whenever you pass an object to save(). collection instance or entire collection role. the state of that object will be synchronized with the database.transaction.class.

but don't write to the second-level cache except when updating data • CacheMode.use_structured_entries true 19.cache.4. optionally.evictCollection("Cat.setCacheRegion("frontpages") .getStatistics() . If you require fine-grained control over query cache expiration policies.StandardQueryCache). so by default queries are not cached.REFRESH . and.write items to the second-level cache.setMaxResults(15) . Hibernate 3. use the Statistics API: Map cacheEntries = sessionFactory. blogger) . To enable caching. Note that the query cache does not cache the state of the actual entities in the result set.list(). List blogs = sess.UpdateTimestampsCache).kittens".setEntity("blogger". The Query Cache Query result sets may also be cached.kittens").one holding cached query result sets (org.createQuery("from Blog blog where blog. You'll need to enable statistics. //evict a particular collection of kittens sessionFactory.use_minimal_puts. • CacheMode. but don't read from the second-level cache • CacheMode. This call allows the query to look for existing cache results or add its results to the cache when it is executed.cache.PUT .evictCollection("Cat.generate_statistics true hibernate.getSecondLevelCacheStatistics(regionName) .cache.cache. forcing a refresh of the second-level cache for all items read from the database To browse the contents of a second-level or query cache region.blogger = :blogger") .read items from and write items to the second-level cache • CacheMode. This is only useful for queries that are run frequently with the same para- meters.setCacheable(true).read items from the second-level cache.hibernate.GET .hibernate.setCacheRegion().2.7 191 . the other holding timestamps of the most recent updates to queryable tables (org.write items to the second-level cache.use_query_cache true This setting causes the creation of two new cache regions . To use the query cache you must first enable it: hibernate. but don't read from the second-level cache. by- pass the effect of hibernate. call Query. it caches only identifier values and results of value type. catId). Most queries do not benefit from caching. //evict all kitten collections The CacheMode controls how a particular session interacts with the second-level cache. you may specify a named cache region for a particular query by calling Query. So the query cache should always be used in conjunction with the second-level cache.cache.getEntries(). force Hibernate to keep the cache entries in a more human- understandable format: hibernate.NORMAL . Improving performance sessionFactory.setCacheable(true) .

On the other hand. Bags are the worst case.. (Side-note: if you want SchemaExport to actually create the primary key of a <set> for you. Since a bag permits duplicate element values and has no index column. Understanding Collection performance We've already spent quite some time talking about collections. for one to many or many to many associ- ations. particularly composite elements or large text or binary fields. they are the best case. 19. we must also consider the structure of the primary key that is used by Hibernate to up- date or delete collection rows. This is a more efficient alternative to eviction of a query cache region via SessionFactory. Hibernate has no way of distinguishing between duplicate rows. Hibernate 3.5. arrays) have a primary key consisting of the <key> and <index> columns.2. Improving performance If the query should force a refresh of its query cache region. so they are always very efficient to update. not modified through Hibernate) and allows the application to selectively refresh particular query result sets.e. In this case collection updates are usually extremely efficient . This suggests the following classification: • indexed collections • sets • bags All indexed collections (maps. In this section we will highlight a couple more issues about how collections behave at runtime. no primary key may be defined. 19.1. Sets have a primary key consisting of <key> and element columns.the primary key may be efficiently indexed and a particular row may be efficiently located when Hibernate tries to update or delete it.REFRESH).setCacheMode(CacheMode.evictQueries(). Taxonomy Hibernate defines three basic kinds of collections: • collections of values • one to many associations • many to many associations This classification distinguishes the various table and foreign key relationships but does not tell us quite everything we need to know about the relational model. particularly in the case of synthetic identifiers. This might be very inefficient. To fully understand the relational structure and per- formance characteristics. This may be less efficient for some types of collection element.5.7 192 . you must declare all columns as not- null="true". This is particularly useful in cases where underlying data may have been updated via a separate process (i. lists. the database may not be able to index a complex primary key as efficently. In fact. it is likely to be just as efficient. Hibernate resolves this prob- lem by completely removing (in a single DELETE) and recreating the collection whenever it changes.) <idbag> mappings define a surrogate key. you should call Query.

2.add() or Collection. suppose that we remove eighteen elements. Child c = new Child(). Sets are expected to be the most common kind of collection in Hibernate applications. For these associations. Lists. //no need to fetch the collection! sess.2. one more advantage that indexed collections have over sets for many to many associations or collections of values.getChildren(). Once again. There are two possible ways to proceed • delete eighteen rows one by one and then insert three rows Hibernate 3. After observing that arrays cannot be lazy. Parent p = (Parent) sess. p. One shot delete Occasionally.7 193 .5. id). This can make the following common code much faster.4.setParent(p).load(Parent. Hibernate doesn't ever UPDATE a row when an ele- ment is "changed". 19. There is. Changes to a Set always work via INSERT and DELETE (of individual rows).add(c). the above classification is still useful. idbags and sets are the most efficient collections to up- date From the discussion above. This is because the "set" semantics are most natural in the relational mod- el.) 19. In this case. and so considerations of collection update performance simply do not apply. However. the update is handled by the many-to-one end of the association. in well-designed Hibernate domain models. leaving two and then add thee new elements.3.flush(). maps and idbags are the most perform- ant (non-inverse) collection types.class.5. Improving performance Note that for a one-to-many association. Hibernate will issue one INSERT statement and two DELETE statements (unless the collection is a bag). (It still reflects how Hibernate "locates" indi- vidual rows of the collection. maps. Because of the structure of a Set. we would conclude that lists. c. deleting collection elements one by one can be extremely inefficient.but even in this case. Hibernate will issue a single DELETE and we are done! Suppose we add a single element to a collection of size twenty and then remove two elements.addAll() must always return true for a bag or List (unlike a Set). However. for ex- ample). removing and updating elements. so it knows not to do that in the case of an newly-empty collection (if you called list.clear(). there is a particular case in which bags (and also lists) are much more per- formant than sets. Bags and lists are the most efficient inverse collections Just before you ditch bags forever. For a collection with inverse="true" (the standard bidirectional one-to-many relationship idiom. This is certainly desir- able. with sets not far behind. arguably. Hibernate isn't completely stupid. for example) we can add elements to a bag or list without needing to initialize (fetch) the bag elements! This is because Collection. this consideration does not apply to one to many associations. we usually see that most collections are in fact one- to-many associations with inverse="true".5. 19. the "primary key" may not be the physical primary key of the database table . it should be clear that indexed collections and (usually) sets allow the most efficient operation in terms of adding.

setStatisticsEnabled(true) Hibernate 3. on).put("sessionFactory". You may enable a single MBean for all your SessionFactory or one per factory. "statistics"). In the second one.put("type". Monitoring a SessionFactory You can access SessionFactory metrics in two ways.generate_statistics to false • at runtime: sf. // Register the Mbean on the server // MBean service registration for all SessionFactory's Hashtable tb = new Hashtable().setSessionFactory(sessionFactory). Hibernate can also use JMX to publish metrics if you enable the StatisticsService MBean. Improving performance • remove the whole collection (in one SQL DELETE) and insert all five current elements (one by one) Hibernate isn't smart enough to know that the second option is probably quicker in this case. // MBean object name StatisticsService stats = new StatisticsService(). ObjectName on = new ObjectName("hibernate". set hibernate.put("sessionFactory". // Bind the stats to a SessionFactory server.registerMBean(stats.6.6. See the following code for minimalistic con- figuration examples: // MBean service registration for a specific SessionFactory Hashtable tb = new Hashtable().setStatisticsEnabled(true) or hibernateStats- Bean.getStatistics() and read or display the Statistics yourself. 19.1. tb. tb).registerMBean(stats. Of course.7 194 . such behaviour might confuse database triggers. Monitoring performance Optimization is not much use without monitoring and access to performance numbers. 19. // MBean implementation server. "myFinancialApp").) Fortunately. tb). we retrieve and use the MBean directly. one-shot-delete does not apply to collections mapped inverse="true".2. tb. This can be very useful and powerful from time to time. Hibernate provides a full range of figures about its internal operations. "statistics"). // MBean implementation stats. you can force this behaviour (ie. Statistics in Hibernate are available per SessionFactory. "all"). (And it would probably be undesirable for Hibernate to be that smart. we must give the JNDI name in which the session factory is held before using it. // Register the MBean on the server TODO: This doesn't make sense: In the first case.put("type".setSessionFactoryJNDIName("my/JNDI/Name") You can (de)activate the monitoring for a SessionFactory • at configuration time. etc. the second strategy) at any time by discarding (ie. on). tb. // MBean object name StatisticsService stats = new StatisticsService(). Use hibernateStats- Bean.getStatistics(). ObjectName on = new ObjectName("hibernate". dereferencing) the original collection and returning a newly instantiated collection with all the current elements. tb. Your first option is to call sessionFact- ory.

sessionFactory. Metrics Hibernate provides a number of metrics. Beware that the number of milliseconds is subject to approximation in Java. query or cache region.getStatistics(). and put ratio of entities. in three categories: • Metrics related to the general Session usage. etc. getCol- lectionRoleNames().2.class. A summary can be sent to a logger (info level) using the logSummary() method. collections and queries.getName() + " changed " + changes + "times" ). etc. and QueryStatistics API Javadoc for more information. log. and the aver- age time a query needs. The fol- lowing code shows a simple example: Statistics stats = HibernateUtil. and getSecondLevelCacheRegionNames(). such as number of open sessions. double queryCacheHitCount = stats.info("Query Hit ratio:" + queryCacheHitRatio). double queryCacheHitRatio = queryCacheHitCount / (queryCacheHitCount + queryCacheMissCount). collections.getQueryCacheHitCount(). miss.getName() ). queries and region caches. from very basic to the specialized information only relevant in certain scenarios.2. For exampl.class. EntityStatistics entityStats = stats. getEntityNames(). 19. Hibernate 3.6. All available counters are described in the Statistics interface API.e you can check the cache hit. queries and region caches with the following methods: getQueries(). Simple getters are used to access the global metrics (i. Improving performance Statistics can be reset programatically using the clear() method. and caches as a whole (aka global metrics). retrieved JDBC connec- tions.getUpdateCount() + entityStats.7 195 . long changes = entityStats. You can access the metrics of a particular entity. EntityStatistics. not tied to a particular entity.). queries. on some platforms this might even only be accurate to 10 seconds.getQueryCacheMissCount(). • Detailed metrics related to a particular entity. CollectionS- tatistics.info(Cat. you can retrieve the list of names of entities. collection or cache region through its name.getInsertCount() + entityStats. cache region. SecondLevelCacheStatistics.e. double queryCacheMissCount = stats. Please refer to the Statistics. and through its HQL or SQL representation for queries. To work on all entities. • Metrics related to he entities. collection. col- lections. log. collection. Hibernate is tied to the JVM precision. collections.getDeleteCount().getEntityStatistics( Cat.

• Ant Tasks: Please refer to the Hibernate Tools package and it's documentation for more information. Automatic schema generation DDL may be generated from your mapping files by a Hibernate utility. 20. the Hibernate main package comes bundled with an integrated tool (it can even be used from "inside" Hibernate on-the-fly): SchemaExport aka hbm2ddl. you can use a wizard to quickly generate Hibernate configuration (cfg. You may set the length.1. commandline tools. It also supports semantic auto-completion for class names and property/field names. The console allows you to execute HQL queries against your database and browse the result directly in Eclipse. • Development Wizards: Several wizards are provided with the Hibernate Eclipse tools. Tables and sequences are also created for mapped identifier generators.2. as well as Ant tasks. supporting auto-completion and syntax high- lighting. 20. you also get an interactive view of your persistent classes and their relationships. or you may even completely reverse engineer an existing database schema into POJO source files and Hibernate mapping files. as DDL is highly vendor specific. customize your mapping files to improve the generated schema.1. However. precision and scale.dialect property when using this tool. Customizing the schema Many Hibernate mapping elements define optional attributes named length. First. <many-to-one name="bar" column="barId" not-null="true"/> Hibernate 3. The generated schema includes referen- tial integrity constraints (primary and foreign keys) for entity and collection tables. Toolset Guide Roundtrip engineering with Hibernate is possible using a set of Eclipse plugins. making it much more versatile than a normal XML editor. You must specify a SQL Dialect via the hibernate. The reverse engineering wizard supports customizable templates. • Console: The console is a new view in Eclipse. precision and scale of a column with this attribute.1.xml) files.7 196 . <property name="zip" length="5"/> <property name="balance" precision="12" scale="2"/> Some tags also accept a not-null attribute (for generating a NOT NULL constraint on table columns) and a unique attribute (for generating UNIQUE constraint on table columns). In addition to a tree overview of your console configura- tions. The Hibernate Tools currently include plugins for the Eclipse IDE as well as Ant tasks for reverse engineering of existing databases: • Mapping Editor: An editor for Hibernate XML mapping files.Chapter 20.

<property name="credits" type="integer" insert="false"> <column name="credits" default="10"/> </property> <version name="version" type="integer" insert="false"> <column name="version" default="0"/> </property> The sql-type attribute allows the user to override the default mapping of a Hibernate type to SQL datatype. Summary Hibernate 3. Toolset Guide <element column="serialNumber" type="long" not-null="true" unique="true"/> A unique-key attribute may be used to group columns in a single unique key constraint...Name"/> <column name="last" not-null="true" index="bar_idx" length="30"/> <column name="first" not-null="true" index="bar_idx" length="20"/> <column name="initial"/> </property> The default attribute lets you specify a default value for a column (you should assign the same value to the mapped property before saving a new instance of the mapped class).2. only to group the columns in the mapping file. Currently. <property name="foo" type="integer"> <column name="foo" check="foo > 10"/> </property> <class name="Foo" table="foos" check="bar < 100. simply by specifying the same index name. the spe- cified value of the unique-key attribute is not used to name the constraint in the generated DDL. <property name="balance" type="float"> <column name="balance" sql-type="decimal(13. <many-to-one name="bar" column="barId" foreign-key="FKFooBar"/> Many mapping elements also accept a child <column> element. <many-to-one name="org" column="orgId" unique-key="OrgEmployeeId"/> <property name="employeeId" unique-key="OrgEmployee"/> An index attribute specifies the name of an index that will be created using the mapped column or columns.7 197 .3)"/> </property> The check attribute allows you to specify a check constraint. This is particularly useful for mapping multi- column types: <property name="name" type="my.1. <property name="bar" type="float"/> </class> Table 20.customtypes.0"> . <property name="lastName" index="CustName"/> <property name="firstName" index="CustName"/> A foreign-key attribute may be used to override the name of any generated foreign key constraint. Multiple columns may be grouped into the same index.

2. <many-to-one>. 20. sql-type SQL column type overrides the default column type (attribute of <column> element only) default SQL expression specify a default value for the column check SQL expression create an SQL check constraint on either column or table The <comment> element allows you to specify comments for the generated schema.7 198 .. Running the tool The SchemaExport tool writes a DDL script to standard out and/or executes the DDL statements.hibernate. <key>.hbm2ddl. or <many-to-many> mapping element. for a <one-to-one>. SchemaExport Command Line Options Option Description --quiet don't output the script to stdout --drop only drop the tables --create only create the tables Hibernate 3.tool.1. Note that in- verse="true" sides will not be considered by SchemaEx- port.2. </class> <property name="balance"> <column name="bal"> <comment>Balance in USD</comment> </column> </property> This results in a comment on table or comment on column statement in the generated DDL (where supported)..SchemaExport options mapping_files Table 20.2. java -cp hibernate_classpaths org. Toolset Guide Attribute Values Interpretation length number column length precision number column decimal precision scale number column decimal scale not-null true|false specfies that the column should be non-nullable unique true|false specifies that the column should have a unique constraint index index_name specifies the name of a (multi-column) index unique-key unique_key_name specifies the name of a multi-column unique constraint foreign-key foreign_key_name specifies the name of the foreign key constraint generated for an association. <class name="Customer" table="CurCust"> <comment>Current customers only</comment> .

connection.7 199 .3.properties read database properties from a file --format format the generated SQL nicely in the script --delimiter=.driver_class jdbc driver class hibernate.hbm2ddl.MyNamingStrategy select a NamingStrategy --config=hibernate. true).ddl output the ddl script to a file --naming=eg.path"/> <schemaexport properties="hibernate.username database user hibernate. 20.password user password hibernate.connection.4..tool.xml read Hibernate configuration from an XML file --properties=hibernate.3.hibernate. Using Ant You can call SchemaExport from your Ant build script: <target name="schemaexport"> <taskdef name="schemaexport" classname="org. SchemaExport Connection Properties Property Name Description hibernate. Properties Database properties may be specified • as system properties with -D<property> • in hibernate.cfg.properties" quiet="no" text="no" Hibernate 3.url jdbc url hibernate.create(false.2.properties • in a named properties file with --properties The needed properties are: Table 20.connection....SchemaExportTask" classpathref="class.1.1.connection. new SchemaExport(cfg). set an end of line delimiter for the script You may even embed SchemaExport in your application: Configuration cfg = .dialect dialect 20. Toolset Guide Option Description --text don't export to the database --output=my_schema.

7 200 .hibernate.MyNamingStrategy select a NamingStrategy --properties=hibernate.hbm2ddl. Toolset Guide drop="no" delimiter=".cfg.SchemaUpdate options mapping_files Table 20. SchemaUpdate Command Line Options Option Description --quiet don't output the script to stdout --text don't export the script to the database --naming=eg. so it will not work with all JDBC Hibernate 3.7.1..SchemaUpdateTask" classpathref="class. new SchemaUpdate(cfg).properties" quiet="no"> <fileset dir="src"> <include name="**/*.hibernate.xml file You may embed SchemaUpdate in your application: Configuration cfg = .tool.1." output="schema-export. Schema validation The SchemaValidator tool will validate that the existing database schema "matches" your mapping documents. java -cp hibernate_classpaths org.4.xml specify a .cfg.6.5. Using Ant for incremental schema updates You can call SchemaUpdate from the Ant script: <target name="schemaupdate"> <taskdef name="schemaupdate" classname="org.path"/> <schemaupdate properties="hibernate.2.hbm.1.hbm2ddl.. Note that SchemaValidator depends heavily upon the JDBC metadata API..hbm.tool.xml"/> </fileset> </schemaupdate> </target> 20.execute(false). 20. Incremental schema updates The SchemaUpdate tool will update an existing schema with "incremental" changes.. Note that SchemaUpdate depends heavily upon the JDBC metadata API.properties read database properties from a file --config=hibernate.sql"> <fileset dir="src"> <include name="**/*.xml"/> </fileset> </schemaexport> </target> 20. so it will not work with all JDBC drivers.

MyNamingStrategy select a NamingStrategy --properties=hibernate..properties"> <fileset dir="src"> <include name="**/*.properties read database properties from a file --config=hibernate.tool. Using Ant for schema validation You can call SchemaValidator from the Ant script: <target name="schemavalidate"> <taskdef name="schemavalidator" classname="org. This tool is extremely useful for testing..hibernate.path"/> <schemavalidator properties="hibernate.validate().hbm2ddl.1. 20.SchemaValidator options mapping_files Table 20.7 201 .. new SchemaValidator(cfg).hbm.cfg..hibernate.xml file You may embed SchemaValidator in your application: Configuration cfg = .xml specify a . SchemaValidator Command Line Options Option Description --naming=eg.8.2. java -cp hibernate_classpaths org.xml"/> </fileset> </schemaupdate> </target> Hibernate 3.tool.SchemaValidatorTask" classpathref="class.cfg.hbm2ddl.5. Toolset Guide drivers.

7 202 . 21. Likewise.flush(). never of the contained entities. session. This behaviour is completely consistent .. p. A note about collections Hibernate collections are considered to be a logical part of their owning entity.add(c). Example: Parent/Child One of the very first things that new users try to do with Hibernate is to model a parent / child type relationship.a change to the internal state of another entity should not cause the associated entity to vanish! Likewise. by default.2.save(c). where the life of the child is bound to the lifecycle of the parent. Bidirectional one-to-many Suppose we start with a simple <one-to-many> association from Parent to Child. This is a crucial distinction! It has the following consequences: • When we remove / add an object from / to a collection.. a composite element). Where it is not appro- priate at all is the case of a parent / child relationship. session.. For various reasons the most convenient approach. that object will cease to be persistent and its state will be completely removed from the database. while removing it removes the link.. Child c = new Child(). (The alternative approach is to declare the Child as a <composite-element>. by default. It's not at all difficult! 21.2. it will not be deleted. especially for new users. There are two different approaches to this. We will explain how to use a bidirec- tional one to many association with cascades to model a parent / child relationship efficiently and elegantly. the default behaviour is that adding an entity to a collection merely creates a link between the two en- tities. the version number of the collection owner is incre- mented. <set name="children"> <key column="parent_id"/> <one-to-many class="Child"/> </set> If we were to execute the following code Parent p = .1. it turns out that default semantics of a one to many association (in Hibernate) are much less close to the usual semantics of a parent / child relationship than those of a composite element mapping.getChildren(). adding an entity to a collection does not cause that entity to become persistent. This is very appropriate for all sorts of cases.Chapter 21. • On the other hand.. if an entity is removed from a collection (a one-to-many or many-to-many association). adding a value type instance to the collection will cause its state to be immediately persistent.) Now. Hibernate would issue two SQL statements: Hibernate 3. • If an object that was removed from a collection is an instance of a value type (eg. Instead. is to model both Parent and Child as entity classes with a <one-to-many> association from Parent to Child.

So the solution is to make the link part of the Child mapping.save(c). public void addChild(Child c) { c. p. We can fix the nullability constraint violation by specifying not-null="true" in the collection mapping: <set name="children"> <key column="parent_id" not-null="true"/> <one-to-many class="Child"/> </set> However. we tell the collection not to update the link. The underlying cause of this behaviour is that the link (the foreign key parent_id) from p to c is not considered part of the state of the Child object and is therefore not created in the INSERT.load(Parent.addChild(c).class. only one SQL INSERT would be issued! To tighten things up a bit. children.add(c).7 203 . but also violates any NOT NULL constraint on the parent_id column. <many-to-one name="parent" column="parent_id" not-null="true"/> (We also need to add the parent property to the Child class. And now.2. we could create an addChild() method of Parent. pid). the code to add a Child looks like Parent p = (Parent) session. Child c = new Child().save(c).flush().flush().add(c). Cascading lifecycle Hibernate 3. We use the inverse attribute.class.setParent(this). } Now. Child c = new Child(). c.getChildren().load(Parent.3. session. Example: Parent/Child • an INSERT to create the record for c • an UPDATE to create the link from p to c This is not only inefficient. 21. session. pid). p. this is not the recommended solution.setParent(p).) Now that the Child entity is managing the state of the link. session. session. <set name="children" inverse="true"> <key column="parent_id"/> <one-to-many class="Child"/> </set> The following code would be used to add a new Child Parent p = (Parent) session.

cascades are still processed by iterating the collection elements.load(Parent.next(). We will address this by using cascades.4. Child c = (Child) p.delete(c). It is not enough to simply call setParent().class. The Parent will contain a collection of childen and. Example: Parent/Child The explicit call to save() is still annoying. p. Now.class. session.setParent(null).flush(). in this case). Child c = (Child) p. we really do want it to be deleted. session.iterator(). since cas- cading update is enabled.2. in our case. c. session. we must use cascade="all-delete-orphan". For this. session.remove(c). Parent p = (Parent) session.next(). Child c = new Child().flush(). will not remove c from the database.getChildren().getChildren().load(Parent. session.getChildren(). you must add it to the collection. made some changes in a UI action and wish to persist these changes in a new session by calling update(). Similarly. The following removes p and all its children from the database. <set name="children" inverse="true" cascade="all"> <key column="parent_id"/> <one-to-many class="Child"/> </set> This simplifies the code above to Parent p = (Parent) session. 21. session. this code Parent p = (Parent) session.delete(p).7 204 . it will ony remove the link to p (and cause a NOT NULL constraint viola- tion.flush(). <set name="children" inverse="true" cascade="all-delete-orphan"> <key column="parent_id"/> <one-to-many class="Child"/> </set> Note: even though the collection mapping specifies inverse="true". However. pid). pid). So if you require that an object be saved. p. Parent p = (Parent) session. Cascades and unsaved-value Suppose we loaded up a Parent in one Session.iterator().addChild(c). Hibernate needs to know which children are newly instantiated and which represent existing rows in the database. a Child can't really exist without its parent. p. pid).class. Hibernate will use the identifier and version/timestamp property value to determine which of the Hibernate 3.getChildren().flush().load(Parent. So if we remove a Child from the collection.load(Parent.class. we don't need to iterate over the children when saving or deleting a Parent. You need to explicitly delete() the Child. deleted or updated by cascade. pid). Lets assume that both Parent and Child have genenerated identifier properties of type Long.remove(c).

5. it is no longer necessary to specify an unsaved-value explicitly. 21. Hibernate 3. The following code will update parent and child and insert newChild. Hibernate will either use the timestamp or version property. which have exactly the semantics of a parent / child relationship. that's all very well for the case of a generated identifier. Child newChild = new Child(). None of the above issues exist in the case of <composite-element> mappings. parent. there are two big limitations to composite element classes: composite elements may not own collections. //parent and child were both loaded in a previous session parent.) In Hibernate3.addChild(child). Unfortu- nately. session.flush().7 205 . session. or will actually query the second-level cache or. to see if the row exists. Example: Parent/Child children are new. it all works out very nicely. in practice. the database. and they should not be the child of any entity other than the unique parent. However.2.7. Conclusion There is quite a bit to digest here and it might look confusing first time around.update(parent). Most Hibernate applications use the parent / child pattern in many places. We mentioned an alternative in the first paragraph. “Automatic state detection”. but what about assigned identifiers and compos- ite identifiers? This is more difficult. In this case. worst case. (See Section 10.addChild(newChild). Well. since Hibernate can't use the identifier property to distinguish between a newly instantiated object (with an identifier assigned by the user) and an object loaded in a previous session.

} public String getText() { return _text.2. public class BlogItem { private Long _id. They are to be modelled as a stand- ard parent/child relationship. but we will use an ordered bag.1. private String _name.text. Hibernate 3. public class Blog { private Long _id.Chapter 22. } public void setBlog(Blog blog) { _blog = blog. } public String getName() { return _name. Persistent Classes The persistent classes represent a weblog.List. import java. import java. private Blog _blog. } public void setId(Long long1) { _id = long1. and an item posted in a weblog. private Calendar _datetime. } public Calendar getDatetime() { return _datetime. } public void setName(String string) { _name = string. } public List getItems() { return _items.Calendar.7 206 . } public String getTitle() { return _title. } public void setItems(List list) { _items = list.DateFormat. public Long getId() { return _id. private String _text. private String _title. package eg. } } package eg. public Blog getBlog() { return _blog. private List _items. instead of a set.util. } public Long getId() { return _id.util. Example: Weblog Application 22. import java.

} public void setTitle(String string) { _title = string.2.sourceforge. } } 22.0//EN" "http://hibernate.7 207 . <?xml version="1.net/hibernate-mapping-3.0//EN" "http://hibernate.0.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3. Hibernate Mappings The XML mappings should now be quite straightforward. Example: Weblog Application } public void setDatetime(Calendar calendar) { _datetime = calendar.dtd"> <hibernate-mapping package="eg"> Hibernate 3.0. } public void setId(Long long1) { _id = long1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.2.dtd"> <hibernate-mapping package="eg"> <class name="Blog" table="BLOGS"> <id name="id" column="BLOG_ID"> <generator class="native"/> </id> <property name="name" column="NAME" not-null="true" unique="true"/> <bag name="items" inverse="true" order-by="DATE_TIME" cascade="all"> <key column="BLOG_ID"/> <one-to-many class="BlogItem"/> </bag> </class> </hibernate-mapping> <?xml version="1.sourceforge. } public void setText(String string) { _text = string.net/hibernate-mapping-3.

util.Session. Hibernate Code The following class demonstrates some of the kinds of things we can do with these classes. import org. import org.hibernate.7 208 . public class BlogMain { private SessionFactory _sessions.hibernate.util.Iterator.List. import java.class) .hibernate.tool. import java.addClass(BlogItem.Transaction.hibernate.class) .Calendar.util.SessionFactory. import org.buildSessionFactory().util. import java.hibernate.Configuration.Query.addClass(Blog. } Hibernate 3. public void configure() throws HibernateException { _sessions = new Configuration() .ArrayList. package eg.hibernate. import org.hibernate. import org.2. import org.cfg.hbm2ddl. Example: Weblog Application <class name="BlogItem" table="BLOG_ITEMS" dynamic-update="true"> <id name="id" column="BLOG_ITEM_ID"> <generator class="native"/> </id> <property name="title" column="TITLE" not-null="true"/> <property name="text" column="TEXT" not-null="true"/> <property name="datetime" column="DATE_TIME" not-null="true"/> <many-to-one name="blog" column="BLOG_ID" not-null="true"/> </class> </hibernate-mapping> 22.3.HibernateException. import java. using Hibernate. import org.SchemaExport.

setTitle(title).add(item). Session session = _sessions. } return item.commit(). Transaction tx = null.openSession(). try { tx = session. } finally { session.getInstance() ).close().beginTransaction().rollback().setText(text). } catch (HibernateException he) { if (tx!=null) tx.class. item. Session session = _sessions.addClass(BlogItem.close(). } return blog. tx. Session session = _sessions.setBlog(blog).7 209 .class). throw he. item. item.openSession().setBlog(blog).update(blog). true).rollback(). } public Blog createBlog(String name) throws HibernateException { Blog blog = new Blog(). String text) throws HibernateException { BlogItem item = new BlogItem(). String title. item. Example: Weblog Application public void exportTables() throws HibernateException { Configuration cfg = new Configuration() .beginTransaction(). Blog blog = (Blog) session. tx. new SchemaExport(cfg). blog.setName(name).create(true. String text) throws HibernateException { BlogItem item = new BlogItem().setDatetime( Calendar.beginTransaction(). blog. } public BlogItem createBlogItem(Blog blog. blogid). throw he. } catch (HibernateException he) { if (tx!=null) tx. session. try { tx = session.addClass(Blog. item. session.persist(blog). Hibernate 3. item. blog.getItems().setText(text). } finally { session. item. Transaction tx = null.commit().openSession(). Transaction tx = null.getInstance() ). try { tx = session.load(Blog. } public BlogItem createBlogItem(Long blogid. item.setTitle(title). String title.setDatetime( Calendar.2.setItems( new ArrayList() ).class) .

} } public void updateBlogItem(Long itemid.list(). Example: Weblog Application blog.id.rollback(). result = q. } finally { session.openSession().id " + "order by max(blogItem. item. q. blog. throw he. BlogItem item = (BlogItem) session.add(item).rollback().name.name.datetime)" ). } return item. tx. throw he. try { tx = session.commit(). } catch (HibernateException he) { if (tx!=null) tx. Session session = _sessions.2.setText(text). Hibernate 3. Transaction tx = null.close().7 210 .load(BlogItem. } catch (HibernateException he) { if (tx!=null) tx. } catch (HibernateException he) { if (tx!=null) tx.beginTransaction().close().createQuery( "select blog. Transaction tx = null. Query q = session. try { tx = session. String text) throws HibernateException { Session session = _sessions.openSession(). session. try { tx = session.update(item). count(blogItem) " + "from Blog as blog " + "left outer join blog.setMaxResults(max).commit(). itemid).beginTransaction(). Transaction tx = null. String text) throws HibernateException { item.openSession(). } public void updateBlogItem(BlogItem item.class.getItems().commit(). } finally { session. tx.close().beginTransaction(). tx. throw he. } finally { session. } } public List listAllBlogNamesAndItemCounts(int max) throws HibernateException { Session session = _sessions.rollback(). blog. List result = null.items as blogItem " + "group by blog.setText(text).

setParameter("blogid". tx. throw he. } catch (HibernateException he) { if (tx!=null) tx.commit().createQuery( "from Blog as blog " + "left outer join fetch blog.list().openSession(). cal).createQuery( "from Blog as blog " + "inner join blog. } return blog. q.close(). } return result. Query q = session. q. } catch (HibernateException he) { if (tx!=null) tx.beginTransaction(). throw he.id = :blogid" ). Transaction tx = null. throw he. } } Hibernate 3.7 211 . } finally { session. false).commit(). result = q.beginTransaction().uniqueResult(). Example: Weblog Application tx. } return result.openSession(). Calendar cal = Calendar.items as blogItem " + "where blogItem.commit(). } public Blog getBlogAndAllItems(Long blogid) throws HibernateException { Session session = _sessions.setCalendar("minDate".getInstance(). } finally { session. try { tx = session.MONTH. } public List listBlogsAndRecentItems() throws HibernateException { Session session = _sessions.rollback().rollback(). Blog blog = null. } catch (HibernateException he) { if (tx!=null) tx. blogid).close(). } finally { session. tx. Query q = session.rollback(). List result = null.items " + "where blog. blog = (Blog) q.datetime > :minDate" ).close().2. cal. Transaction tx = null.roll(Calendar. try { tx = session.

Example: Various Mappings This chapters shows off some more complex association mappings. 2)"/> </property> <property name="currency" length="12"/> </component> <many-to-one name="employer" column="employer_id" not-null="true"/> <many-to-one name="employee" column="employee_id" not-null="true"/> </class> <class name="Employee" table="employees"> <id name="id"> Hibernate 3.1. This is done because there might be more than one period of employment for the same two parties.2. Components are used to model monetary values and employee names. Heres a possible mapping document: <hibernate-mapping> <class name="Employer" table="employers"> <id name="id"> <generator class="sequence"> <param name="sequence">employer_id_seq</param> </generator> </id> <property name="name"/> </class> <class name="Employment" table="employment_periods"> <id name="id"> <generator class="sequence"> <param name="sequence">employment_id_seq</param> </generator> </id> <property name="startDate" column="start_date"/> <property name="endDate" column="end_date"/> <component name="hourlyRate" class="MonetaryAmount"> <property name="amount"> <column name="hourly_rate" sql-type="NUMERIC(12. Employer/Employee The following model of the relationship between Employer and Employee uses an actual entity class (Employ- ment) to represent the association.7 212 . 23.Chapter 23.

Author/Work Consider the following model of the relationships between Work.7 213 . firstName VARCHAR(255). Another possibility would be to have Author extend Person. start_date TIMESTAMP. Hibernate 3. employee_id BIGINT not null. Author and Person. We represent the relation- ship between Work and Author as a many-to-many association. primary key (id) ) create table employees ( id BIGINT not null.2. end_date TIMESTAMP. lastName VARCHAR(255). 2). initial CHAR(1). Example: Various Mappings <generator class="sequence"> <param name="sequence">employee_id_seq</param> </generator> </id> <property name="taxfileNumber"/> <component name="name" class="Name"> <property name="firstName"/> <property name="initial"/> <property name="lastName"/> </component> </class> </hibernate-mapping> And heres the table schema generated by SchemaExport. employer_id BIGINT not null. name VARCHAR(255). taxfileNumber VARCHAR(255). primary key (id) ) alter table employment_periods add constraint employment_periodsFK0 foreign key (employer_id) references employers alter table employment_periods add constraint employment_periodsFK1 foreign key (employee_id) references employees create sequence employee_id_seq create sequence employment_id_seq create sequence employer_id_seq 23. primary key (id) ) create table employment_periods ( id BIGINT not null. currency VARCHAR(12). hourly_rate NUMERIC(12. We choose to represent the relationship between Author and Person as one-to-one association. create table employers ( id BIGINT not null.2.

The Author must have the same identifier as the Person --> <generator class="assigned"/> </id> <property name="alias"/> <one-to-one name="person" constrained="true"/> <set name="works" table="author_work" inverse="true"> <key column="author_id"/> <many-to-many class="Work" column="work_id"/> </set> </class> Hibernate 3.7 214 .2. Example: Various Mappings The following mapping document correctly represents these relationships: <hibernate-mapping> <class name="Work" table="works" discriminator-value="W"> <id name="id" column="id"> <generator class="native"/> </id> <discriminator column="type" type="character"/> <property name="title"/> <set name="authors" table="author_work"> <key column name="work_id"/> <many-to-many class="Author" column name="author_id"/> </set> <subclass name="Book" discriminator-value="B"> <property name="text"/> </subclass> <subclass name="Song" discriminator-value="S"> <property name="tempo"/> <property name="genre"/> </subclass> </class> <class name="Author" table="authors"> <id name="id" column="id"> <!-.

create table works ( id BIGINT not null generated by default as identity. tempo FLOAT.3. works. Customer/Order/Product Now consider a model of the relationships between Customer.2. In Hibernate. author and person data respect- ively. author_id) ) create table authors ( id BIGINT not null generated by default as identity. authors and persons hold work. There is a one-to-many association between Customer and Order. primary key (id) ) create table author_work ( author_id BIGINT not null. primary key (work_id. primary key (id) ) alter table authors add constraint authorsFK0 foreign key (id) references persons alter table author_work add constraint author_workFK0 foreign key (author_id) references authors alter table author_work add constraint author_workFK1 foreign key (work_id) references works 23. primary key (id) ) create table persons ( id BIGINT not null generated by default as identity. author_work is an association table linking authors to works. this is called a composite element. alias VARCHAR(255). title VARCHAR(255). Example: Various Mappings <class name="Person" table="persons"> <id name="id" column="id"> <generator class="native"/> </id> <property name="name"/> </class> </hibernate-mapping> There are four tables in this mapping. Hibernate 3. type CHAR(1) not null.7 215 . but how should we represent Order / LineItem / Product? I've chosen to map LineItem as an association class representing the many-to-many association between Order and Product. as generated by SchemaExport. text INTEGER. Order and LineItem and Product. genre VARCHAR(255). name VARCHAR(255). Heres the table schema. work_id BIGINT not null.

primary key (id) ) create table orders ( id BIGINT not null generated by default as identity.2. orders. date TIMESTAMP. order line item and product data respect- ively. primary key (id) ) create table line_items ( line_number INTEGER not null. order. create table customers ( id BIGINT not null generated by default as identity. customer_id BIGINT. line_items also acts as an association table linking orders with products. name VARCHAR(255). Hibernate 3. Example: Various Mappings The mapping document: <hibernate-mapping> <class name="Customer" table="customers"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <set name="orders" inverse="true"> <key column="customer_id"/> <one-to-many class="Order"/> </set> </class> <class name="Order" table="orders"> <id name="id"> <generator class="native"/> </id> <property name="date"/> <many-to-one name="customer" column="customer_id"/> <list name="lineItems" table="line_items"> <key column="order_id"/> <list-index column="line_number"/> <composite-element class="LineItem"> <property name="quantity"/> <many-to-one name="product" column="product_id"/> </composite-element> </list> </class> <class name="Product" table="products"> <id name="id"> <generator class="native"/> </id> <property name="serialNumber"/> </class> </hibernate-mapping> customers. line_items and products hold customer.7 216 .

quantity INTEGER. line_number) ) create table products ( id BIGINT not null generated by default as identity. Miscellaneous example mappings These examples are all taken from the Hibernate test suite.4.1. primary key (order_id.4. Composite key example <class name="Customer"> <id name="customerId" length="10"> <generator class="assigned"/> Hibernate 3. You will find many other useful example mappings there. serialNumber VARCHAR(255). product_id BIGINT. Example: Various Mappings order_id BIGINT not null.7 217 .2. 'HOME'.4.2. TODO: put words around this stuff 23. 'BUSINESS')"> <composite-id> <key-many-to-one name="person" column="personName"/> <key-property name="type" column="addressType"/> </composite-id> <property name="street" type="text"/> <property name="state"/> <property name="zip"/> </class> 23. "Typed" one-to-one association <class name="Person"> <id name="name"/> <one-to-one name="address" cascade="all"> <formula>name</formula> <formula>'HOME'</formula> </one-to-one> <one-to-one name="mailingAddress" cascade="all"> <formula>name</formula> <formula>'MAILING'</formula> </one-to-one> </class> <class name="Address" batch-size="2" check="addressType in ('MAILING'. Look in the test folder of the Hibernate distribution. primary key (id) ) alter table orders add constraint ordersFK0 foreign key (customer_id) references customers alter table line_items add constraint line_itemsFK0 foreign key (product_id) references products alter table line_items add constraint line_itemsFK1 foreign key (order_id) references orders 23.

Product p where li.2.customerId = customerId and li.7 218 .quantity*p.orderNumber = orderNumber ) </formula> </property> <many-to-one name="customer" column="customerId" insert="false" update="false" not-null="true"/> <bag name="lineItems" fetch="join" inverse="true" cascade="save-update"> <key> <column name="customerId"/> <column name="orderNumber"/> </key> <one-to-many class="LineItem"/> </bag> </class> <class name="LineItem"> <composite-id name="id" class="LineItem$Id"> <key-property name="customerId" length="10"/> <key-property name="orderNumber"/> <key-property name="productId" length="10"/> </composite-id> <property name="quantity"/> <many-to-one name="order" insert="false" Hibernate 3.price) from LineItem li.productId and li.productId = p. Example: Various Mappings </id> <property name="name" not-null="true" length="100"/> <property name="address" not-null="true" length="200"/> <list name="orders" inverse="true" cascade="save-update"> <key column="customerId"/> <index column="orderNumber"/> <one-to-many class="Order"/> </list> </class> <class name="Order" table="CustomerOrder" lazy="true"> <synchronize table="LineItem"/> <synchronize table="Product"/> <composite-id name="id" class="Order$Id"> <key-property name="customerId" length="10"/> <key-property name="orderNumber"/> </composite-id> <property name="orderDate" type="calendar_date" not-null="true"/> <property name="total"> <formula> ( select sum(li.

quantity) from LineItem li where li. Many-to-many with shared composite key attribute <class name="User" table="`User`"> <composite-id> <key-property name="name"/> <key-property name="org"/> </composite-id> <set name="groups" table="UserGroup"> <key> <column name="userName"/> <column name="org"/> </key> <many-to-many class="Group"> <column name="groupName"/> <formula>org</formula> </many-to-many> </set> </class> <class name="Group" table="`Group`"> <composite-id> <key-property name="name"/> <key-property name="org"/> </composite-id> <property name="description"/> <set name="users" table="UserGroup" inverse="true"> <key> <column name="groupName"/> <column name="org"/> </key> Hibernate 3.7 219 .productId = productId ) </formula> </property> </class> 23.3.4. Example: Various Mappings update="false" not-null="true"> <column name="customerId"/> <column name="orderNumber"/> </many-to-one> <many-to-one name="product" insert="false" update="false" not-null="true" column="productId"/> </class> <class name="Product"> <synchronize table="LineItem"/> <id name="productId" length="10"> <generator class="assigned"/> </id> <property name="description" not-null="true" length="200"/> <property name="price" length="3"/> <property name="numberAvailable"/> <property name="numberOrdered"> <formula> ( select sum(li.2.

5. Example: Various Mappings <many-to-many class="User"> <column name="userName"/> <formula>org</formula> </many-to-many> </set> </class> 23. Content based discrimination <class name="Person" discriminator-value="P"> <id name="id" column="person_id" unsaved-value="0"> <generator class="native"/> </id> <discriminator type="character"> <formula> case when title is not null then 'E' when salesperson is not null then 'C' else 'P' end </formula> </discriminator> <property name="name" not-null="true" length="80"/> <property name="sex" not-null="true" update="false"/> <component name="address"> <property name="address"/> <property name="zip"/> <property name="country"/> </component> <subclass name="Employee" discriminator-value="E"> <property name="title" length="20"/> <property name="salary"/> <many-to-one name="manager"/> </subclass> <subclass name="Customer" discriminator-value="C"> <property name="comments"/> <many-to-one name="salesperson"/> </subclass> </class> 23. Associations on alternate keys <class name="Person"> <id name="id"> <generator class="hilo"/> Hibernate 3.4.2.4.4.7 220 .

Example: Various Mappings </id> <property name="name" length="100"/> <one-to-one name="address" property-ref="person" cascade="all" fetch="join"/> <set name="accounts" inverse="true"> <key column="userId" property-ref="userId"/> <one-to-many class="Account"/> </set> <property name="userId" length="8"/> </class> <class name="Address"> <id name="id"> <generator class="hilo"/> </id> <property name="address" length="300"/> <property name="zip" length="5"/> <property name="country" length="25"/> <many-to-one name="person" unique="true" not-null="true"/> </class> <class name="Account"> <id name="accountId" length="32"> <generator class="uuid"/> </id> <many-to-one name="user" column="userId" property-ref="userId"/> <property name="type" not-null="true"/> </class> Hibernate 3.7 221 .2.

Hibernate makes identifier properties optional. Don't use a single monolithic mapping document. consider providing your own implementation of org. That way you can still use the same transaction strategy and underlying connection provider. And don't assume that direct JDBC is necessarily faster. Use an Address class to encapsulate street. In a three tiered architecture. Externalising the query strings to mapping files will make the application more portable. Declare identifier properties on persistent classes. Suppose you have a Java type. This makes particularly good sense in a team environment. say from some library. Use hand-coded JDBC in bottlenecks.hibernate. state. Identify natural keys for all entities. This approach should be considered a last-resort. always replace non-constant values by "?".7 222 . Consider using a custom type.connection. This is a good practice if your queries call non-ANSI-standard SQL functions. We recommend that identifiers be 'synthetic' (generated. Load mappings as resources. This approach frees the application code from implementing transformations to / from a Hibernate type.xml. If you need to use direct JDBC. From time to time the Session synchronizes its persistent state with the database. In performance-critical areas of the system. Understand Session flushing. Don't manage your own JDBC connections. Implement equals() and hash- Code() to compare the properties that make up the natural key. You may sometimes minimize unnecessary flushing by disabling automatic flushing or even by changing the order of queries and other operations within a particular trans- action.ConnectionProvider.2. with no business meaning).hibernate. Performance will be af- fected if this process occurs too often.UserType. you could pass persistent objects loaded in the session Hibernate 3. and map them using <natural-id>. If you can't use the built-in connections providers. Place each class mapping in its own file. Hibernate lets the application manage JDBC connections. wait until you know something is a bottleneck. There are all sorts of reasons why you should use them. Map com. Identify natural keys. consider using named parameters in queries.Chapter 24. Best Practices Write fine-grained classes and map them using <component>. This encourages code reuse and simplifies refactoring. Deploy the mappings along with the classes they map.hbm. consider using detached objects. Consider externalising query strings.Foo in the file com/eg/Foo. Never use string manipulation to bind a non- constant value in a query! Even better. postcode.eg. When using a servlet / session bean architecture. You should consider implementing org. suburb. Use bind variables. it might be worth opening a Hibernate Session and using that JDBC connection. that needs to be persisted but doesn't provide the ac- cessors needed to map it as a component. But please. As in JDBC. some kinds of operations might benefit from direct JDBC.

Hide (Hibernate) data-access code behind an interface. In this case. Don't treat exceptions as recoverable. second. Hibernate 3. it is much better to use two one-to-many associations to an in- termediate link class. This is more of a necessary practice than a "best" practice. This is not a lim- itation of Hibernate! It is a fundamental requirement of safe transactional data access. they implicitly define an assembly phase where all data to be used by the view is fetched and marshalled into the DTOs before returning control to the presentation tier. you should be careful when using any other association style and ask yourself if it is really neccessary.saveOrUpdate() to synchronize objects with the database.merge() or Session. Use Session. consider using long persistence contexts. do not use Session. An application transaction might span several client request/response cycles. a single unit-of-work from the point of view of a user. An alternative. In a large application. Database Transactions have to be as short as possible for best scalability. is to maintain a single open persistence contact (session) for the whole lifecycle of the application transaction and simply disconnect from the JDBC connection at the end of each request and reconnect at the beginning of the subsequent request.get() or a query instead. When an join fetching is appropriate to a particular use case.load() to determine if an instance with the given identifier exists on the database. use a query with a left join fetch.2. they work around the problem that entity beans are not serializ- able. Prefer bidirectional associations. Most of the time you need additional inform- ation stored in the "link table". Use proxies and lazy collections for most associations to classes that are not likely to be completely held in the second-level cache. In a traditional EJB ar- chitecture. extremely appropriate in two tiered architec- ture. For associations to cached classes. DTOs serve dual purposes: first. In fact. When an exception occurs. Good usecases for a real many-to-many associations are rare. Consider abstracting your business logic from Hibernate. Combine the DAO and Thread Local Session pat- terns. It is common to use detached objects to implement application transactions. almost all associations must be navigable in both directions in queries. explicitly disable eager fetching using lazy="false". Prefer lazy fetching for associations. it is not appropriate for an application with five tables!) Don't use exotic association mappings. Hibernate can't guarantee that in-memory state accurately rep- resents persistent state. Best Practices bean to and from the servlet / JSP layer. However. we think that most associations are one-to-many and many-to-one. Use eager fetching sparingly. where there is an a extremely high probability of a cache hit. Unidirectional associations are more difficult to query. associated to Hibernate via a User- Type. In a two tiered architecture. Use a new session to service each request. you will still need an assembly phase (think of your business methods as having a strict contract with the presentation tier about what data is available in the detached objects) unless you are pre- pared to hold the persistence context (the session) open across the view rendering process.7 223 . Use the open session in view pattern. Never share a single session across more than one application transaction. You can even have some classes persisted by handcoded JDBC. As a special case of this. it is often neccessary to implement long running application transactions. (This advice is intended for "sufficiently large" applications. If you don't. use Session. or you will be working with stale data. roll back the Trans- action and close the Session. Hibernate frees the developer from writing tedious Data Transfer Objects (DTO). However. or a disciplined assembly phase to avoid problems with unfetched data. Hibernate eliminates the first purpose.