Working with both Object-Oriented software and Relational Databases can be cumbersome and time consuming. Development costs are significantly higher due to a paradigm mismatch between how data is represented in objects versus relational databases. Hibernate is an Object/ Relational Mapping solution for Java environments. The term Object/Relational Mapping refers to the technique of mapping data from an object model representation to a relational data model representation (and visa versa).

Comments 0

Document transcript

HIBERNATE - RelationalPersistence for Idiomatic Java1Hibernate ReferenceDocumentation3.6.3.Finalby Gavin King, Christian Bauer, Max Rydahl Andersen,Emmanuel Bernard, Steve Ebersole, and Hardy Ferentschikand thanks to James Cobb (Graphic Design) and Cheyenne Weaver (Graphic Design)iiiPreface ............................................................................................................................. xi1. Tutorial ........................................................................................................................ 11.1. Part 1 - The first Hibernate Application ................................................................ 11.1.1. Setup ...................................................................................................... 11.1.2. The first class .......................................................................................... 31.1.3. The mapping file ...................................................................................... 41.1.4. Hibernate configuration ............................................................................. 71.1.5. Building with Maven ................................................................................. 91.1.6. Startup and helpers .................................................................................. 91.1.7. Loading and storing objects .................................................................... 101.2. Part 2 - Mapping associations ........................................................................... 131.2.1. Mapping the Person class ...................................................................... 131.2.2. A unidirectional Set-based association ..................................................... 141.2.3. Working the association .......................................................................... 151.2.4. Collection of values ................................................................................ 171.2.5. Bi-directional associations ....................................................................... 191.2.6. Working bi-directional links ..................................................................... 191.3. Part 3 - The EventManager web application ....................................................... 201.3.1. Writing the basic servlet ......................................................................... 201.3.2. Processing and rendering ....................................................................... 221.3.3. Deploying and testing ............................................................................. 231.4. Summary .......................................................................................................... 242. Architecture ............................................................................................................... 252.1. Overview .......................................................................................................... 252.1.1. Minimal architecture ............................................................................... 252.1.2. Comprehensive architecture .................................................................... 262.1.3. Basic APIs ............................................................................................. 272.2. JMX Integration ................................................................................................ 282.3. Contextual sessions .......................................................................................... 283. Configuration ............................................................................................................. 313.1. Programmatic configuration ............................................................................... 313.2. Obtaining a SessionFactory ............................................................................... 323.3. JDBC connections ............................................................................................ 323.4. Optional configuration properties ........................................................................ 343.4.1. SQL Dialects .......................................................................................... 423.4.2. Outer Join Fetching ................................................................................ 433.4.3. Binary Streams ...................................................................................... 433.4.4. Second-level and query cache ................................................................ 433.4.5. Query Language Substitution .................................................................. 433.4.6. Hibernate statistics ................................................................................. 443.5. Logging ............................................................................................................ 443.6. Implementing a NamingStrategy ........................................................................ 453.7. Implementing a PersisterClassProvider .............................................................. 453.8. XML configuration file ........................................................................................ 46HIBERNATE - Relational Persis...iv3.9. Java EE Application Server integration ............................................................... 473.9.1. Transaction strategy configuration ........................................................... 473.9.2. JNDI-bound SessionFactory .................................................................... 493.9.3. Current Session context management with JTA ........................................ 493.9.4. JMX deployment .................................................................................... 504. Persistent Classes ..................................................................................................... 534.1. A simple POJO example ................................................................................... 534.1.1. Implement a no-argument constructor ...................................................... 544.1.2. Provide an identifier property .................................................................. 554.1.3. Prefer non-final classes (semi-optional) ................................................... 554.1.4. Declare accessors and mutators for persistent fields (optional) .................. 564.2. Implementing inheritance ................................................................................... 564.3. Implementing equals() and hashCode() .............................................................. 574.4. Dynamic models ............................................................................................... 584.5. Tuplizers .......................................................................................................... 604.6. EntityNameResolvers ........................................................................................ 615. Basic O/R Mapping .................................................................................................... 655.1. Mapping declaration .......................................................................................... 655.1.1. Entity ..................................................................................................... 685.1.2. Identifiers ............................................................................................... 735.1.3. Optimistic locking properties (optional) ..................................................... 915.1.4. Property ................................................................................................. 945.1.5. Embedded objects (aka components) .................................................... 1035.1.6. Inheritance strategy .............................................................................. 1065.1.7. Mapping one to one and one to many associations ................................. 1175.1.8. Natural-id ............................................................................................. 1265.1.9. Any ...................................................................................................... 1275.1.10. Properties .......................................................................................... 1295.1.11. Some hbm.xml specificities ................................................................. 1305.2. Hibernate types ............................................................................................... 1345.2.1. Entities and values ............................................................................... 1345.2.2. Basic value types ................................................................................. 1355.2.3. Custom value types .............................................................................. 1375.3. Mapping a class more than once ..................................................................... 1385.4. SQL quoted identifiers ..................................................................................... 1395.5. Generated properties ....................................................................................... 1395.6. Column transformers: read and write expressions ............................................. 1405.7. Auxiliary database objects ............................................................................... 1416. Types ....................................................................................................................... 1436.1. Value types .................................................................................................... 1436.1.1. Basic value types ................................................................................. 1436.1.2. Composite types .................................................................................. 1496.1.3. Collection types .................................................................................... 1496.2. Entity types ..................................................................................................... 150v6.3. Significance of type categories ......................................................................... 1506.4. Custom types .................................................................................................. 1506.4.1. Custom types using org.hibernate.type.Type .......................................... 1506.4.2. Custom types using org.hibernate.usertype.UserType ............................. 1526.4.3. Custom types using org.hibernate.usertype.CompositeUserType ............. 1536.5. Type registry ................................................................................................... 1557. Collection mapping .................................................................................................. 1577.1. Persistent collections ....................................................................................... 1577.2. How to map collections ................................................................................... 1587.2.1. Collection foreign keys .......................................................................... 1627.2.2. Indexed collections ............................................................................... 1627.2.3. Collections of basic types and embeddable objects ................................. 1687.3. Advanced collection mappings ......................................................................... 1707.3.1. Sorted collections ................................................................................. 1707.3.2. Bidirectional associations ...................................................................... 1717.3.3. Bidirectional associations with indexed collections .................................. 1767.3.4. Ternary associations ............................................................................. 1777.3.5. Using an <idbag> ................................................................................. 1787.4. Collection examples ........................................................................................ 1798. Association Mappings ............................................................................................. 1858.1. Introduction ..................................................................................................... 1858.2. Unidirectional associations ............................................................................... 1858.2.1. Many-to-one ......................................................................................... 1858.2.2. One-to-one ........................................................................................... 1858.2.3. One-to-many ........................................................................................ 1868.3. Unidirectional associations with join tables ........................................................ 1878.3.1. One-to-many ........................................................................................ 1878.3.2. Many-to-one ......................................................................................... 1888.3.3. One-to-one ........................................................................................... 1888.3.4. Many-to-many ...................................................................................... 1898.4. Bidirectional associations ................................................................................. 1908.4.1. one-to-many / many-to-one ................................................................... 1908.4.2. One-to-one ........................................................................................... 1918.5. Bidirectional associations with join tables .......................................................... 1928.5.1. one-to-many / many-to-one ................................................................... 1928.5.2. one to one ........................................................................................... 1938.5.3. Many-to-many ...................................................................................... 1938.6. More complex association mappings ................................................................ 1949. Component Mapping ................................................................................................ 1979.1. Dependent objects .......................................................................................... 1979.2. Collections of dependent objects ...................................................................... 1999.3. Components as Map indices ............................................................................ 2009.4. Components as composite identifiers ............................................................... 2009.5. Dynamic components ...................................................................................... 202HIBERNATE - Relational Persis...vi10. Inheritance mapping .............................................................................................. 20510.1. The three strategies ...................................................................................... 20510.1.1. Table per class hierarchy .................................................................... 20510.1.2. Table per subclass ............................................................................. 20610.1.3. Table per subclass: using a discriminator ............................................. 20610.1.4. Mixing table per class hierarchy with table per subclass ........................ 20710.1.5. Table per concrete class ..................................................................... 20810.1.6. Table per concrete class using implicit polymorphism ............................ 20910.1.7. Mixing implicit polymorphism with other inheritance mappings ................ 21010.2. Limitations .................................................................................................... 21011. Working with objects ............................................................................................. 21311.1. Hibernate object states .................................................................................. 21311.2. Making objects persistent .............................................................................. 21311.3. Loading an object .......................................................................................... 21411.4. Querying ....................................................................................................... 21611.4.1. Executing queries ............................................................................... 21611.4.2. Filtering collections ............................................................................. 22011.4.3. Criteria queries ................................................................................... 22111.4.4. Queries in native SQL ........................................................................ 22111.5. Modifying persistent objects ........................................................................... 22211.6. Modifying detached objects ............................................................................ 22211.7. Automatic state detection ............................................................................... 22311.8. Deleting persistent objects ............................................................................. 22411.9. Replicating object between two different datastores ......................................... 22511.10. Flushing the Session ................................................................................... 22511.11. Transitive persistence .................................................................................. 22611.12. Using metadata ........................................................................................... 22912. Read-only entities .................................................................................................. 23112.1. Making persistent entities read-only ................................................................ 23112.1.1. Entities of immutable classes .............................................................. 23212.1.2. Loading persistent entities as read-only ............................................... 23212.1.3. Loading read-only entities from an HQL query/criteria ........................... 23312.1.4. Making a persistent entity read-only ..................................................... 23412.2. Read-only affect on property type ................................................................... 23512.2.1. Simple properties ................................................................................ 23612.2.2. Unidirectional associations .................................................................. 23712.2.3. Bidirectional associations .................................................................... 23813. Transactions and Concurrency .............................................................................. 24113.1. Session and transaction scopes ..................................................................... 24113.1.1. Unit of work ....................................................................................... 24113.1.2. Long conversations ............................................................................. 24213.1.3. Considering object identity .................................................................. 24313.1.4. Common issues .................................................................................. 24413.2. Database transaction demarcation .................................................................. 245vii13.2.1. Non-managed environment ................................................................. 24613.2.2. Using JTA .......................................................................................... 24713.2.3. Exception handling ............................................................................. 24813.2.4. Transaction timeout ............................................................................ 24913.3. Optimistic concurrency control ........................................................................ 25013.3.1. Application version checking ............................................................... 25013.3.2. Extended session and automatic versioning ......................................... 25113.3.3. Detached objects and automatic versioning .......................................... 25213.3.4. Customizing automatic versioning ........................................................ 25213.4. Pessimistic locking ........................................................................................ 25313.5. Connection release modes ............................................................................ 25414. Interceptors and events ......................................................................................... 25714.1. Interceptors ................................................................................................... 25714.2. Event system ................................................................................................ 25914.3. Hibernate declarative security ........................................................................ 26015. Batch processing ................................................................................................... 26315.1. Batch inserts ................................................................................................. 26315.2. Batch updates ............................................................................................... 26415.3. The StatelessSession interface ...................................................................... 26415.4. DML-style operations ..................................................................................... 26516. HQL: The Hibernate Query Language .................................................................... 26916.1. Case Sensitivity ............................................................................................ 26916.2. The from clause ............................................................................................ 26916.3. Associations and joins ................................................................................... 27016.4. Forms of join syntax ...................................................................................... 27116.5. Referring to identifier property ........................................................................ 27216.6. The select clause .......................................................................................... 27216.7. Aggregate functions ....................................................................................... 27416.8. Polymorphic queries ...................................................................................... 27416.9. The where clause .......................................................................................... 27516.10. Expressions ................................................................................................ 27716.11. The order by clause .................................................................................... 28116.12. The group by clause .................................................................................... 28116.13. Subqueries .................................................................................................. 28216.14. HQL examples ............................................................................................ 28316.15. Bulk update and delete ................................................................................ 28516.16. Tips & Tricks ............................................................................................... 28516.17. Components ................................................................................................ 28616.18. Row value constructor syntax ....................................................................... 28717. Criteria Queries ...................................................................................................... 28917.1. Creating a Criteria instance ........................................................................... 28917.2. Narrowing the result set ................................................................................. 28917.3. Ordering the results ....................................................................................... 29017.4. Associations .................................................................................................. 291HIBERNATE - Relational Persis...viii17.5. Dynamic association fetching ......................................................................... 29217.6. Example queries ........................................................................................... 29217.7. Projections, aggregation and grouping ............................................................ 29317.8. Detached queries and subqueries .................................................................. 29517.9. Queries by natural identifier ........................................................................... 29518. Native SQL ............................................................................................................. 29718.1. Using a SQLQuery ........................................................................................ 29718.1.1. Scalar queries .................................................................................... 29718.1.2. Entity queries ..................................................................................... 29818.1.3. Handling associations and collections .................................................. 29818.1.4. Returning multiple entities ................................................................... 29918.1.5. Returning non-managed entities .......................................................... 30118.1.6. Handling inheritance ........................................................................... 30118.1.7. Parameters ........................................................................................ 30118.2. Named SQL queries ...................................................................................... 30218.2.1. Using return-property to explicitly specify column/alias names ................ 30818.2.2. Using stored procedures for querying ................................................... 30918.3. Custom SQL for create, update and delete ..................................................... 31018.4. Custom SQL for loading ................................................................................ 31319. Filtering data .......................................................................................................... 31519.1. Hibernate filters ............................................................................................. 31520. XML Mapping ......................................................................................................... 31920.1. Working with XML data ................................................................................. 31920.1.1. Specifying XML and class mapping together ........................................ 31920.1.2. Specifying only an XML mapping ......................................................... 32020.2. XML mapping metadata ................................................................................. 32020.3. Manipulating XML data .................................................................................. 32221. Improving performance .......................................................................................... 32521.1. Fetching strategies ........................................................................................ 32521.1.1. Working with lazy associations ............................................................ 32621.1.2. Tuning fetch strategies ........................................................................ 32621.1.3. Single-ended association proxies ......................................................... 32721.1.4. Initializing collections and proxies ........................................................ 32921.1.5. Using batch fetching ........................................................................... 33121.1.6. Using subselect fetching ..................................................................... 33121.1.7. Fetch profiles ..................................................................................... 33221.1.8. Using lazy property fetching ................................................................ 33421.2. The Second Level Cache .............................................................................. 33421.2.1. Cache mappings ................................................................................ 33521.2.2. Strategy: read only ............................................................................. 33821.2.3. Strategy: read/write ............................................................................. 33821.2.4. Strategy: nonstrict read/write ............................................................... 33821.2.5. Strategy: transactional ........................................................................ 33821.2.6. Cache-provider/concurrency-strategy compatibility ................................ 338ix21.3. Managing the caches .................................................................................... 33921.4. The Query Cache .......................................................................................... 34021.4.1. Enabling query caching ....................................................................... 34121.4.2. Query cache regions .......................................................................... 34221.5. Understanding Collection performance ............................................................ 34221.5.1. Taxonomy .......................................................................................... 34221.5.2. Lists, maps, idbags and sets are the most efficient collections to update ... 34321.5.3. Bags and lists are the most efficient inverse collections ......................... 34321.5.4. One shot delete .................................................................................. 34421.6. Monitoring performance ................................................................................. 34421.6.1. Monitoring a SessionFactory ............................................................... 34421.6.2. Metrics ............................................................................................... 34522. Toolset Guide ......................................................................................................... 34722.1. Automatic schema generation ........................................................................ 34722.1.1. Customizing the schema ..................................................................... 34722.1.2. Running the tool ................................................................................. 35022.1.3. Properties .......................................................................................... 35122.1.4. Using Ant ........................................................................................... 35122.1.5. Incremental schema updates ............................................................... 35222.1.6. Using Ant for incremental schema updates ........................................... 35222.1.7. Schema validation .............................................................................. 35322.1.8. Using Ant for schema validation .......................................................... 35323. Additional modules ................................................................................................ 35523.1. Bean Validation ............................................................................................. 35523.1.1. Adding Bean Validation ....................................................................... 35523.1.2. Configuration ...................................................................................... 35523.1.3. Catching violations .............................................................................. 35723.1.4. Database schema ............................................................................... 35723.2. Hibernate Search .......................................................................................... 35823.2.1. Description ......................................................................................... 35823.2.2. Integration with Hibernate Annotations ................................................. 35824. Example: Parent/Child ............................................................................................ 35924.1. A note about collections ................................................................................ 35924.2. Bidirectional one-to-many ............................................................................... 35924.3. Cascading life cycle ...................................................................................... 36124.4. Cascades and unsaved-value ........................................................................ 36224.5. Conclusion .................................................................................................... 36325. Example: Weblog Application ................................................................................ 36525.1. Persistent Classes ......................................................................................... 36525.2. Hibernate Mappings ...................................................................................... 36625.3. Hibernate Code ............................................................................................. 36826. Example: Various Mappings .................................................................................. 37326.1. Employer/Employee ....................................................................................... 37326.2. Author/Work .................................................................................................. 375HIBERNATE - Relational Persis...x26.3. Customer/Order/Product ................................................................................ 37726.4. Miscellaneous example mappings .................................................................. 37926.4.1. "Typed" one-to-one association ........................................................... 37926.4.2. Composite key example ...................................................................... 37926.4.3. Many-to-many with shared composite key attribute ............................... 38126.4.4. Content based discrimination ............................................................... 38226.4.5. Associations on alternate keys ............................................................ 38327. Best Practices ........................................................................................................ 38528. Database Portability Considerations ...................................................................... 38928.1. Portability Basics ........................................................................................... 38928.2. Dialect .......................................................................................................... 38928.3. Dialect resolution ........................................................................................... 38928.4. Identifier generation ....................................................................................... 39028.5. Database functions ........................................................................................ 39128.6. Type mappings ............................................................................................. 391References .................................................................................................................... 393xiPrefaceWorking with both Object-Oriented software and Relational Databases can be cumbersomeand time consuming. Development costs are significantly higher due to a paradigm mismatchbetween how data is represented in objects versus relational databases. Hibernate is an Object/Relational Mapping solution for Java environments. The term Object/Relational Mapping refersto the technique of mapping data from an object model representation to a relational data modelrepresentation (and visa versa). See http://en.wikipedia.org/wiki/Object-relational_mapping for agood high-level discussion.NoteWhile having a strong background in SQL is not required to use Hibernate, havinga basic understanding of the concepts can greatly help you understand Hibernatemore fully and quickly. Probably the single best background is an understanding ofdata modeling principles. You might want to consider these resources as a goodstarting point:• http://www.agiledata.org/essays/dataModeling101.html• http://en.wikipedia.org/wiki/Data_modelingHibernate not only takes care of the mapping from Java classes to database tables (and fromJava data types to SQL data types), but also provides data query and retrieval facilities. It cansignificantly reduce development time otherwise spent with manual data handling in SQL andJDBC. Hibernate’s design goal is to relieve the developer from 95% of common data persistence-related programming tasks by eliminating the need for manual, hand-crafted data processingusing SQL and JDBC. However, unlike many other persistence solutions, Hibernate does not hidethe power of SQL from you and guarantees that your investment in relational technology andknowledge is as valid as always.Hibernate may not be the best solution for data-centric applications that only use stored-procedures to implement the business logic in the database, it is most useful with object-oriented domain models and business logic in the Java-based middle-tier. However, Hibernatecan certainly help you to remove or encapsulate vendor-specific SQL code and will help with thecommon task of result set translation from a tabular representation to a graph of objects.If you are new to Hibernate and Object/Relational Mapping or even Java, please follow thesesteps:1.Read Chapter 1, Tutorial for a tutorial with step-by-step instructions. The source code for thetutorial is included in the distribution in the doc/reference/tutorial/ directory.2.Read Chapter 2, Architecture to understand the environments where Hibernate can be used.Prefacexii3.View the eg/ directory in the Hibernate distribution. It contains a simple standalone application.Copy your JDBC driver to the lib/ directory and edit etc/hibernate.properties, specifyingcorrect values for your database. From a command prompt in the distribution directory, typeant eg (using Ant), or under Windows, type build eg.4.Use this reference documentation as your primary source of information. Consider reading[JPwH] if you need more help with application design, or if you prefer a step-by-step tutorial. Alsovisit http://caveatemptor.hibernate.org and download the example application from [JPwH].5.FAQs are answered on the Hibernate website.6.Links to third party demos, examples, and tutorials are maintained on the Hibernate website.7.The Community Area on the Hibernate website is a good resource for design patterns andvarious integration solutions (Tomcat, JBoss AS, Struts, EJB, etc.).There are a number of ways to become involved in the Hibernate community, including• Trying stuff out and reporting bugs. See http://hibernate.org/issuetracker.html details.• Trying your hand at fixing some bugs or implementing enhancements. Again, see http://hibernate.org/issuetracker.html details.• http://hibernate.org/community.html list a few ways to engage in the community.• There are forums for users to ask questions and receive help from the community.• There are also IRC [http://en.wikipedia.org/wiki/Internet_Relay_Chat] channels for both userand developer discussions.• Helping improve or translate this documentation. Contact us on the developer mailing list if youhave interest.• Evangelizing Hibernate within your organization.Chapter 1.1TutorialIntended for new users, this chapter provides an step-by-step introduction to Hibernate, startingwith a simple application using an in-memory database. The tutorial is based on an earlier tutorialdeveloped by Michael Gloegl. All code is contained in the tutorials/web directory of the projectsource.ImportantThis tutorial expects the user have knowledge of both Java and SQL. If you havea limited knowledge of JAVA or SQL, it is advised that you start with a goodintroduction to that technology prior to attempting to learn Hibernate.NoteThe distribution contains another example application under the tutorial/egproject source directory.1.1. Part 1 - The first Hibernate ApplicationFor this example, we will set up a small database application that can store events we want toattend and information about the host(s) of these events.NoteAlthough you can use whatever database you feel comfortable using, we will useHSQLDB [http://hsqldb.org/] (an in-memory, Java database) to avoid describinginstallation/setup of any particular database servers.1.1.1. SetupThe first thing we need to do is to set up the development environment. We will be usingthe "standard layout" advocated by alot of build tools such as Maven [http://maven.org].Maven, in particular, has a good resource describing this layout [http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html]. As this tutorial is to be a webapplication, we will be creating and making use of src/main/java, src/main/resources andsrc/main/webapp directories.We will be using Maven in this tutorial, taking advantage of its transitive dependency managementcapabilities as well as the ability of many IDEs to automatically set up a project for us based onthe maven descriptor.Chapter 1. Tutorial2<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.hibernate.tutorials</groupId><artifactId>hibernate-tutorial</artifactId><version>1.0.0-SNAPSHOT</version><name>First Hibernate Tutorial</name><build><!-- we dont want the version to be part of the generated war file name --><finalName>${artifactId}</finalName></build><dependencies><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId></dependency><!-- Because this is a web app, we also have a dependency on the servlet api. --><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId></dependency><!-- Hibernate uses slf4j for logging, for our purposes here use the simple backend --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId></dependency><!-- Hibernate gives you a choice of bytecode providers between cglib and javassist --><dependency><groupId>javassist</groupId><artifactId>javassist</artifactId></dependency></dependencies></project>TipIt is not a requirement to use Maven. If you wish to use something else to buildthis tutorial (such as Ant), the layout will remain the same. The only change isthat you will need to manually account for all the needed dependencies. If youuse something like Ivy [http://ant.apache.org/ivy/] providing transitive dependencymanagement you would still use the dependencies mentioned below. Otherwise,you'd need to grab all dependencies, both explicit and transitive, and add themto the project's classpath. If working from the Hibernate distribution bundle, thisThe first class3would mean hibernate3.jar, all artifacts in the lib/required directory and allfiles from either the lib/bytecode/cglib or lib/bytecode/javassist directory;additionally you will need both the servlet-api jar and one of the slf4j loggingbackends.Save this file as pom.xml in the project root directory.1.1.2. The first classNext, we create a class that represents the event we want to store in the database; it is a simpleJavaBean class with some properties:package org.hibernate.tutorial.domain;import java.util.Date;public class Event {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;}}This class uses standard JavaBean naming conventions for property getter and setter methods,as well as private visibility for the fields. Although this is the recommended design, it is notChapter 1. Tutorial4required. Hibernate can also access fields directly, the benefit of accessor methods is robustnessfor refactoring.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 wantto use the full feature set of Hibernate. In fact, most applications, especially web applications, needto distinguish objects by identifier, so you should consider this a feature rather than a limitation.However, we usually do not manipulate the identity of an object, hence the setter method shouldbe private. Only Hibernate will assign identifiers when an object is saved. Hibernate can accesspublic, private, and protected accessor methods, as well as public, private and protected fieldsdirectly. 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 createobjects for you, using Java Reflection. The constructor can be private, however package or publicvisibility is required for runtime proxy generation and efficient data retrieval without bytecodeinstrumentation.Save this file to the src/main/java/org/hibernate/tutorial/domain directory.1.1.3. The mapping fileHibernate needs to know how to load and store objects of the persistent class. This is wherethe Hibernate mapping file comes into play. The mapping file tells Hibernate what table in thedatabase 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://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="org.hibernate.tutorial.domain">[...]</hibernate-mapping>Hibernate DTD is sophisticated. You can use it for auto-completion of XML mapping elementsand attributes in your editor or IDE. Opening up the DTD file in your text editor is the easiestway to get an overview of all elements and attributes, and to view the defaults, as well as somecomments. Hibernate will not load the DTD file from the web, but first look it up from the classpathof the application. The DTD file is included in hibernate-core.jar (it is also included in thehibernate3.jar, if using the distribution bundle).The mapping file5ImportantWe will omit the DTD declaration in future examples to shorten the code. It is, ofcourse, 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 amapping to a table in the SQL database:<hibernate-mapping package="org.hibernate.tutorial.domain"><class name="Event" table="EVENTS"></class></hibernate-mapping>So far we have told Hibernate how to persist and load object of class Event to the table EVENTS.Each instance is now represented by a row in that table. Now we can continue by mapping theunique identifier property to the tables primary key. As we do not want to care about handlingthis identifier, we configure Hibernate's identifier generation strategy for a surrogate primary keycolumn:<hibernate-mapping package="org.hibernate.tutorial.domain"><class name="Event" table="EVENTS"><id name="id" column="EVENT_ID"><generator class="native"/></id></class></hibernate-mapping>The id element is the declaration of the identifier property. The name="id" mapping attributedeclares the name of the JavaBean property and tells Hibernate to use the getId() and setId()methods to access the property. The column attribute tells Hibernate which column of the EVENTStable holds the primary key value.The nested generator element specifies the identifier generation strategy (aka how are identifiervalues generated?). In this case we choose native, which offers a level of portability dependingon the configured database dialect. Hibernate supports database generated, globally unique, aswell as application assigned, identifiers. Identifier value generation is also one of Hibernate's manyextension points and you can plugin in your own strategy.Chapter 1. Tutorial6Tipnative is no longer consider the best strategy in terms of portability. for furtherdiscussion, see Section 28.4, “Identifier generation”Lastly, we need to tell Hibernate about the remaining entity class properties. By default, noproperties of the class are considered persistent:<hibernate-mapping package="org.hibernate.tutorial.domain"><class name="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>Similar to the id element, the name attribute of the property element tells Hibernate whichgetter and setter methods to use. In this case, Hibernate will search for getDate(), setDate(),getTitle() and setTitle() methods.NoteWhy does the date property mapping include the column attribute, but the titledoes not? Without the column attribute, Hibernate by default uses the propertyname as the column name. This works for title, however, date is a reservedkeyword in most databases so you will need to map it to a different name.The title mapping also lacks a type attribute. The types declared and used in the mapping filesare not Java data types; they are not SQL database types either. These types are called Hibernatemapping 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 attributeis not present in the mapping. In some cases this automatic detection using Reflection on theJava class might not have the default you expect or need. This is the case with the date property.Hibernate cannot know if the property, which is of java.util.Date, should map to a SQL date,timestamp, or time column. Full date and time information is preserved by mapping the propertywith a timestamp converter.Hibernate configuration7TipHibernate makes this mapping type determination using reflection when themapping files are processed. This can take time and resources, so if startupperformance is important you should consider explicitly defining the type to use.Save this mapping file as src/main/resources/org/hibernate/tutorial/domain/Event.hbm.xml.1.1.4. Hibernate configurationAt this point, you should have the persistent class and its mapping file in place. It is now time toconfigure Hibernate. First let's set up HSQLDB to run in "server mode"NoteWe do this do that the data remains between runs.We will utilize the Maven exec plugin to launch the HSQLDB server by running: mvn exec:java-Dexec.mainClass="org.hsqldb.Server" -Dexec.args="-database.0 file:target/data/tutorial" You will see it start up and bind to a TCP/IP socket; this is where our application willconnect later. If you want to start with a fresh database during this tutorial, shutdown HSQLDB,delete all files in the target/data directory, and start HSQLDB again.Hibernate will be connecting to the database on behalf of your application, so it needs to knowhow to obtain connections. For this tutorial we will be using a standalone connection pool (asopposed to a javax.sql.DataSource). Hibernate comes with support for two third-party opensource JDBC connection pools: c3p0 [https://sourceforge.net/projects/c3p0] and proxool [http://proxool.sourceforge.net/]. However, we will be using the Hibernate built-in connection pool forthis tutorial.CautionThe built-in Hibernate connection pool is in no way intended for production use. Itlacks several features found on any decent connection pool.For Hibernate's configuration, we can use a simple hibernate.properties file, a moresophisticated hibernate.cfg.xml file, or even complete programmatic setup. Most users preferthe XML configuration file:<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN"Chapter 1. Tutorial8"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- Database connection settings --><property name="connection.driver_class">org.hsqldb.jdbcDriver</property><property name="connection.url">jdbc:hsqldb:hsql://localhost</property><property name="connection.username">sa</property><property name="connection.password"></property><!-- JDBC connection pool (use the built-in) --><property name="connection.pool_size">1</property><!-- SQL dialect --><property name="dialect">org.hibernate.dialect.HSQLDialect</property><!-- Enable Hibernate's automatic session context management --><property name="current_session_context_class">thread</property><!-- Disable the second-level cache --><property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property><!-- Echo all executed SQL to stdout --><property name="show_sql">true</property><!-- Drop and re-create the database schema on startup --><property name="hbm2ddl.auto">update</property><mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/></session-factory></hibernate-configuration>NoteNotice that this configuration file specifies a different DTDYou configure Hibernate's SessionFactory. SessionFactory is a global factory responsible fora particular database. If you have several databases, for easier startup you should use several<session-factory> configurations in several configuration files.The first four property elements contain the necessary configuration for the JDBC connection.The dialect property element specifies the particular SQL variant Hibernate generates.TipIn most cases, Hibernate is able to properly determine which dialect to use. SeeSection 28.3, “Dialect resolution” for more information.Building with Maven9Hibernate's automatic session management for persistence contexts is particularly useful in thiscontext. The hbm2ddl.auto option turns on automatic generation of database schemas directlyinto the database. This can also be turned off by removing the configuration option, or redirectedto a file with the help of the SchemaExport Ant task. Finally, add the mapping file(s) for persistentclasses to the configuration.Save this file as hibernate.cfg.xml into the src/main/resources directory.1.1.5. Building with MavenWe will now build the tutorial with Maven. You will need to have Maven installed; it is availablefrom the Maven download page [http://maven.apache.org/download.html]. Maven will read the /pom.xml file we created earlier and know how to perform some basic project tasks. First, lets runthe compile goal to make sure we can compile everything so far:[hibernateTutorial]$ mvn compile[INFO] Scanning for projects...[INFO] ------------------------------------------------------------------------[INFO] Building First Hibernate Tutorial[INFO] task-segment: [compile][INFO] ------------------------------------------------------------------------[INFO] [resources:resources][INFO] Using default encoding to copy filtered resources.[INFO] [compiler:compile][INFO] Compiling 1 source file to /home/steve/projects/sandbox/hibernateTutorial/target/classes[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESSFUL[INFO] ------------------------------------------------------------------------[INFO] Total time: 2 seconds[INFO] Finished at: Tue Jun 09 12:25:25 CDT 2009[INFO] Final Memory: 5M/547M[INFO] ------------------------------------------------------------------------1.1.6. Startup and helpersIt is time to load and store some Event objects, but first you have to complete thesetup with some infrastructure code. You have to startup Hibernate by building a globalorg.hibernate.SessionFactory object and storing it somewhere for easy access inapplication code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Sessioninstances. A org.hibernate.Session represents a single-threaded unit of work. Theorg.hibernate.SessionFactory is a thread-safe global object that is instantiated once.We will create a HibernateUtil helper class that takes care of startup and makes accessing theorg.hibernate.SessionFactory more convenient.package org.hibernate.tutorial.util;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;Chapter 1. Tutorial10public class HibernateUtil {private static final SessionFactory sessionFactory = buildSessionFactory();private static SessionFactory buildSessionFactory() {try {// Create the SessionFactory from hibernate.cfg.xmlreturn new Configuration().configure().buildSessionFactory();}catch (Throwable ex) {// Make sure you log the exception, as it might be swallowedSystem.err.println("Initial SessionFactory creation failed." + ex);throw new ExceptionInInitializerError(ex);}}public static SessionFactory getSessionFactory() {return sessionFactory;}}Save this code as src/main/java/org/hibernate/tutorial/util/HibernateUtil.javaThis class not only produces the global org.hibernate.SessionFactory reference in its staticinitializer; it also hides the fact that it uses a static singleton. We might just as well have looked upthe org.hibernate.SessionFactory reference from JNDI in an application server or any otherlocation for that matter.If you give the org.hibernate.SessionFactory a name in your configuration, Hibernate will tryto bind it to JNDI under that name after it has been built. Another, better option is to use a JMXdeployment and let the JMX-capable container instantiate and bind a HibernateService to JNDI.Such advanced options are discussed later.You now need to configure a logging system. Hibernate uses commons logging and provides twochoices: Log4j and JDK 1.4 logging. Most developers prefer Log4j: copy log4j.properties fromthe Hibernate distribution in the etc/ directory to your src directory, next to hibernate.cfg.xml.If you prefer to have more verbose output than that provided in the example configuration, youcan change the settings. By default, only the Hibernate startup message is shown on stdout.The tutorial infrastructure is complete and you are now ready to do some real work with Hibernate.1.1.7. Loading and storing objectsWe are now ready to start doing some real work with Hibernate. Let's start by writing anEventManager class with a main() method:package org.hibernate.tutorial;import org.hibernate.Session;Loading and storing objects11import java.util.*;import org.hibernate.tutorial.domain.Event;import org.hibernate.tutorial.util.HibernateUtil;public class EventManager {public static void main(String[] args) {EventManager mgr = new EventManager();if (args[0].equals("store")) {mgr.createAndStoreEvent("My Event", new Date());}HibernateUtil.getSessionFactory().close();}private void createAndStoreEvent(String title, Date theDate) {Session session = HibernateUtil.getSessionFactory().getCurrentSession();session.beginTransaction();Event theEvent = new Event();theEvent.setTitle(title);theEvent.setDate(theDate);session.save(theEvent);session.getTransaction().commit();}}In createAndStoreEvent() we created a new Event object and handed it over to Hibernate. Atthat point, Hibernate takes care of the SQL and executes an INSERT on the database.A org.hibernate.Session is designed to represent a single unit of work (a single atomic piece ofwork to be performed). For now we will keep things simple and assume a one-to-one granularitybetween a Hibernate org.hibernate.Session and a database transaction. To shield our code fromthe actual underlying transaction system we use the Hibernate org.hibernate.TransactionAPI. In this particular case we are using JDBC-based transactional semantics, but it could alsorun with JTA.What does sessionFactory.getCurrentSession() do? First, you can call it as many timesand anywhere you like once you get hold of your org.hibernate.SessionFactory. ThegetCurrentSession() method always returns the "current" unit of work. Remember that weswitched the configuration option for this mechanism to "thread" in our src/main/resources/hibernate.cfg.xml? Due to that setting, the context of a current unit of work is bound to thecurrent Java thread that executes the application.ImportantHibernate offers three methods of current session tracking. The "thread" basedmethod is not intended for production use; it is merely useful for prototyping andChapter 1. Tutorial12tutorials such as this one. Current session tracking is discussed in more detail lateron.A org.hibernate.Session begins when the first call to getCurrentSession() is made for thecurrent thread. It is then bound by Hibernate to the current thread. When the transaction ends,either through commit or rollback, Hibernate automatically unbinds the org.hibernate.Sessionfrom the thread and closes it for you. If you call getCurrentSession() again, you get a neworg.hibernate.Session and can start a new unit of work.Related to the unit of work scope, should the Hibernate org.hibernate.Session be used to executeone or several database operations? The above example uses one org.hibernate.Session for oneoperation. However this is pure coincidence; the example is just not complex enough to showany other approach. The scope of a Hibernate org.hibernate.Session is flexible but you shouldnever design your application to use a new Hibernate org.hibernate.Session for every databaseoperation. Even though it is used in the following examples, consider session-per-operation ananti-pattern. A real web application is shown later in the tutorial which will help illustrate this.See Chapter 13, Transactions and Concurrency for more information about transaction handlingand demarcation. The previous example also skipped any error handling and rollback.To run this, we will make use of the Maven exec plugin to callour class with the necessary classpath setup: mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="store"NoteYou may need to perform mvn compile first.You should see Hibernate starting up and, depending on your configuration, lots of log output.Towards the end, the following line will be displayed:[java] Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) values (?, ?, ?)This is the INSERT executed by Hibernate.To list stored events an option is added to the main method:if (args[0].equals("store")) {mgr.createAndStoreEvent("My Event", new Date());}else if (args[0].equals("list")) {List events = mgr.listEvents();for (int i = 0; i < events.size(); i++) {Event theEvent = (Event) events.get(i);System.out.println("Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate()Part 2 - Mapping associations13);}}A new listEvents() method is also added:private List listEvents() {Session session = HibernateUtil.getSessionFactory().getCurrentSession();session.beginTransaction();List result = session.createQuery("from Event").list();session.getTransaction().commit();return result;}Here, we are using a Hibernate Query Language (HQL) query to load all existing Event objectsfrom the database. Hibernate will generate the appropriate SQL, send it to the database andpopulate Event objects with the data. You can create more complex queries with HQL. SeeChapter 16, HQL: The Hibernate Query Language for more information.Now we can call our new functionality, again using the Maven exec plugin: mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="list"1.2. Part 2 - Mapping associationsSo far we have mapped a single persistent entity class to a table in isolation. Let's expand on thata bit and add some class associations. We will add people to the application and store a list ofevents in which they participate.1.2.1. Mapping the Person classThe first cut of the Person class looks like this:package org.hibernate.tutorial.domain;public class Person {private Long id;private int age;private String firstname;private String lastname;public Person() {}// Accessor methods for all properties, private setter for 'id'}Save this to a file named src/main/java/org/hibernate/tutorial/domain/Person.javaChapter 1. Tutorial14Next, create the new mapping file as src/main/resources/org/hibernate/tutorial/domain/Person.hbm.xml<hibernate-mapping package="org.hibernate.tutorial.domain"><class name="Person" table="PERSON"><id name="id" column="PERSON_ID"><generator class="native"/></id><property name="age"/><property name="firstname"/><property name="lastname"/></class></hibernate-mapping>Finally, add the new mapping to Hibernate's configuration:<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/><mapping resource="org/hibernate/tutorial/domain/Person.hbm.xml"/>Create an association between these two entities. Persons can participate in events, and eventshave participants. The design questions you have to deal with are: directionality, multiplicity, andcollection behavior.1.2.2. A unidirectional Set-based associationBy adding a collection of events to the Person class, you can easily navigate to the events for aparticular person, without executing an explicit query - by calling Person#getEvents. Multi-valuedassociations are represented in Hibernate by one of the Java Collection Framework contracts;here we choose a java.util.Set because the collection will not contain duplicate elements andthe ordering is not relevant to our examples:public class Person {private Set events = new HashSet();public Set getEvents() {return events;}public void setEvents(Set events) {this.events = events;}}Working the association15Before mapping this association, let's consider the other side. We could just keep thisunidirectional or create another collection on the Event, if we wanted to be able to navigate it fromboth directions. This is not necessary, from a functional perspective. You can always execute anexplicit query to retrieve the participants for a particular event. This is a design choice left to you,but what is clear from this discussion is the multiplicity of the association: "many" valued on bothsides is called a many-to-many association. Hence, we use Hibernate's many-to-many mapping:<class name="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="Event"/></set></class>Hibernate supports a broad range of collection mappings, a set being most common. For a many-to-many association, or n:m entity relationship, an association table is required. Each row in thistable represents a link between a person and an event. The table name is decalred using the tableattribute of the set element. The identifier column name in the association, for the person side, isdefined with the key element, the column name for the event's side with the column attribute ofthe many-to-many. You also have to tell Hibernate the class of the objects in your collection (theclass on the other side of the collection of references).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.2.3. Working the associationNow we will bring some people and events together in a new method in EventManager:Chapter 1. Tutorial16private void addPersonToEvent(Long personId, Long eventId) {Session session = HibernateUtil.getSessionFactory().getCurrentSession();session.beginTransaction();Person aPerson = (Person) session.load(Person.class, personId);Event anEvent = (Event) session.load(Event.class, eventId);aPerson.getEvents().add(anEvent);session.getTransaction().commit();}After loading a Person and an Event, simply modify the collection using the normal collectionmethods. There is no explicit call to update() or save(); Hibernate automatically detects that thecollection has been modified and needs to be updated. This is called automatic dirty checking. Youcan also try it by modifying the name or the date property of any of your objects. As long as they arein persistent state, that is, bound to a particular Hibernate org.hibernate.Session, Hibernatemonitors any changes and executes SQL in a write-behind fashion. The process of synchronizingthe memory state with the database, usually only at the end of a unit of work, is called flushing. Inour code, the unit of work ends with a commit, or rollback, of the database transaction.You can load person and event in different units of work. Or you can modify an object outside ofa org.hibernate.Session, when it is not in persistent state (if it was persistent before, this stateis called detached). You can even modify a collection when it is detached:private void addPersonToEvent(Long personId, Long eventId) {Session session = HibernateUtil.getSessionFactory().getCurrentSession();session.beginTransaction();Person aPerson = (Person) session.createQuery("select p from Person p left join fetch p.events where p.id = :pid").setParameter("pid", personId).uniqueResult(); // Eager fetch the collection so we can use it detachedEvent anEvent = (Event) session.load(Event.class, eventId);session.getTransaction().commit();// End of first unit of workaPerson.getEvents().add(anEvent); // aPerson (and its collection) is detached// Begin second unit of workSession session2 = HibernateUtil.getSessionFactory().getCurrentSession();session2.beginTransaction();session2.update(aPerson); // Reattachment of aPersonsession2.getTransaction().commit();}Collection of values17The call to update makes a detached object persistent again by binding it to a new unit of work,so any modifications you made to it while detached can be saved to the database. This includesany modifications (additions/deletions) you made to a collection of that entity object.This is not much use in our example, but it is an important concept you can incorporate intoyour own application. Complete this exercise by adding a new action to the main method of theEventManager and call it from the command line. If you need the identifiers of a person and anevent - the save() method returns it (you might have to modify some of the previous methodsto return that identifier):else if (args[0].equals("addpersontoevent")) {Long eventId = mgr.createAndStoreEvent("My Event", new Date());Long personId = mgr.createAndStorePerson("Foo", "Bar");mgr.addPersonToEvent(personId, eventId);System.out.println("Added person " + personId + " to event " + eventId);}This is an example of an association between two equally important classes : two entities. Asmentioned earlier, there are other classes and types in a typical model, usually "less important".Some you have already seen, like an int or a java.lang.String. We call these classes valuetypes, and their instances depend on a particular entity. Instances of these types do not havetheir own identity, nor are they shared between entities. Two persons do not reference the samefirstname object, even if they have the same first name. Value types cannot only be found in theJDK , but you can also write dependent classes yourself such as an Address or MonetaryAmountclass. In fact, in a Hibernate application all JDK classes are considered value types.You can also design a collection of value types. This is conceptually different from a collection ofreferences to other entities, but looks almost the same in Java.1.2.4. Collection of valuesLet's add a collection of email addresses to the Person entity. This will be represented as ajava.util.Set of java.lang.String instances:private Set emailAddresses = new HashSet();public Set getEmailAddresses() {return emailAddresses;}public void setEmailAddresses(Set emailAddresses) {this.emailAddresses = emailAddresses;}The mapping of this Set is as follows:Chapter 1. Tutorial18<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 use of the element part which tellsHibernate that the collection does not contain references to another entity, but is rather a collectionwhose elements are values types, here specifically of type string. The lowercase name tells youit is a Hibernate mapping type/converter. Again the table attribute of the set element determinesthe table name for the collection. The key element defines the foreign-key column name in thecollection table. The column attribute in the element element defines the column name where theemail address values will actually be stored.Here is 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 that uses bothcolumns. This also implies that there cannot be duplicate email addresses per person, which isexactly the semantics we need for a set in Java.You can now try to add elements to this collection, just like we did before by linking persons andevents. It is the same code in Java:private void addEmailToPerson(Long personId, String emailAddress) {Session session = HibernateUtil.getSessionFactory().getCurrentSession();session.beginTransaction();Person aPerson = (Person) session.load(Person.class, personId);// adding to the emailAddress collection might trigger a lazy load of the collectionaPerson.getEmailAddresses().add(emailAddress);session.getTransaction().commit();}Bi-directional associations19This time we did not use a fetch query to initialize the collection. Monitor the SQL log and try tooptimize this with an eager fetch.1.2.5. Bi-directional associationsNext you will map a bi-directional association. You will make the association between person andevent work from both sides in Java. The database schema does not change, so you will still havemany-to-many multiplicity.NoteA relational database is more flexible than a network programming language, inthat it does not need a navigation direction; data can be viewed and retrieved inany possible way.First, add a collection of participants to the Event class:private Set participants = new HashSet();public Set getParticipants() {return participants;}public void setParticipants(Set participants) {this.participants = participants;}Now map this side of the association in Event.hbm.xml.<set name="participants" table="PERSON_EVENT" inverse="true"><key column="EVENT_ID"/><many-to-many column="PERSON_ID" class="Person"/></set>These are normal set mappings in both mapping documents. Notice that the column names inkey and many-to-many swap in both mapping documents. The most important addition here isthe inverse="true" attribute in the set element of the Event's collection mapping.What this means is that Hibernate should take the other side, the Person class, when it needs tofind out information about the link between the two. This will be a lot easier to understand onceyou see how the bi-directional link between our two entities is created.1.2.6. Working bi-directional linksFirst, keep in mind that Hibernate does not affect normal Java semantics. How did we createa link between a Person and an Event in the unidirectional example? You add an instance ofChapter 1. Tutorial20Event to the collection of event references, of an instance of Person. If you want to make thislink bi-directional, you have to do the same on the other side by adding a Person reference tothe collection in an Event. This process of "setting the link on both sides" is absolutely necessarywith bi-directional links.Many developers program defensively and create link management methods to correctly set bothsides (for example, in Person):protected Set getEvents() {return events;}protected void setEvents(Set events) {this.events = events;}public void addToEvent(Event event) {this.getEvents().add(event);event.getParticipants().add(this);}public void removeFromEvent(Event event) {this.getEvents().remove(event);event.getParticipants().remove(this);}The get and set methods for the collection are now protected. This allows classes in the samepackage and subclasses to still access the methods, but prevents everybody else from alteringthe collections directly. Repeat the steps for the collection on the other side.What about the inverse mapping attribute? For you, and for Java, a bi-directional link is simplya matter of setting the references on both sides correctly. Hibernate, however, does not haveenough information to correctly arrange SQL INSERT and UPDATE statements (to avoid constraintviolations). Making one side of the association inverse tells Hibernate to consider it a mirrorof the other side. That is all that is necessary for Hibernate to resolve any issues that arisewhen transforming a directional navigation model to a SQL database schema. The rules arestraightforward: all bi-directional associations need one side as inverse. In a one-to-manyassociation it has to be the many-side, and in many-to-many association you can select either side.1.3. Part 3 - The EventManager web applicationA Hibernate web application uses Session and Transaction almost like a standalone application.However, some common patterns are useful. You can now write an EventManagerServlet. Thisservlet can list all events stored in the database, and it provides an HTML form to enter new events.1.3.1. Writing the basic servletFirst we need create our basic processing servlet. Since our servlet only handles HTTP GETrequests, we will only implement the doGet() method:Writing the basic servlet21package org.hibernate.tutorial.web;// Importspublic class EventManagerServlet extends HttpServlet {protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {SimpleDateFormat dateFormatter = new SimpleDateFormat( "dd.MM.yyyy" );try {// Begin unit of workHibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();// Process request and render page...// End unit of workHibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();}catch (Exception ex) {HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();if ( ServletException.class.isInstance( ex ) ) {throw ( ServletException ) ex;}else {throw new ServletException( ex );}}}}Save this servlet as src/main/java/org/hibernate/tutorial/web/EventManagerServlet.javaThe pattern applied here is called session-per-request. When a request hits the servlet, anew Hibernate Session is opened through the first call to getCurrentSession() on theSessionFactory. A database transaction is then started. All data access occurs inside atransaction irrespective of whether the data is read or written. Do not use the auto-commit modein applications.Do not use a new Hibernate Session for every database operation. Use one Hibernate Sessionthat is scoped to the whole request. Use getCurrentSession(), so that it is automatically boundto the current Java thread.Next, the possible actions of the request are processed and the response HTML is rendered. Wewill get to that part soon.Finally, the unit of work ends when processing and rendering are complete. If any problemsoccurred during processing or rendering, an exception will be thrown and the database transactionrolled back. This completes the session-per-request pattern. Instead of the transactionChapter 1. Tutorial22demarcation code in every servlet, you could also write a servlet filter. See the Hibernate websiteand Wiki for more information about this pattern called Open Session in View. You will need it assoon as you consider rendering your view in JSP, not in a servlet.1.3.2. Processing and renderingNow you can implement the processing of the request and the rendering of the page.// Write HTML headerPrintWriter out = response.getWriter();out.println("<html><head><title>Event Manager</title></head><body>");// Handle actionsif ( "store".equals(request.getParameter("action")) ) {String eventTitle = request.getParameter("eventTitle");String eventDate = request.getParameter("eventDate");if ( "".equals(eventTitle) || "".equals(eventDate) ) {out.println("<b><i>Please enter event title and date.</i></b>");}else {createAndStoreEvent(eventTitle, dateFormatter.parse(eventDate));out.println("<b><i>Added event.</i></b>");}}// Print pageprintEventForm(out);listEvents(out, dateFormatter);// Write HTML footerout.println("</body></html>");out.flush();out.close();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. The code printsan HTML header and a footer. Inside this page, an HTML form for event entry and a list of allevents in the database are printed. The first method is trivial and only outputs HTML:private void printEventForm(PrintWriter out) {out.println("<h2>Add new event:</h2>");out.println("<form>");out.println("Title: <input name='eventTitle' length='50'/><br/>");out.println("Date (e.g. 24.12.2009): <input name='eventDate' length='10'/><br/>");out.println("<input type='submit' name='action' value='store'/>");out.println("</form>");