Академический Документы
Профессиональный Документы
Культура Документы
4.3.0.Final
Copyright 2004 Red Hat, Inc. Legal Notice 2013-12-16 Table of Contents Preface 1. Tutorial 1.1. Part 1 - The first Hibernate Application 1.1.1. 1.1.2. 1.1.3. 1.1.4. 1.1.5. 1.1.6. 1.1.7. Setup The first class The mapping file Hibernate configuration Building with Maven Startup and helpers Loading and storing objects
1.2. Part 2 - Mapping associations 1.2.1. 1.2.2. 1.2.3. 1.2.4. 1.2.5. 1.2.6. Mapping the Person class A unidirectional Set-based association Working the association Collection of values Bi-directional associations Working bi-directional links
1.3. Part 3 - The EventManager web application 1.3.1. Writing the basic servlet 1.3.2. Processing and rendering 1.3.3. Deploying and testing 1.4. Summary 2. Architecture 2.1. Overview 2.1.1. Minimal architecture 2.1.2. Comprehensive architecture 2.1.3. Basic APIs 2.2. Contextual sessions 3. Configuration 3.1. 3.2. 3.3. 3.4. Programmatic configuration Obtaining a SessionFactory JDBC connections Optional configuration properties SQL Dialects Outer Join Fetching Binary Streams Second-level and query cache Query Language Substitution Hibernate statistics
3.5. Logging
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
1/215
12/30/13
6. Types 6.1. Value types 6.1.1. Basic value types 6.1.2. Composite types 6.1.3. Collection types 6.2. Entity types 6.3. Significance of type categories 6.4. Custom types 6.4.1. Custom types using o r g . h i b e r n a t e . t y p e . T y p e 6.4.2. Custom types using o r g . h i b e r n a t e . u s e r t y p e . U s e r T y p e 6.4.3. Custom types using o r g . h i b e r n a t e . u s e r t y p e . C o m p o s i t e U s e r T y p e 6.5. Type registry 7. Collection mapping 7.1. Persistent collections 7.2. How to map collections 7.2.1. Collection foreign keys 7.2.2. Indexed collections 7.2.3. Collections of basic types and embeddable objects 7.3. Advanced collection mappings 7.3.1. 7.3.2. 7.3.3. 7.3.4. 7.3.5. Sorted collections Bidirectional associations Bidirectional associations with indexed collections Ternary associations
U s i n ga n< i d b a g >
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
2/215
12/30/13
8. Association Mappings 8.1. Introduction
8.2. Unidirectional associations 8.2.1. Many-to-one 8.2.2. One-to-one 8.2.3. One-to-many 8.3. Unidirectional associations with join tables 8.3.1. One-to-many 8.3.2. Many-to-one 8.3.3. One-to-one 8.3.4. Many-to-many 8.4. Bidirectional associations 8.4.1. one-to-many / many-to-one 8.4.2. One-to-one 8.5. Bidirectional associations with join tables 8.5.1. one-to-many / many-to-one 8.5.2. one to one 8.5.3. Many-to-many 8.6. More complex association mappings 9. Component Mapping 9.1. 9.2. 9.3. 9.4. 9.5. Dependent objects Collections of dependent objects Components as Map indices Components as composite identifiers Dynamic components
10. Inheritance mapping 10.1. The three strategies 10.1.1. 10.1.2. 10.1.3. 10.1.4. 10.1.5. 10.1.6. 10.1.7. Table per class hierarchy Table per subclass Table per subclass: using a discriminator Mixing table per class hierarchy with table per subclass Table per concrete class Table per concrete class using implicit polymorphism Mixing implicit polymorphism with other inheritance mappings
10.2. Limitations 11. Working with objects 11.1. 11.2. 11.3. 11.4. Hibernate object states Making objects persistent Loading an object Querying Executing queries Filtering collections Criteria queries Queries in native SQL
11.5. Modifying persistent objects 11.6. Modifying detached objects 11.7. Automatic state detection 11.8. Deleting persistent objects 11.9. Replicating object between two different datastores 11.10. Flushing the Session 11.11. Transitive persistence 11.12. Using metadata 12. Read-only entities 12.1. Making persistent entities read-only 12.1.1. 12.1.2. 12.1.3. 12.1.4. Entities of immutable classes Loading persistent entities as read-only Loading read-only entities from an HQL query/criteria Making a persistent entity read-only
12.2. Read-only affect on property type 12.2.1. Simple properties 12.2.2. Unidirectional associations 12.2.3. Bidirectional associations 13. Transactions and Concurrency 13.1. Session and transaction scopes
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
3/215
12/30/13
13.1.1. Unit of work
16. HQL: The Hibernate Query Language 16.1. Case Sensitivity 16.2. The from clause 16.3. Associations and joins 16.4. Forms of join syntax 16.5. Referring to identifier property 16.6. The select clause 16.7. Aggregate functions 16.8. Polymorphic queries 16.9. The where clause 16.10. Expressions 16.11. The order by clause 16.12. The group by clause 16.13. Subqueries 16.14. HQL examples 16.15. Bulk update and delete 16.16. Tips & Tricks 16.17. Components 16.18. Row value constructor syntax 17. Criteria Queries 17.1. Creating a C r i t e r i ainstance 17.2. Narrowing the result set 17.3. Ordering the results 17.4. Associations 17.5. Dynamic association fetching 17.6. Components 17.7. Collections 17.8. Example queries 17.9. Projections, aggregation and grouping 17.10. Detached queries and subqueries 17.11. Queries by natural identifier 18. Native SQL 18.1. Using a S Q L Q u e r y 18.1.1. 18.1.2. 18.1.3. 18.1.4. 18.1.5. 18.1.6. 18.1.7. Scalar queries Entity queries Handling associations and collections Returning multiple entities Returning non-managed entities Handling inheritance Parameters
18.2. Named SQL queries 18.2.1. Using return-property to explicitly specify column/alias names 18.2.2. Using stored procedures for querying
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
4/215
12/30/13
20.7. Monitoring performance 20.7.1. Monitoring a SessionFactory 20.7.2. Metrics 21. Toolset Guide 21.1. Automatic schema generation 21.1.1. 21.1.2. 21.1.3. 21.1.4. 21.1.5. 21.1.6. 21.1.7. 21.1.8. Customizing the schema Running the tool Properties Using Ant Incremental schema updates Using Ant for incremental schema updates Schema validation Using Ant for schema validation
22. Additional modules 22.1. Bean Validation 22.1.1. 22.1.2. 22.1.3. 22.1.4. Adding Bean Validation Configuration Catching violations Database schema
22.2. Hibernate Search 22.2.1. Description 22.2.2. Integration with Hibernate Annotations 23. Example: Parent/Child 23.1. 23.2. 23.3. 23.4. A note about collections Bidirectional one-to-many Cascading life cycle Cascades and u n s a v e d v a l u e
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
5/215
12/30/13
24.1. Persistent Classes
3.9. Hibernate Log Categories 3.10. JTA TransactionManagers 10.1. Features of inheritance mappings 12.1. Affect of read-only entity on property types 18.1. Alias injection names 20.1. Cache Providers 20.2. Cache Concurrency Strategy Support 21.1. Summary 21.2. S c h e m a E x p o r tCommand Line Options 21.3. SchemaExport Connection Properties 21.4. S c h e m a U p d a t eCommand Line Options 21.5. S c h e m a V a l i d a t o rCommand Line Options List of Examples 4.1. Simple POJO representing a cat 4.2. Disabling proxies in h b m . x m l 4.3. Disabling proxies in annotations 4.4. Proxying an interface in h b m . x m l 4.5. Proxying an interface in annotations 4.6. Specify custom tuplizers in annotations 4.7. Specify custom tuplizers in h b m . x m l 5.1. 5.2. 5.3. 5.4. 6.1. 6.2. 6.3. 6.4. 6.5. 7.1. 7.2. 7.3. 7.4. 7.5. 7.6. 7.7. @NotFound annotation @OnDelete annotation @ForeignKey annotation One to One association Defining and registering the custom Type Defining the custom UserType Defining the custom CompositeUserType Overriding the standard S t r i n g T y p e Snippet from BasicType.java Hibernate uses its own collection implementations Collection mapping using @OneToMany and @JoinColumn Collection mapping using @OneToMany and @JoinTable Mapping a Set using <set> options of <one-to-many> element Elements of the <map> mapping Ordered lists using @ O r d e r B y
7.8. Explicit index column using @ O r d e r C o l u m n 7.9. index-list element for indexed collections in xml mapping 7.10. Use of target entity property as map key via @ M a p K e y 7.11. Map key as basic type using @ M a p K e y C o l u m n 7.12. map-key xml mapping element 7.13. map-key-many-to-many
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
6/215
12/30/13
18.8. Implicit result set mapping 18.9. Using dot notation in @FieldResult for specifying associations 18.10. Scalar values via @ C o l u m n R e s u l t 18.11. Custom CRUD via annotations 18.12. Custom CRUD XML 18.13. Overriding SQL statements for collections using annotations 18.14. Overriding SQL statements for secondary tables 18.15. Stored procedures and their return value 19.1. @FilterDef and @Filter annotations 19.2. Using @ F i l t e r J o i n T a b l efor filterting on the association table 19.3. Defining a filter definition via < f i l t e r d e f > 19.4. Attaching a filter to a class or collection using < f i l t e r > 20.1. Specifying a fetch profile using @ F e t c h P r o f i l e 20.2. Specifying a fetch profile using < f e t c h p r o f i l e >outside < c l a s s >node 20.3. Specifying a fetch profile using < f e t c h p r o f i l e >inside < c l a s s >node 20.4. Activating a fetch profile for a given S e s s i o n 20.5. Definition of cache concurrency strategy via @ C a c h e 20.6. Caching collections using annotations 20.7. @ C a c h eannotation with attributes 20.8. The Hibernate < c a c h e >mapping element 20.9. Explcitly evicting a cached instance from the first level cache using S e s s i o n . e v i c t ( ) 20.10. Second-level cache eviction via S e s s i o n F a c t o t y . e v i c t ( ) and S e s s i o n F a c y o r y . e v i c t C o l l e c t i o n ( ) 20.11. Browsing the second-level cache entries via the S t a t i s t i c sAPI 20.12. Enabling Hibernate statistics 22.1. Using custom groups for validation
Preface
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). See http://en.wikipedia.org/wiki/Object-relational_mapping for a good high-level discussion.
Note
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741 7/215
12/30/13
Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities. It can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC. Hibernates 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 processing using SQL and JDBC. However, unlike many other persistence solutions, Hibernate does not hide the power of SQL from you and guarantees that your investment in relational technology and knowledge 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, 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 representation to a graph of objects. If you are new to Hibernate and Object/Relational Mapping or even Java, please follow these steps: 1. Read Chapter 1, Tutorial for a tutorial with step-by-step instructions. The source code for the tutorial is included in the distribution in the d o c / r e f e r e n c e / t u t o r i a l /directory. 2. Read Chapter 2, Architecture to understand the environments where Hibernate can be used. 3. View the e g / directory in the Hibernate distribution. It contains a simple standalone application. Copy your JDBC driver to the l i b /directory and edit e t c / h i b e r n a t e . p r o p e r t i e s , specifying correct values for your database. From a command prompt in the distribution directory, type a n t e g (using Ant), or under Windows, type b u i l de g . 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. Also visit 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 and various 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 http://hibernate.org/issuetracker.html details. or implementing enhancements. Again, see
http://hibernate.org/community.html lists 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 channels for both user and developer discussions. Helping improve or translate this documentation. Contact us on the developer mailing list if you have interest. Evangelizing Hibernate within your organization.
Chapter 1. Tutorial
Table of Contents 1.1. Part 1 - The first Hibernate Application 1.1.1. 1.1.2. 1.1.3. 1.1.4. 1.1.5. 1.1.6. 1.1.7. Setup The first class The mapping file Hibernate configuration Building with Maven Startup and helpers Loading and storing objects
1.2. Part 2 - Mapping associations 1.2.1. 1.2.2. 1.2.3. 1.2.4. 1.2.5. 1.2.6. Mapping the Person class A unidirectional Set-based association Working the association Collection of values Bi-directional associations Working bi-directional links
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
8/215
12/30/13
Important
This tutorial expects the user have knowledge of both Java and SQL. If you have a limited knowledge of JAVA or SQL, it is advised that you start with a good introduction to that technology prior to attempting to learn Hibernate.
Note
The distribution contains another example application under the
t u t o r i a l / e gproject source directory.
Note
Although you can use whatever database you feel comfortable using, we will use HSQLDB (an in-memory, Java database) to avoid describing installation/setup of any particular database servers.
1.1.1. Setup
The first thing we need to do is to set up the development environment. We will be using the "standard layout" advocated by alot of build tools such as Maven. Maven, in particular, has a good resource describing this layout. As this tutorial is to be a web application, we will be creating and making use of s r c / m a i n / j a v a ,s r c / m a i n / r e s o u r c e sand s r c / m a i n / w e b a p pdirectories. We will be using Maven in this tutorial, taking advantage of its transitive dependency management capabilities as well as the ability of many IDEs to automatically set up a project for us based on the maven descriptor.
< p r o j e c tx m l n s = " h t t p : / / m a v e n . a p a c h e . o r g / P O M / 4 . 0 . 0 " x m l n s : x s i = " h t t p : / / w w w . w 3 . o r g / 2 0 0 1 / X M L S c h e m a i n s t a n c e " x s i : s c h e m a L o c a t i o n = " h t t p : / / m a v e n . a p a c h e . o r g / P O M / 4 . 0 . 0h t t p : / / m a v e n . a p a c h e . o r g / x s d / m a v e n 4 . 0 . 0 . x s d " > < m o d e l V e r s i o n > 4 . 0 . 0 < / m o d e l V e r s i o n > < g r o u p I d > o r g . h i b e r n a t e . t u t o r i a l s < / g r o u p I d > < a r t i f a c t I d > h i b e r n a t e t u t o r i a l < / a r t i f a c t I d > < v e r s i o n > 1 . 0 . 0 S N A P S H O T < / v e r s i o n > < n a m e > F i r s tH i b e r n a t eT u t o r i a l < / n a m e > < b u i l d > < ! -w ed o n tw a n tt h ev e r s i o nt ob ep a r to ft h eg e n e r a t e dw a rf i l en a m e> < f i n a l N a m e > $ { a r t i f a c t I d } < / f i n a l N a m e > < / b u i l d > < d e p e n d e n c i e s > < d e p e n d e n c y > < g r o u p I d > o r g . h i b e r n a t e < / g r o u p I d > < a r t i f a c t I d > h i b e r n a t e c o r e < / a r t i f a c t I d > < / d e p e n d e n c y > < ! -B e c a u s et h i si saw e ba p p ,w ea l s oh a v ead e p e n d e n c yo nt h es e r v l e ta p i .> < d e p e n d e n c y > < g r o u p I d > j a v a x . s e r v l e t < / g r o u p I d > < a r t i f a c t I d > s e r v l e t a p i < / a r t i f a c t I d > < / d e p e n d e n c y > < ! -H i b e r n a t eu s e ss l f 4 jf o rl o g g i n g ,f o ro u rp u r p o s e sh e r eu s et h es i m p l eb a c k e n d> < d e p e n d e n c y > < g r o u p I d > o r g . s l f 4 j < / g r o u p I d > < a r t i f a c t I d > s l f 4 j s i m p l e < / a r t i f a c t I d > < / d e p e n d e n c y > < d e p e n d e n c y > < g r o u p I d > j a v a s s i s t < / g r o u p I d > < a r t i f a c t I d > j a v a s s i s t < / a r t i f a c t I d >
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
9/215
12/30/13
Tip
It is not a requirement to use Maven. If you wish to use something else to build this tutorial (such as Ant), the layout will remain the same. The only change is that you will need to manually account for all the needed dependencies. If you use something like Ivy providing transitive dependency management you would still use the dependencies mentioned below. Otherwise, you'd need to grab all dependencies, both explicit and transitive, and add them to the project's classpath. If working from the Hibernate distribution bundle, this would mean h i b e r n a t e 3 . j a r , all artifacts in the
l i b / r e q u i r e d
directory
and
all
files
from
either
the
will need both the servlet-api jar and one of the slf4j logging backends.
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 not required. Hibernate can also access fields directly, the benefit of accessor methods is robustness for refactoring. The i dproperty 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, especially web applications, need to 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 should be private. Only Hibernate will assign identifiers when an object is saved. Hibernate can access public, private, and protected accessor methods, as well as public, private and 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 or public visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation. Save this file to the s r c / m a i n / j a v a / o r g / h i b e r n a t e / t u t o r i a l / d o m a i ndirectory.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
10/215
12/30/13
Hibernate DTD is sophisticated. You can use it for auto-completion of XML mapping elements and attributes in your editor or IDE. Opening up the DTD file in your text editor is the easiest way to get an overview of all elements and attributes, and to view the defaults, as well as some comments. Hibernate will not load the DTD file from the web, but first look it up from the classpath of the application. The DTD file is included in h i b e r n a t e c o r e . j a r (it is also included in the h i b e r n a t e 3 . j a r , if using the distribution bundle).
Important
We will omit the DTD declaration in future examples to shorten the code. It is, of course, not optional.
Between the two h i b e r n a t e m a p p i n g tags, include a c l a s s element. All persistent entity classes (again, there might be dependent classes later on, which are not first-class entities) need a mapping to a table in the SQL database:
< h i b e r n a t e m a p p i n gp a c k a g e = " o r g . h i b e r n a t e . t u t o r i a l . d o m a i n " > < c l a s sn a m e = " E v e n t "t a b l e = " E V E N T S " > < / c l a s s > < / h i b e r n a t e m a p p i n g >
So far we have told Hibernate how to persist and load object of class E v e n t to the table E V E N T S . Each instance is now represented by a row in that table. Now we can continue by mapping the unique identifier property to the tables primary key. As we do not want to care about handling this identifier, we configure Hibernate's identifier generation strategy for a surrogate primary key column:
< h i b e r n a t e m a p p i n gp a c k a g e = " o r g . h i b e r n a t e . t u t o r i a l . d o m a i n " > < c l a s sn a m e = " E v e n t "t a b l e = " E V E N T S " > < i dn a m e = " i d "c o l u m n = " E V E N T _ I D " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < / c l a s s > < / h i b e r n a t e m a p p i n g >
The i d element is the declaration of the identifier property. The n a m e = " i d " mapping attribute declares the name of the JavaBean property and tells Hibernate to use the g e t I d ( ) and s e t I d ( ) methods to access the property. The column attribute tells Hibernate which column of the E V E N T S table holds the primary key value. The nested g e n e r a t o relement specifies the identifier generation strategy (aka how are identifier values generated?). In this case we choose n a t i v e , which offers a level of portability depending on the configured database dialect. Hibernate supports database generated, globally unique, as well as application assigned, identifiers. Identifier value generation is also one of Hibernate's many extension points and you can plugin in your own strategy.
Tip
n a t i v e is no longer consider the best strategy in terms of portability. for
Lastly, we need to tell Hibernate about the remaining entity class properties. By default, no properties of the class are considered persistent:
< h i b e r n a t e m a p p i n gp a c k a g e = " o r g . h i b e r n a t e . t u t o r i a l . d o m a i n " > < c l a s sn a m e = " E v e n t "t a b l e = " E V E N T S " > < i dn a m e = " i d "c o l u m n = " E V E N T _ I D " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < p r o p e r t yn a m e = " d a t e "t y p e = " t i m e s t a m p "c o l u m n = " E V E N T _ D A T E " / > < p r o p e r t yn a m e = " t i t l e " / > < / c l a s s > < / h i b e r n a t e m a p p i n g >
Similar to the i d element, the n a m e attribute of the p r o p e r t y element tells Hibernate which getter and setter methods to use. In this case, Hibernate will search for g e t D a t e ( ) , s e t D a t e ( ) , g e t T i t l e ( ) and
s e t T i t l e ( )methods.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
11/215
12/30/13
Note
Why does the d a t e property mapping include the c o l u m n attribute, but the
t i t l edoes not? Without the c o l u m nattribute, Hibernate by default uses the
property name as the column name. This works for t i t l e , however, d a t e is a reserved keyword in most databases so you will need to map it to a different name.
The t i t l emapping also lacks a t y p eattribute. The types declared and used in the mapping files are not Java data types; they are not SQL database types either. These types are 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 t y p eattribute 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 d a t e property. Hibernate cannot know if the property, which is of j a v a . u t i l . D a t e , should map to a SQL d a t e ,t i m e s t a m p , or t i m e column. Full date and time information is preserved by mapping the property with a t i m e s t a m pconverter.
Tip
Hibernate makes this mapping type determination using reflection when the mapping files are processed. This can take time and resources, so if startup performance is important you should consider explicitly defining the type to use.
Note
We do this so 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 will connect later. If you want to start with a fresh database during this tutorial, shutdown HSQLDB, delete all files in the t a r g e t / d a t a directory, and start HSQLDB again. Hibernate will be connecting to the database on behalf of your application, so it needs to know how to obtain connections. For this tutorial we will b e using a standalone connection pool (as opposed to a j a v a x . s q l . D a t a S o u r c e ). Hibernate comes with support for two third-party open source JDBC connection pools: c3p0 and proxool. However, we will be using the Hibernate built-in connection pool for this tutorial.
Caution
The built-in Hibernate connection pool is in no way intended for production use. It lacks several features found on any decent connection pool.
file:
< ? x m lv e r s i o n = ' 1 . 0 'e n c o d i n g = ' u t f 8 ' ? > < ! D O C T Y P Eh i b e r n a t e c o n f i g u r a t i o nP U B L I C " / / H i b e r n a t e / H i b e r n a t eC o n f i g u r a t i o nD T D3 . 0 / / E N " " h t t p : / / w w w . h i b e r n a t e . o r g / d t d / h i b e r n a t e c o n f i g u r a t i o n 3 . 0 . d t d " > < h i b e r n a t e c o n f i g u r a t i o n > < s e s s i o n f a c t o r y > < ! -D a t a b a s ec o n n e c t i o ns e t t i n g s> < p r o p e r t yn a m e = " c o n n e c t i o n . d r i v e r _ c l a s s " > o r g . h s q l d b . j d b c D r i v e r < / p r o p e r t y > < p r o p e r t yn a m e = " c o n n e c t i o n . u r l " > j d b c : h s q l d b : h s q l : / / l o c a l h o s t < / p r o p e r t y > < p r o p e r t yn a m e = " c o n n e c t i o n . u s e r n a m e " > s a < / p r o p e r t y > < p r o p e r t yn a m e = " c o n n e c t i o n . p a s s w o r d " > < / p r o p e r t y > < ! -J D B Cc o n n e c t i o np o o l( u s et h eb u i l t i n )> < p r o p e r t yn a m e = " c o n n e c t i o n . p o o l _ s i z e " > 1 < / p r o p e r t y > < ! -S Q Ld i a l e c t> < p r o p e r t yn a m e = " d i a l e c t " > o r g . h i b e r n a t e . d i a l e c t . H S Q L D i a l e c t < / p r o p e r t y > < ! -E n a b l eH i b e r n a t e ' sa u t o m a t i cs e s s i o nc o n t e x tm a n a g e m e n t> < p r o p e r t yn a m e = " c u r r e n t _ s e s s i o n _ c o n t e x t _ c l a s s " > t h r e a d < / p r o p e r t y >
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
12/215
12/30/13
Note
Notice that this configuration file specifies a different DTD
You configure Hibernate's S e s s i o n F a c t o r y . SessionFactory is a global factory responsible for a particular database. If you have several databases, for easier startup you should use several < s e s s i o n f a c t o r y > configurations in several configuration files. The first four p r o p e r t yelements contain the necessary configuration for the JDBC connection. The dialect
p r o p e r t yelement specifies the particular SQL variant Hibernate generates.
Tip
In most cases, Hibernate is able to properly determine which dialect to use. See Section 27.3, Dialect resolution for more information.
Hibernate's automatic session management for persistence contexts is particularly useful in this context. The h b m 2 d d l . a u t ooption turns on automatic generation of database schemas directly into the database. This can also be turned off by removing the configuration option, or redirected to a file with the help of the S c h e m a E x p o r tAnt task. Finally, add the mapping file(s) for persistent classes to the configuration. Save this file as h i b e r n a t e . c f g . x m linto the s r c / m a i n / r e s o u r c e sdirectory.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
13/215
12/30/13
Save this code as s r c / m a i n / j a v a / o r g / h i b e r n a t e / t u t o r i a l / u t i l / H i b e r n a t e U t i l . j a v a This class not only produces the global o r g . h i b e r n a t e . S e s s i o n F a c t o r yreference in its static initializer; it also hides the fact that it uses a static singleton. We might just as well have looked up the
o r g . h i b e r n a t e . S e s s i o n F a c t o r y reference from JNDI in an application server or any other location for
that matter. If you give the o r g . h i b e r n a t e . S e s s i o n F a c t o r ya name in your configuration, Hibernate will try to bind it to JNDI under that name after it has been built. Another, better option is to use a JMX deployment and let the JMX-capable container instantiate and bind a H i b e r n a t e S e r v i c e to JNDI. Such advanced options are discussed later. You now need to configure a logging system. Hibernate uses commons logging and provides two choices: Log4j and JDK 1.4 logging. Most developers prefer Log4j: copy l o g 4 j . p r o p e r t i e s from the Hibernate distribution in the e t c / directory to your s r c directory, next to h i b e r n a t e . c f g . x m l . If you prefer to have more verbose output than that provided in the example configuration, you can 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.
In c r e a t e A n d S t o r e E v e n t ( ) we created a new E v e n t object and handed it over to Hibernate. At that point, Hibernate takes care of the SQL and executes an I N S E R Ton the database. Ao r g . h i b e r n a t e . S e s s i o nis designed to represent a single unit of work (a single atomic piece of work to be performed). For now we will keep things simple and assume a one-to-one granularity between a Hibernate o r g . h i b e r n a t e . S e s s i o n and a database transaction. To shield our code from the actual underlying transaction system we use the Hibernate o r g . h i b e r n a t e . T r a n s a c t i o n API. In this particular case we are using JDBC-based transactional semantics, but it could also run with JTA. What does s e s s i o n F a c t o r y . g e t C u r r e n t S e s s i o n ( ) do? First, you can call it as many times and anywhere you like once you get hold of your o r g . h i b e r n a t e . S e s s i o n F a c t o r y . The g e t C u r r e n t S e s s i o n ( ) method always returns the "current" unit of work. Remember that we switched the configuration option for this mechanism to "thread" in our s r c / m a i n / r e s o u r c e s / h i b e r n a t e . c f g . x m l ? Due to that setting, the context of a current unit of work is bound to the current Java thread that executes the application.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
14/215
12/30/13
Important
Hibernate offers three methods of current session tracking. The "thread" based method is not intended for production use; it is merely useful for prototyping and tutorials such as this one. Current session tracking is discussed in more detail later on.
A o r g . h i b e r n a t e . S e s s i o n begins when the first call to g e t C u r r e n t S e s s i o n ( ) is made for the current thread. It is then bound by Hibernate to the current thread. When the transaction ends, either through commit or rollback, Hibernate automatically unbinds the o r g . h i b e r n a t e . S e s s i o n from the thread and closes it for you. If you call g e t C u r r e n t S e s s i o n ( ) again, you get a new o r g . h i b e r n a t e . S e s s i o n and can start a new unit of work. Related to the unit of work scope, should the Hibernate o r g . h i b e r n a t e . S e s s i o nbe used to execute one or several database operations? The above example uses one o r g . h i b e r n a t e . S e s s i o n for one operation. However this is pure coincidence; the example is just not complex enough to show any other approach. The scope of a Hibernate o r g . h i b e r n a t e . S e s s i o nis flexible but you should never design your application to use a new Hibernate o r g . h i b e r n a t e . S e s s i o nfor every database operation. Even though it is used in the following examples, consider session-per-operation an anti-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 handling and demarcation. The previous example also skipped any error handling and rollback. To run this, we will make use of the Maven exec plugin to call our class with the necessary classpath setup: mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" Dexec.args="store"
Note
You 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:
[ j a v a ]H i b e r n a t e :i n s e r ti n t oE V E N T S( E V E N T _ D A T E ,t i t l e ,E V E N T _ I D )v a l u e s( ? ,? ,? )
This is the I N S E R Texecuted by Hibernate. To list stored events an option is added to the main method:
i f( a r g s [ 0 ] . e q u a l s ( " s t o r e " ) ){ m g r . c r e a t e A n d S t o r e E v e n t ( " M yE v e n t " ,n e wD a t e ( ) ) ; } e l s ei f( a r g s [ 0 ] . e q u a l s ( " l i s t " ) ){ L i s te v e n t s=m g r . l i s t E v e n t s ( ) ; f o r( i n ti=0 ;i<e v e n t s . s i z e ( ) ;i + + ){ E v e n tt h e E v e n t=( E v e n t )e v e n t s . g e t ( i ) ; S y s t e m . o u t . p r i n t l n ( " E v e n t :"+t h e E v e n t . g e t T i t l e ( )+"T i m e :"+t h e E v e n t . g e t D a t e ( ) ) ; } }
A new l i s t E v e n t s ( )m e t h o di sa l s oa d d e d :
p r i v a t eL i s tl i s t E v e n t s ( ){ S e s s i o ns e s s i o n=H i b e r n a t e U t i l . g e t S e s s i o n F a c t o r y ( ) . g e t C u r r e n t S e s s i o n ( ) ; s e s s i o n . b e g i n T r a n s a c t i o n ( ) ; L i s tr e s u l t=s e s s i o n . c r e a t e Q u e r y ( " f r o mE v e n t " ) . l i s t ( ) ; s e s s i o n . g e t T r a n s a c t i o n ( ) . c o m m i t ( ) ; r e t u r nr e s u l t ; }
Here, we are using a Hibernate Query Language (HQL) query to load all existing E v e n t objects from the database. Hibernate will generate the appropriate SQL, send it to the database and populate E v e n t objects with the data. You can create more complex queries with HQL. See Chapter 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"
12/30/13
Save this to a file named s r c / m a i n / j a v a / o r g / h i b e r n a t e / t u t o r i a l / d o m a i n / P e r s o n . j a v a Next, create the new mapping file as
s r c / m a i n / r e s o u r c e s / o r g / h i b e r n a t e / t u t o r i a l / d o m a i n / P e r s o n . h b m . x m l < h i b e r n a t e m a p p i n gp a c k a g e = " o r g . h i b e r n a t e . t u t o r i a l . d o m a i n " > < c l a s sn a m e = " P e r s o n "t a b l e = " P E R S O N " > < i dn a m e = " i d "c o l u m n = " P E R S O N _ I D " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < p r o p e r t yn a m e = " a g e " / > < p r o p e r t yn a m e = " f i r s t n a m e " / > < p r o p e r t yn a m e = " l a s t n a m e " / > < / c l a s s > < / h i b e r n a t e m a p p i n g >
Create an association between these two entities. Persons can participate in events, and events have participants. The design questions you have to deal with are: directionality, multiplicity, and collection behavior.
Before mapping this association, let's consider the other side. We could just keep this unidirectional or create another collection on the E v e n t , if we wanted to be able to navigate it from both directions. This is not necessary, from a functional perspective. You can always execute an explicit 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 both sides is called a many-to-many association. Hence, we use Hibernate's many-to-many mapping:
< c l a s sn a m e = " P e r s o n "t a b l e = " P E R S O N " > < i dn a m e = " i d "c o l u m n = " P E R S O N _ I D " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < p r o p e r t yn a m e = " a g e " / > < p r o p e r t yn a m e = " f i r s t n a m e " / > < p r o p e r t yn a m e = " l a s t n a m e " / > < s e tn a m e = " e v e n t s "t a b l e = " P E R S O N _ E V E N T " > < k e yc o l u m n = " P E R S O N _ I D " / > < m a n y t o m a n yc o l u m n = " E V E N T _ I D "c l a s s = " E v e n t " / > < / s e t > < / c l a s s >
Hibernate supports a broad range of collection mappings, a s e t being most common. For a many-tomany association, or n:m entity relationship, an association table is required. Each row in this table represents a link between a person and an event. The table name is declared using the t a b l e attribute of the s e t element. The identifier column name in the association, for the person side, is defined with the k e y element, the column name for the event's side with the c o l u m n attribute of the m a n y t o m a n y . You also have to tell Hibernate the class of the objects in your collection (the class on the other side of
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
16/215
12/30/13
After loading a P e r s o n and an E v e n t , simply modify the collection using the normal collection methods. There is no explicit call to u p d a t e ( ) or s a v e ( ) ; Hibernate automatically detects that the collection has been modified and needs to be updated. This is called automatic dirty checking. You can also try it by modifying the name or the date property of any of your objects. As long as they are in persistent state, that is, bound to a particular Hibernate o r g . h i b e r n a t e . S e s s i o n , Hibernate monitors any changes and executes SQL in a write-behind fashion. The process of synchronizing the memory state with the database, usually only at the end of a unit of work, is called flushing. In our 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 of a o r g . h i b e r n a t e . S e s s i o n , when it is not in persistent state (if it was persistent before, this state is called detached). You can even modify a collection when it is detached:
p r i v a t ev o i da d d P e r s o n T o E v e n t ( L o n gp e r s o n I d ,L o n ge v e n t I d ){ S e s s i o ns e s s i o n=H i b e r n a t e U t i l . g e t S e s s i o n F a c t o r y ( ) . g e t C u r r e n t S e s s i o n ( ) ; s e s s i o n . b e g i n T r a n s a c t i o n ( ) ; P e r s o na P e r s o n=( P e r s o n )s e s s i o n . c r e a t e Q u e r y ( " s e l e c tpf r o mP e r s o npl e f tj o i nf e t c hp . e v e n t sw h e r ep . i d=: p i d " ) . s e t P a r a m e t e r ( " p i d " ,p e r s o n I d ) . u n i q u e R e s u l t ( ) ;/ /E a g e rf e t c ht h ec o l l e c t i o ns ow ec a nu s ei td e t a c h e d E v e n ta n E v e n t=( E v e n t )s e s s i o n . l o a d ( E v e n t . c l a s s ,e v e n t I d ) ; s e s s i o n . g e t T r a n s a c t i o n ( ) . c o m m i t ( ) ; / /E n do ff i r s tu n i to fw o r k a P e r s o n . g e t E v e n t s ( ) . a d d ( a n E v e n t ) ;/ /a P e r s o n( a n di t sc o l l e c t i o n )i sd e t a c h e d / /B e g i ns e c o n du n i to fw o r k S e s s i o ns e s s i o n 2=H i b e r n a t e U t i l . g e t S e s s i o n F a c t o r y ( ) . g e t C u r r e n t S e s s i o n ( ) ; s e s s i o n 2 . b e g i n T r a n s a c t i o n ( ) ; s e s s i o n 2 . u p d a t e ( a P e r s o n ) ;/ /R e a t t a c h m e n to fa P e r s o n s e s s i o n 2 . g e t T r a n s a c t i o n ( ) . c o m m i t ( ) ; }
The call to u p d a t emakes 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 includes any 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 into your own application. Complete this exercise by adding a new action to the main method of the E v e n t M a n a g e r and call it from the command line. If you need the identifiers of a person and an event - the s a v e ( ) method returns it (you might have to modify some of the previous methods to return that identifier):
e l s ei f( a r g s [ 0 ] . e q u a l s ( " a d d p e r s o n t o e v e n t " ) ){ L o n ge v e n t I d=m g r . c r e a t e A n d S t o r e E v e n t ( " M yE v e n t " ,n e wD a t e ( ) ) ; L o n gp e r s o n I d=m g r . c r e a t e A n d S t o r e P e r s o n ( " F o o " ," B a r " ) ; m g r . a d d P e r s o n T o E v e n t ( p e r s o n I d ,e v e n t I d ) ; S y s t e m . o u t . p r i n t l n ( " A d d e dp e r s o n"+p e r s o n I d+"t oe v e n t"+e v e n t I d ) ; }
This is an example of an association between two equally important classes : two entities. As mentioned earlier, there are other classes and types in a typical model, usually "less important". Some you have already seen, like an i n t or a j a v a . l a n g . S t r i n g . We call these classes value types , and their instances depend on a particular entity. Instances of these types do not have their own identity, nor are they shared between entities. Two persons do not reference the same f i r s t n a m e object, even if they have the same first name. Value types cannot only be found in the JDK , but you can also write
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
17/215
12/30/13
The difference compared with the earlier mapping is the use of the e l e m e n t part which tells Hibernate that the collection does not contain references to another entity, but is rather a collection whose elements are values types, here specifically of type s t r i n g . The lowercase name tells you it is a Hibernate mapping type/converter. Again the t a b l e attribute of the s e t element determines the table name for the collection. The k e yelement defines the foreign-key column name in the collection table. The
c o l u m n attribute in the e l e m e n t element defines the column name where the email address values will
You can see that the primary key of the collection table is in fact a composite key that uses both columns. This also implies that there cannot be duplicate email addresses per person, which is exactly 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 and events. It is the same code in Java:
p r i v a t ev o i da d d E m a i l T o P e r s o n ( L o n gp e r s o n I d ,S t r i n ge m a i l A d d r e s s ){ S e s s i o ns e s s i o n=H i b e r n a t e U t i l . g e t S e s s i o n F a c t o r y ( ) . g e t C u r r e n t S e s s i o n ( ) ; s e s s i o n . b e g i n T r a n s a c t i o n ( ) ; P e r s o na P e r s o n=( P e r s o n )s e s s i o n . l o a d ( P e r s o n . c l a s s ,p e r s o n I d ) ; / /a d d i n gt ot h ee m a i l A d d r e s sc o l l e c t i o nm i g h tt r i g g e ral a z yl o a do ft h ec o l l e c t i o n a P e r s o n . g e t E m a i l A d d r e s s e s ( ) . a d d ( e m a i l A d d r e s s ) ; s e s s i o n . g e t T r a n s a c t i o n ( ) . c o m m i t ( ) ; }
This time we did not use a fetch query to initialize the collection. Monitor the SQL log and try to optimize this with an eager fetch.
Note
A relational database is more flexible than a network programming language, in that it does not need a navigation direction; data can be viewed and retrieved in any possible way.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
18/215
12/30/13
These are normal s e t mappings in both mapping documents. Notice that the column names in k e y and
m a n y t o m a n y swap
in
both
mapping
documents. The
most
important
addition
here
is
the
What this means is that Hibernate should take the other side, the P e r s o n class, when it needs to find out information about the link between the two. This will be a lot easier to understand once you see how the bi-directional link between our two entities is created.
The get and set methods for the collection are now protected. This allows classes in the same package and subclasses to still access the methods, but prevents everybody else from altering the collections directly. Repeat the steps for the collection on the other side. What about the i n v e r s emapping attribute? For you, and for Java, a bi-directional link is simply a matter of setting the references on both sides correctly. Hibernate, however, does not have enough information to correctly arrange SQL I N S E R T and U P D A T E statements (to avoid constraint violations). Making one side of the association i n v e r s etells Hibernate to consider it a mirror of the other side. That is all that is necessary for Hibernate to resolve any issues that arise when transforming a directional navigation model to a SQL database schema. The rules are straightforward: all bi-directional associations need one side as i n v e r s e . In a one-to-many association it has to be the many-side, and in many-to-many association you can select either side.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
19/215
12/30/13
/ /I m p o r t s
Save this servlet as s r c / m a i n / j a v a / o r g / h i b e r n a t e / t u t o r i a l / w e b / E v e n t M a n a g e r S e r v l e t . j a v a The pattern applied here is called session-per-request. When a request hits the servlet, a new Hibernate S e s s i o n is opened through the first call to g e t C u r r e n t S e s s i o n ( ) on the S e s s i o n F a c t o r y . A database transaction is then started. All data access occurs inside a transaction irrespective of whether the data is read or written. Do not use the auto-commit mode in applications. Do not use a new Hibernate S e s s i o n for every database operation. Use one Hibernate S e s s i o n that is scoped to the whole request. Use g e t C u r r e n t S e s s i o n ( ) , so that it is automatically bound to the current Java thread. Next, the possible actions of the request are processed and the response HTML is rendered. We will get to that part soon. Finally, the unit of work ends when processing and rendering are complete. If any problems occurred during processing or rendering, an exception will be thrown and the database transaction rolled back. This completes the s e s s i o n p e r r e q u e s t pattern. Instead of the transaction demarcation code in every servlet, you could also write a servlet filter. See the Hibernate website and Wiki for more information about this pattern called Open Session in View. You will need it as soon as you consider rendering your view in JSP, not in a servlet.
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 prints an HTML header and a footer. Inside this page, an HTML form for event entry and a list of all events in the database are printed. The first method is trivial and only outputs HTML:
p r i v a t ev o i dp r i n t E v e n t F o r m ( P r i n t W r i t e ro u t ){ o u t . p r i n t l n ( " < h 2 > A d dn e we v e n t : < / h 2 > " ) ; o u t . p r i n t l n ( " < f o r m > " ) ; o u t . p r i n t l n ( " T i t l e :< i n p u tn a m e = ' e v e n t T i t l e 'l e n g t h = ' 5 0 ' / > < b r / > " ) ; o u t . p r i n t l n ( " D a t e( e . g .2 4 . 1 2 . 2 0 0 9 ) :< i n p u tn a m e = ' e v e n t D a t e 'l e n g t h = ' 1 0 ' / > < b r / > " ) ; o u t . p r i n t l n ( " < i n p u tt y p e = ' s u b m i t 'n a m e = ' a c t i o n 'v a l u e = ' s t o r e ' / > " ) ;
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
20/215
12/30/13
}
The l i s t E v e n t s ( )method uses the Hibernate S e s s i o nbound to the current thread to execute a query:
p r i v a t ev o i dl i s t E v e n t s ( P r i n t W r i t e ro u t ,S i m p l e D a t e F o r m a td a t e F o r m a t t e r ){ L i s tr e s u l t=H i b e r n a t e U t i l . g e t S e s s i o n F a c t o r y ( ) . g e t C u r r e n t S e s s i o n ( ) . c r e a t e C r i t e r i a ( E v e n t . c l a s s ) . l i s t ( ) ; i f( r e s u l t . s i z e ( )>0 ){ o u t . p r i n t l n ( " < h 2 > E v e n t si nd a t a b a s e : < / h 2 > " ) ; o u t . p r i n t l n ( " < t a b l eb o r d e r = ' 1 ' > " ) ; o u t . p r i n t l n ( " < t r > " ) ; o u t . p r i n t l n ( " < t h > E v e n tt i t l e < / t h > " ) ; o u t . p r i n t l n ( " < t h > E v e n td a t e < / t h > " ) ; o u t . p r i n t l n ( " < / t r > " ) ; I t e r a t o ri t=r e s u l t . i t e r a t o r ( ) ; w h i l e( i t . h a s N e x t ( ) ){ E v e n te v e n t=( E v e n t )i t . n e x t ( ) ; o u t . p r i n t l n ( " < t r > " ) ; o u t . p r i n t l n ( " < t d > "+e v e n t . g e t T i t l e ( )+" < / t d > " ) ; o u t . p r i n t l n ( " < t d > "+d a t e F o r m a t t e r . f o r m a t ( e v e n t . g e t D a t e ( ) )+" < / t d > " ) ; o u t . p r i n t l n ( " < / t r > " ) ; } o u t . p r i n t l n ( " < / t a b l e > " ) ; } }
Finally, the s t o r e action is dispatched to the c r e a t e A n d S t o r e E v e n t ( ) method, which also uses the
S e s s i o nof the current thread: p r o t e c t e dv o i dc r e a t e A n d S t o r e E v e n t ( S t r i n gt i t l e ,D a t et h e D a t e ){ E v e n tt h e E v e n t=n e wE v e n t ( ) ; t h e E v e n t . s e t T i t l e ( t i t l e ) ; t h e E v e n t . s e t D a t e ( t h e D a t e ) ; H i b e r n a t e U t i l . g e t S e s s i o n F a c t o r y ( ) . g e t C u r r e n t S e s s i o n ( ) . s a v e ( t h e E v e n t ) ; }
The servlet is now complete. A request to the servlet will be processed in a single S e s s i o n and
T r a n s a c t i o n . As earlier in the standalone application, Hibernate can automatically bind these objects to
the current thread of execution. This gives you the freedom to layer your code and access the S e s s i o n F a c t o r y in any way you like. Usually you would use a more sophisticated design and move the data access code into data access objects (the DAO pattern). See the Hibernate Wiki for more examples.
To build and deploy call m v np a c k a g e in your project directory and copy the h i b e r n a t e t u t o r i a l . w a r file into your Tomcat w e b a p p sdirectory.
Note
If you do not have Tomcat installed, download it from http://tomcat.apache.org/ and follow the installation instructions. Our application requires no changes to the standard Tomcat configuration.
Once
deployed
and
Tomcat
is
running,
access
the
application
at
Hibernate initialize when the first request hits your servlet (the static initializer in H i b e r n a t e U t i l is called) and to get the detailed output if any exceptions occurs.
1.4. Summary
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741 21/215
12/30/13
Chapter 2. Architecture
Table of Contents 2.1. Overview 2.1.1. Minimal architecture 2.1.2. Comprehensive architecture 2.1.3. Basic APIs 2.2. Contextual sessions
2.1. Overview
The diagram below provides a high-level view of the Hibernate architecture:
Unfortunately we cannot provide a detailed view of all possible runtime architectures. Hibernate is sufficiently flexible to be used in a number of ways in many, many architectures. We will, however, illustrate 2 specifically since they are extremes.
12/30/13
client
of
o r g . h i b e r n a t e . c o n n e c t i o n . C o n n e c t i o n P r o v i d e r .
Optionally maintains a s e c o n d l e v e l c a c h e of data that is reusable between transactions at a process or cluster level. Session ( o r g . h i b e r n a t e . S e s s i o n ) A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC j a v a . s q l . C o n n e c t i o n . Factory for o r g . h i b e r n a t e . T r a n s a c t i o n . Maintains a f i r s tl e v e lc a c h eof persistent the application's persistent objects and collections; this cache is used when navigating the object graph or looking up objects by identifier. Persistent objects and collections Short-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one o r g . h i b e r n a t e . S e s s i o n . Once the
o r g . h i b e r n a t e . S e s s i o n is closed, they will be detached and free to use in any application layer (for
example, directly as data transfer objects to and from presentation). Chapter 11, Working with objects discusses transient, persistent and detached object states. Transient and detached objects and collections Instances of persistent classes that are not currently associated with a o r g . h i b e r n a t e . S e s s i o n . They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed o r g . h i b e r n a t e . S e s s i o n . Chapter 11, Working with objects discusses transient, persistent and detached object states. Transaction ( o r g . h i b e r n a t e . T r a n s a c t i o n ) (Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A
o r g . h i b e r n a t e . S e s s i o n might span several o r g . h i b e r n a t e . T r a n s a c t i o n s in some cases. However,
transaction demarcation, either using the underlying API or o r g . h i b e r n a t e . T r a n s a c t i o n , is never optional. ConnectionProvider ( o r g . h i b e r n a t e . c o n n e c t i o n . C o n n e c t i o n P r o v i d e r ) (Optional) A factory for, and pool of, JDBC connections. It abstracts the application from underlying
j a v a x . s q l . D a t a S o u r c e or j a v a . s q l . D r i v e r M a n a g e r . It is not exposed to application, but it can be
extended and/or implemented by the developer. TransactionFactory ( o r g . h i b e r n a t e . T r a n s a c t i o n F a c t o r y ) (Optional) A factory for o r g . h i b e r n a t e . T r a n s a c t i o n instances. It is not exposed to the application, but it can be extended and/or implemented by the developer. Extension Interfaces Hibernate offers a range of optional extension interfaces you can implement to customize the behavior of your persistence layer. See the API documentation for details.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
23/215
12/30/13
sessions
are
tracked
by
execution. However, you are responsible to bind and unbind a S e s s i o n instance with static methods on this class: it does not open, flush, or close a S e s s i o n . The first two implementations provide a "one session - one database transaction" programming model. This is also known and used as session-per-request. The beginning and end of a Hibernate session is defined by the duration of a database transaction. If you use programmatic transaction demarcation in plain JSE without JTA, you are advised to use the Hibernate T r a n s a c t i o n API to hide the underlying transaction system from your code. If you use JTA, you can utilize the JTA interfaces to demarcate transactions. If you execute in an EJB container that supports CMT, transaction boundaries are defined declaratively and you do not need any transaction or session demarcation operations in your code. Refer to Chapter 13, Transactions and Concurrency for more information and code examples. The
h i b e r n a t e . c u r r e n t _ s e s s i o n _ c o n t e x t _ c l a s s
configuration parameter is
parameter not
which a
compatibility,
if
this
configuration
o r g . h i b e r n a t e . e n g i n e . t r a n s a c t i o n . j t a . p l a t f o r m . s p i . J t a P l a t f o r mis configured, Hibernate will use the o r g . h i b e r n a t e . c o n t e x t . i n t e r n a l . J T A S e s s i o n C o n t e x t . Typically, the value of this parameter would just
name the implementation class to use. For the three out-of-the-box implementations, however, there are three corresponding short names: "jta", "thread", and "managed".
Chapter 3. Configuration
Table of Contents 3.1. Programmatic configuration 3.2. Obtaining a SessionFactory 3.3. JDBC connections 3.4. Optional configuration properties 3.4.1. SQL Dialects 3.4.2. Outer Join Fetching 3.4.3. Binary Streams 3.4.4. Second-level and query cache 3.4.5. Query Language Substitution 3.4.6. Hibernate statistics 3.5. Logging 3.6. Implementing a N a m i n g S t r a t e g y 3.7. Implementing a PersisterClassProvider 3.8. XML configuration file 3.9. Java EE Application Server integration 3.9.1. Transaction strategy configuration 3.9.2. JNDI-bound S e s s i o n F a c t o r y 3.9.3. Current Session context management with JTA Hibernate is designed to operate in many different environments and, as such, there is a broad range of
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
24/215
12/30/13
An alternative way is to specify the mapped class and allow Hibernate to find the mapping document for you:
C o n f i g u r a t i o nc f g=n e wC o n f i g u r a t i o n ( ) . a d d C l a s s ( o r g . h i b e r n a t e . a u c t i o n . I t e m . c l a s s ) . a d d C l a s s ( o r g . h i b e r n a t e . a u c t i o n . B i d . c l a s s ) ;
This is not the only way to pass configuration properties to Hibernate. Some alternative options include: 1. Pass an instance of j a v a . u t i l . P r o p e r t i e sto C o n f i g u r a t i o n . s e t P r o p e r t i e s ( ) . 2. Place a file named h i b e r n a t e . p r o p e r t i e sin a root directory of the classpath. 3. Set S y s t e mproperties using j a v aD p r o p e r t y = v a l u e . 4. Include < p r o p e r t y >elements in h i b e r n a t e . c f g . x m l(this is discussed later). If you want to get started quicklyh i b e r n a t e . p r o p e r t i e sis the easiest approach. The o r g . h i b e r n a t e . c f g . C o n f i g u r a t i o nis intended as a startup-time object that will be discarded once a
S e s s i o n F a c t o r yis created.
Hibernate does allow your application to instantiate more than one o r g . h i b e r n a t e . S e s s i o n F a c t o r y . This is useful if you are using more than one database.
Once you start a task that requires access to the database, a JDBC connection will be obtained from the pool. Before you can do this, you first need to pass some JDBC connection properties to Hibernate. All Hibernate property names and semantics are defined on the class o r g . h i b e r n a t e . c f g . E n v i r o n m e n t . The most important settings for JDBC connection configuration are outlined below. Hibernate will obtain and pool connections using j a v a . s q l . D r i v e r M a n a g e r if you set the following properties:
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
25/215
12/30/13
Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started 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 l i b directory. Hibernate will use its o r g . h i b e r n a t e . c o n n e c t i o n . C 3 P 0 C o n n e c t i o n P r o v i d e r for connection pooling if you set hibernate.c3p0.* properties. If you would like to use Proxool, refer to the packaged
h i b e r n a t e . p r o p e r t i e sand the Hibernate web site for more information.
For use inside an application server, you should almost always configure Hibernate to obtain connections from an application server j a v a x . s q l . D a t a s o u r c e registered in JNDI. You will need to set at least one of the following properties:
Table 3.2. Hibernate Datasource Properties Property name hibernate.connection.datasource hibernate.jndi.url hibernate.jndi.class hibernate.connection.username hibernate.connection.password Purpose datasource JNDI name URL of the JNDI provider (optional) class of the JNDI I n i t i a l C o n t e x t F a c t o r y(optional) database user (optional) database user password (optional)
JDBC connections obtained from a JNDI datasource will automatically participate in the containermanaged transactions of the application server. Arbitrary connection properties can be given by prepending " h i b e r n a t e . c o n n e c t i o n " to the connection property name. For example, you can specify a charSet connection property using hibernate.connection.charSet. You can define your own plugin strategy for obtaining JDBC connections by implementing the interface
o r g . h i b e r n a t e . c o n n e c t i o n . C o n n e c t i o n P r o v i d e r , and specifying your custom implementation via the
hibernate.connection.provider_class property.
Warning
Some of these properties are "system-level" only. System-level properties can be set only via j a v a D p r o p e r t y = v a l u e or h i b e r n a t e . p r o p e r t i e s . They cannot be set by the other techniques described above.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
26/215
12/30/13
Property name
generate SQL optimized for a particular relational database. hibernate.dialect e.g. f u l l . c l a s s n a m e . o f . D i a l e c t In most cases Hibernate will actually be able to choose the correct o r g . h i b e r n a t e . d i a l e c t . D i a l e c t implementation based on the J D B Cm e t a d a t areturned by the JDBC driver. Write all SQL statements to console. This is an alternative to hibernate.show_sql setting the log category o r g . h i b e r n a t e . S Q Lto d e b u g . e.g. t r u e| f a l s e hibernate.format_sql hibernate.default_schema hibernate.default_catalog Pretty print the SQL in the log and console. e.g. t r u e| f a l s e Qualify unqualified table names with the given schema/tablespace in generated SQL. e.g. S C H E M A _ N A M E Qualifies unqualified table names with the given catalog in generated SQL. e.g. C A T A L O G _ N A M E The hibernate.session_factory_name
o r g . h i b e r n a t e . S e s s i o n F a c t o r y will
be
automatically
bound to this name in JNDI after it has been created. e.g. j n d i / c o m p o s i t e / n a m e Sets a maximum "depth" for the outer join fetch tree for single-ended associations (one-to-one, many-to-one). A 0
hibernate.max_fetch_depth
disables default outer join fetching. e.g. recommended values between 0and 3
hibernate.default_batch_fetch_size
Sets a default size for Hibernate batch associations. e.g. recommended values 4 ,8 ,1 6
fetching
of
hibernate.default_entity_mode
Sets a default mode for entity representation for all sessions opened from this S e s s i o n F a c t o r y , defaults to p o j o . e.g. d y n a m i c m a p| p o j o Forces Hibernate to order SQL updates by the primary key
hibernate.order_updates
value of the items being updated. This will result in fewer transaction deadlocks in highly concurrent systems. e.g. t r u e |f a l s e If enabled, Hibernate will collect statistics useful for
hibernate.generate_statistics hibernate.use_identifier_rollback
performance tuning. e.g. t r u e| f a l s e If enabled, generated identifier properties will be reset to default values when objects are deleted. e.g. t r u e| f a l s e If turned on, Hibernate will generate comments inside the SQL, for easier debugging, defaults to f a l s e . e.g. t r u e| f a l s e Setting is relevant when using @ G e n e r a t e d V a l u e . It indicates whether or not the are new
I d e n t i f i e r G e n e r a t o r
hibernate.use_sql_comments
implementations hibernate.id.new_generator_mappings
used
e.g. t r u e| f a l s e
Note
We recommend all new projects which make use of to use @ G e n e r a t e d V a l u e to also set
h i b e r n a t e . i d . n e w _ g e n e r a t o r _ m a p p i n g s = t r u e as
the
new
generators are more efficient and closer to the JPA 2 specification semantic. However they are not backward compatible with existing databases (if a sequence or a table is used for id generation).
Table 3.4. Hibernate JDBC and Connection Properties Property name hibernate.jdbc.fetch_size hibernate.jdbc.batch_size Purpose A non-zero value determines the JDBC fetch size (calls
S t a t e m e n t . s e t F e t c h S i z e ( ) ).
A non-zero value enables use of JDBC2 batch updates by Hibernate. e.g. recommended values between 5and 3 0 Set this property to t r u e if your JDBC driver returns correct
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
27/215
12/30/13
Most
applications will not need this configuration property. e.g. c l a s s n a m e . o f . B a t c h e r F a c t o r y Enables use of JDBC2 scrollable resultsets by Hibernate. This property is only necessary when using user-supplied JDBC connections. Hibernate uses connection metadata otherwise. e.g. t r u e| f a l s e Use streams when writing/reading b i n a r y or s e r i a l i z a b l e types to/from JDBC. *system-level property* e.g. t r u e| f a l s e Enables use of JDBC3
hibernate.jdbc.use_scrollable_resultset
hibernate.jdbc.use_streams_for_binary
generated keys after insert. Requires JDBC3+ driver and hibernate.jdbc.use_get_generated_keys JRE1.4+, set to false if your driver has problems with the Hibernate identifier generators. By default, it tries to determine metadata. the driver capabilities using connection
o r g . h i b e r n a t e . c o n n e c t i o n . C o n n e c t i o n P r o v i d e r
provides JDBC connections to Hibernate. e.g. c l a s s n a m e . o f . C o n n e c t i o n P r o v i d e r Sets the JDBC transaction isolation level. Check
hibernate.connection.isolation
most databases do not support all isolation levels and some define additional, non-standard isolations. e.g. 1 ,2 ,4 ,8
hibernate.connection.autocommit
Enables autocommit for JDBC pooled connections (it is not recommended). e.g. t r u e| f a l s e Specifies when Hibernate should release JDBC connections. By default, a JDBC connection is held until the session is explicitly closed or disconnected. For an application server JTA datasource, use a f t e r _ s t a t e m e n t to aggressively release connections after every JDBC call. For a non-JTA connection, it often makes sense to release the connection at the end of each transaction, by using
a f t e r _ t r a n s a c t i o n . a u t o will choose a f t e r _ s t a t e m e n t for
the hibernate.connection.release_mode
JTA
and
CMT
transaction
strategies
and
e.g. a u t o (default) | o n _ c l o s e | a f t e r _ t r a n s a c t i o n |
a f t e r _ s t a t e m e n t
This
setting
only
affects
S e s s i o n s
returned
from the
S e s s i o n F a c t o r y . o p e n S e s s i o n .
For
S e s s i o n s
obtained
through
S e s s i o n F a c t o r y . g e t C u r r e n t S e s s i o n ,
controls the connection release mode for those S e s s i o n s. See Section 2.2, Contextual sessions hibernate.connection.<propertyName> hibernate.jndi.<propertyName> Pass Pass the the JDBC property property <propertyName> to the to JNDI
D r i v e r M a n a g e r . g e t C o n n e c t i o n ( ) .
<propertyName>
I n i t i a l C o n t e x t F a c t o r y .
Table 3.5. Hibernate Cache Properties Property name Purpose The classname of a custom C a c h e P r o v i d e r .
h i b e r n a t e . c a c h e . p r o v i d e r _ c l a s s
h i b e r n a t e . c a c h e . u s e _ m i n i m a l _ p u t s
writes, at the cost of more frequent reads. This setting is most useful for clustered caches and, in Hibernate, is enabled by default for clustered cache
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
28/215
12/30/13
Enables the query cache. Individual queries still have to be set cachable. e.g. t r u e | f a l s e Can be used to completely disable the second level cache, which is enabled by default for classes which specify a < c a c h e >mapping. e.g. t r u e | f a l s e The classname of a custom Q u e r y C a c h e interface,
h i b e r n a t e . c a c h e . u s e _ s e c o n d _ l e v e l _ c a c h e
h i b e r n a t e . c a c h e . q u e r y _ c a c h e _ f a c t o r y
defaults to the built-in S t a n d a r d Q u e r y C a c h e . e.g. c l a s s n a m e . o f . Q u e r y C a c h e A prefix to use for second-level cache region names. e.g. p r e f i x Forces Hibernate to store data in the second-level cache in a more human-friendly format. e.g. t r u e | f a l s e Enables the automatic eviction of a bi-directional association's collection cache when an element in the
h i b e r n a t e . c a c h e . r e g i o n _ p r e f i x h i b e r n a t e . c a c h e . u s e _ s t r u c t u r e d _ e n t r i e s
h i b e r n a t e . c a c h e . a u t o _ e v i c t _ c o l l e c t i o n _ c a c h e
ManyToOne collection is added/updated/removed without properly managing the change on the OneToMany side. e.g. t r u e | f a l s e(default: false) Setting used to give the name of the default
o r g . h i b e r n a t e . a n n o t a t i o n s . C a c h e C o n c u r r e n c y S t r a t e g y
h i b e r n a t e . c a c h e . d e f a u l t _ c a c h e _ c o n c u r r e n c y _ s t r a t e g y
Table 3.6. Hibernate Transaction Properties Property name Purpose The classname of a T r a n s a c t i o n F a c t o r y to use with
h i b e r n a t e . t r a n s a c t i o n . f a c t o r y _ c l a s s
Hibernate
T r a n s a c t i o n API
(defaults
to
J D B C T r a n s a c t i o n F a c t o r y ).
the
JTA
U s e r T r a n s a c t i o n
from
the
application server. e.g. j n d i / c o m p o s i t e / n a m e The classname of a T r a n s a c t i o n M a n a g e r L o o k u p . It is required when JVM-level caching is enabled or
h i b e r n a t e . t r a n s a c t i o n . m a n a g e r _ l o o k u p _ c l a s s
when using hilo generator in a JTA environment. e.g. c l a s s n a m e . o f . T r a n s a c t i o n M a n a g e r L o o k u p If enabled, the session will be automatically flushed during the before completion phase of the
h i b e r n a t e . t r a n s a c t i o n . f l u s h _ b e f o r e _ c o m p l e t i o n management
transaction. Built-in and automatic session context is preferred, see Section 2.2, Contextual sessions. e.g. t r u e| f a l s e If enabled, the session will be automatically
closed during the after completion phase of the transaction. Built-in and automatic session context
h i b e r n a t e . t r a n s a c t i o n . a u t o _ c l o s e _ s e s s i o n
see
Section
2.2,
Table 3.7. Miscellaneous Properties Property name Purpose Supply a custom strategy for the scoping of the "current" S e s s i o n . See
h i b e r n a t e . c u r r e n t _ s e s s i o n _ c o n t e x t _ c l a s s
Section 2.2, Contextual sessions for more information about the built-in strategies. e.g. j t a| t h r e a d| m a n a g e d| c u s t o m . C l a s s Chooses the HQL parser implementation. e.g. or
h i b e r n a t e . q u e r y . f a c t o r y _ c l a s s
o r g . h i b e r n a t e . h q l . i n t e r n a l . a s t . A S T Q u e r y T r a n s l a t o r F a c t o r y
o r g . h i b e r n a t e . h q l . i n t e r n a l . c l a s s i c . C l a s s i c Q u e r y T r a n s l a t o r F a c t o r y
Is used to map from tokens in Hibernate queries to SQL tokens (tokens might be function or literal names, for example). e.g.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
29/215
12/30/13
Automatically validates or exports schema DDL to the database when the S e s s i o n F a c t o r y is created. With c r e a t e d r o p , the database
h i b e r n a t e . h b m 2 d d l . a u t o
schema will be dropped when the S e s s i o n F a c t o r yis closed explicitly. e.g. v a l i d a t e| u p d a t e| c r e a t e| c r e a t e d r o p Comma-separated names of the optional files containing SQL DML statements executed during the S e s s i o n F a c t o r y creation. This is useful for testing or demoing: by adding INSERT statements for example you can populate your database with a minimal set of data when it is deployed.
h i b e r n a t e . h b m 2 d d l . i m p o r t _ f i l e s
File order matters, the statements of a give file are executed before the statements of the following files. These statements are only executed if the schema is created ie if h i b e r n a t e . h b m 2 d d l . a u t o is set to c r e a t eor c r e a t e d r o p . e.g. / h u m a n s . s q l , / d o g s . s q l The classname of a custom I m p o r t S q l C o m m a n d E x t r a c t o r (defaults to the from built-in each
S i n g l e L i n e S q l C o m m a n d E x t r a c t o r ).
This
is
useful
for
implementing dedicated parser that extracts single SQL statements import file.
u l t i p l e L i n e s S q l C o m m a n d E x t r a c t o r h i b e r n a t e . h b m 2 d d l . i m p o r t _ f i l e s _ s q l _ e x t r a c t o r M
instructions/comments and quoted strings spread over multiple lines (mandatory semicolon at the end of each statement). e.g. c l a s s n a m e . o f . I m p o r t S q l C o m m a n d E x t r a c t o r Enables the use of bytecode manipulation instead of runtime
reflection. This is a System-level property and cannot be set in h i b e r n a t e . c f g . x m l . Reflection can sometimes be useful when
h i b e r n a t e . b y t e c o d e . u s e _ r e f l e c t i o n _ o p t i m i z e r
troubleshooting. Hibernate always requires javassist even if you turn off the optimizer. e.g. t r u e| f a l s e At the moment, j a v a s s i s tis the only supported bytecode provider.
h i b e r n a t e . b y t e c o d e . p r o v i d e r
e.g. j a v a s s i s t
Table 3.8. Hibernate SQL Dialects ( h i b e r n a t e . d i a l e c t ) RDBMS DB2 DB2 AS/400 DB2 OS390 PostgreSQL 8.1 PostgreSQL 8.2 and later MySQL5 MySQL5 with InnoDB MySQL with MyISAM Oracle (any version) Oracle 9i Oracle 10g Oracle 11g Sybase ASE 15.5 Sybase ASE 15.7 Sybase Anywhere Microsoft SQL Server 2000 Microsoft SQL Server 2005 Microsoft SQL Server 2008 SAP DB Informix HypersonicSQL H2 Database Ingres Dialect
o r g . h i b e r n a t e . d i a l e c t . D B 2 D i a l e c t o r g . h i b e r n a t e . d i a l e c t . D B 2 4 0 0 D i a l e c t o r g . h i b e r n a t e . d i a l e c t . D B 2 3 9 0 D i a l e c t o r g . h i b e r n a t e . d i a l e c t . P o s t g r e S Q L 8 1 D i a l e c t o r g . h i b e r n a t e . d i a l e c t . P o s t g r e S Q L 8 2 D i a l e c t o r g . h i b e r n a t e . d i a l e c t . M y S Q L 5 D i a l e c t o r g . h i b e r n a t e . d i a l e c t . M y S Q L 5 I n n o D B D i a l e c t o r g . h i b e r n a t e . d i a l e c t . M y S Q L M y I S A M D i a l e c t o r g . h i b e r n a t e . d i a l e c t . O r a c l e D i a l e c t o r g . h i b e r n a t e . d i a l e c t . O r a c l e 9 i D i a l e c t o r g . h i b e r n a t e . d i a l e c t . O r a c l e 1 0 g D i a l e c t o r g . h i b e r n a t e . d i a l e c t . O r a c l e 1 0 g D i a l e c t o r g . h i b e r n a t e . d i a l e c t . S y b a s e A S E 1 5 D i a l e c t o r g . h i b e r n a t e . d i a l e c t . S y b a s e A S E 1 5 7 D i a l e c t o r g . h i b e r n a t e . d i a l e c t . S y b a s e A n y w h e r e D i a l e c t o r g . h i b e r n a t e . d i a l e c t . S Q L S e r v e r D i a l e c t o r g . h i b e r n a t e . d i a l e c t . S Q L S e r v e r 2 0 0 5 D i a l e c t o r g . h i b e r n a t e . d i a l e c t . S Q L S e r v e r 2 0 0 8 D i a l e c t o r g . h i b e r n a t e . d i a l e c t . S A P D B D i a l e c t o r g . h i b e r n a t e . d i a l e c t . I n f o r m i x D i a l e c t o r g . h i b e r n a t e . d i a l e c t . H S Q L D i a l e c t o r g . h i b e r n a t e . d i a l e c t . H 2 D i a l e c t o r g . h i b e r n a t e . d i a l e c t . I n g r e s D i a l e c t
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
30/215
12/30/13
Progress Mckoi SQL Interbase Pointbase FrontBase Firebird
or
s e r i a l i z a b l e
type,
you
should
enable
This would cause the tokens t r u eand f a l s eto be translated to integer literals in the generated SQL.
h i b e r n a t e . q u e r y . s u b s t i t u t i o n st o L o w e r c a s e = L O W E R
3.5. Logging
Important
Completely out of date. Hibernate uses JBoss Logging starting in 4.0. This will get documented as we migrate this content to the Developer Guide.
Hibernate utilizes Simple Logging Facade for Java (SLF4J) in order to log various system events. SLF4J can direct your logging output to several logging frameworks (NOP, Simple, log4j version 1.2, JDK 1.4 logging, JCL or logback) depending on your chosen binding. In order to setup logging you will need
s l f 4 j a p i . j a rin your classpath together with the jar file for your preferred binding - s l f 4 j l o g 4 j 1 2 . j a r
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
31/215
12/30/13
Function Log all SQL DML statements as they are executed Log all JDBC parameters Log all SQL DDL statements as they are executed Log the state of all entities (max 20 entities) associated with the session at flush time Log all second-level cache activity Log transaction related activity Log all JDBC resource acquisition Log all JAAS authorization requests Log everything. This is a lot of information but it is useful for troubleshooting
When developing applications with Hibernate, you should almost always work with d e b u g enabled for the category o r g . h i b e r n a t e . S Q L , or, alternatively, the property h i b e r n a t e . s h o w _ s q lenabled.
3.6. Implementing a N a m i n g S t r a t e g y
The interface o r g . h i b e r n a t e . c f g . N a m i n g S t r a t e g y allows you to specify a "naming standard" for database objects and schema elements. You can 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. This feature helps reduce the verbosity of the mapping document, eliminating repetitive noise (T B L _prefixes, for example). The default strategy used by Hibernate is quite minimal. You can specify a different strategy by calling C o n f i g u r a t i o n . s e t N a m i n g S t r a t e g y ( ) before adding mappings:
S e s s i o n F a c t o r ys f=n e wC o n f i g u r a t i o n ( ) . s e t N a m i n g S t r a t e g y ( I m p r o v e d N a m i n g S t r a t e g y . I N S T A N C E ) . a d d F i l e ( " I t e m . h b m . x m l " ) . a d d F i l e ( " B i d . h b m . x m l " ) . b u i l d S e s s i o n F a c t o r y ( ) ; o r g . h i b e r n a t e . c f g . I m p r o v e d N a m i n g S t r a t e g y is a built-in strategy that might be a useful starting point
The persister class provider methods, when returning a non null persister class, override the default Hibernate persisters. The entity name or the collection role are passed to the methods. It is a nice way to centralize the overriding logic of the persisters instead of spreading them on each entity or collection mapping.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
32/215
12/30/13
are present, to override properties. The XML configuration file is by default expected to be in the root of your C L A S S P A T H . Here is an example:
< ? x m lv e r s i o n = ' 1 . 0 'e n c o d i n g = ' u t f 8 ' ? > < ! D O C T Y P Eh i b e r n a t e c o n f i g u r a t i o nP U B L I C " / / H i b e r n a t e / H i b e r n a t eC o n f i g u r a t i o nD T D / / E N " " h t t p : / / w w w . h i b e r n a t e . o r g / d t d / h i b e r n a t e c o n f i g u r a t i o n 3 . 0 . d t d " > < h i b e r n a t e c o n f i g u r a t i o n > < ! -aS e s s i o n F a c t o r yi n s t a n c el i s t e da s/ j n d i / n a m e> < s e s s i o n f a c t o r y n a m e = " j a v a : h i b e r n a t e / S e s s i o n F a c t o r y " > < ! -p r o p e r t i e s> < p r o p e r t yn a m e = " c o n n e c t i o n . d a t a s o u r c e " > j a v a : / c o m p / e n v / j d b c / M y D B < / p r o p e r t y > < p r o p e r t yn a m e = " d i a l e c t " > o r g . h i b e r n a t e . d i a l e c t . M y S Q L D i a l e c t < / p r o p e r t y > < p r o p e r t yn a m e = " s h o w _ s q l " > f a l s e < / p r o p e r t y > < p r o p e r t yn a m e = " t r a n s a c t i o n . f a c t o r y _ c l a s s " > o r g . h i b e r n a t e . t r a n s a c t i o n . J T A T r a n s a c t i o n F a c t o r y < / p r o p e r t y > < p r o p e r t yn a m e = " j t a . U s e r T r a n s a c t i o n " > j a v a : c o m p / U s e r T r a n s a c t i o n < / p r o p e r t y > < ! -m a p p i n gf i l e s> < m a p p i n gr e s o u r c e = " o r g / h i b e r n a t e / a u c t i o n / I t e m . h b m . x m l " / > < m a p p i n gr e s o u r c e = " o r g / h i b e r n a t e / a u c t i o n / B i d . h b m . x m l " / > < ! -c a c h es e t t i n g s> < c l a s s c a c h ec l a s s = " o r g . h i b e r n a t e . a u c t i o n . I t e m "u s a g e = " r e a d w r i t e " / > < c l a s s c a c h ec l a s s = " o r g . h i b e r n a t e . a u c t i o n . B i d "u s a g e = " r e a d o n l y " / > < c o l l e c t i o n c a c h ec o l l e c t i o n = " o r g . h i b e r n a t e . a u c t i o n . I t e m . b i d s "u s a g e = " r e a d w r i t e " / > < / s e s s i o n f a c t o r y > < / h i b e r n a t e c o n f i g u r a t i o n >
The advantage of this approach is the externalization of the mapping file names to configuration. The
h i b e r n a t e . c f g . x m lis also more convenient once you have to tune the Hibernate cache. It is your choice
to use either h i b e r n a t e . p r o p e r t i e s or h i b e r n a t e . c f g . x m l . Both are equivalent, except for the above mentioned benefits of using the XML syntax. With the XML configuration, starting Hibernate is then as simple as:
S e s s i o n F a c t o r ys f=n e wC o n f i g u r a t i o n ( ) . c o n f i g u r e ( ) . b u i l d S e s s i o n F a c t o r y ( ) ;
h i b e r n a t e . c o n n e c t i o n . a g g r e s s i v e _ r e l e a s e to
containment" exceptions.
12/30/13
instances
by
setting
the
Hibernate
configuration
property
h i b e r n a t e . t r a n s a c t i o n . f a c t o r y _ c l a s s .
delegates to container-managed transactions if an existing transaction is underway in this context (for example, EJB session bean method). Otherwise, a new transaction is started and beanmanaged transactions are used.
o r g . h i b e r n a t e . t r a n s a c t i o n . C M T T r a n s a c t i o n F a c t o r y
delegates to container-managed JTA transactions You can also define your own transaction strategies (for a CORBA transaction service, for example). Some features in Hibernate (i.e., the second level cache, Contextual Sessions with JTA, etc.) require access to the JTA T r a n s a c t i o n M a n a g e r in a managed environment. In an application server, since J2EE does not standardize a single mechanism, you have to specify how Hibernate should obtain a reference to the T r a n s a c t i o n M a n a g e r :
Application Server JBoss AS Weblogic WebSphere WebSphere 6 Orion Resin JOTM JOnAS JRun4 Borland ES JBoss TS used standalone (ie. outside JBoss AS and a JNDI environment generally). Known to work for
o r g . j b o s s . j b o s s t s : j b o s s j t a : 4 . 1 1 . 0 . F i n a l
o r g . h i b e r n a t e . t r a n s a c t i o n . J B o s s T S S t a n d a l o n e T r a n s a c t i o n M a n a g e r L o o k u p
3.9.2. JNDI-bound S e s s i o n F a c t o r y
A JNDI-bound Hibernate S e s s i o n F a c t o r y can simplify the lookup function of the factory and create new
S e s s i o n s. This is not, however, related to a JNDI bound D a t a s o u r c e ; both simply use the same registry.
If you wish to have the S e s s i o n F a c t o r y bound to a JNDI namespace, specify a name (e.g.
j a v a : h i b e r n a t e / S e s s i o n F a c t o r y ) using the property h i b e r n a t e . s e s s i o n _ f a c t o r y _ n a m e . If this property is
omitted, the S e s s i o n F a c t o r y will not be bound to JNDI. This is especially useful in environments with a read-only JNDI default implementation (in Tomcat, for example). When binding the S e s s i o n F a c t o r y to JNDI, Hibernate will use the values of h i b e r n a t e . j n d i . u r l ,
h i b e r n a t e . j n d i . c l a s s to
instantiate
I n i t i a l C o n t e x twill be used.
Hibernate will automatically place the S e s s i o n F a c t o r y in JNDI after you call c f g . b u i l d S e s s i o n F a c t o r y ( ) . This means you will have this call in some startup code, or utility class in your application, unless you use JMX deployment with the H i b e r n a t e S e r v i c e(this is discussed later in greater detail). If you use a JNDI S e s s i o n F a c t o r y , an EJB or any other class, you can obtain the S e s s i o n F a c t o r y using a JNDI lookup. It is recommended that you bind the S e s s i o n F a c t o r y to JNDI in a managed environment and use a
s t a t i c singleton otherwise. To shield your application code from these details, we also recommend to
hide
the
actual
lookup
code
for
S e s s i o n F a c t o r y
in
helper
class,
such
as
Hibernatesee chapter 1.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
34/215
12/30/13
will
be
started
and
associated
with
that
JTA
transaction
the
first
time
you
call
context are set to automatically flush before the transaction completes, close after the transaction completes, and aggressively release JDBC connections after each statement. This allows the S e s s i o n s to be managed by the life cycle of the JTA transaction to which it is associated, keeping user code clean of such management concerns. Your code can either use JTA programmatically through U s e r T r a n s a c t i o n , or (recommended for portable code) use the Hibernate T r a n s a c t i o n API to set transaction boundaries. If you run in an EJB container, declarative transaction demarcation with CMT is preferred.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
35/215
12/30/13
The four main rules of persistent classes are explored in more detail in the following sections.
non-public)
so
that
Hibernate
can
instantiate
them
using
at least package visibility in order for runtime proxy generation to work properly.
C a t has a property named i d . This property maps to the primary key column(s) of the underlying
database table. The type of the identifier property can be any "basic" type (see ???). See Section 9.4, Components as composite identifiers for information on mapping composite (multi-column) identifiers.
Note
Identifiers do not necessarily need to identify column(s) in the database physically defined as a primary key. They should just identify columns that can be used to uniquely identify rows in the underlying table.
We recommend that you declare consistently-named identifier properties on persistent classes and that you use a nullable (i.e., non-primitive) type.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
36/215
12/30/13
If the f i n a l class does implement a proper interface, you could alternatively tell Hibernate to use the interface instead when generating the proxies. See Example 4.4, Proxying an interface in h b m . x m l and Example 4.5, Proxying an interface in annotations.
You should also avoid declaring p u b l i c f i n a l methods as this will again limit the ability to generate proxies from this class. If you want to use a class with p u b l i cf i n a lmethods, you must explicitly disable proxying. Again, see Example 4.2, Disabling proxies in h b m . x m l and Example 4.3, Disabling proxies in annotations.
variables. It is better to provide an indirection between the relational schema and internal data structures of the class. By default, Hibernate persists JavaBeans style properties and recognizes method names of the form g e t F o o ,i s F o oand s e t F o o . If required, you can switch to direct field access for particular properties. Properties need not be declared public. Hibernate can persist a property declared with p a c k a g e ,
p r o t e c t e dor p r i v a t evisibility as well.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
37/215
12/30/13
The most obvious way is to implement e q u a l s ( ) /h a s h C o d e ( ) by comparing the identifier value of both objects. If the value is the same, both must be the same database row, because they are equal. If both are added to a S e t , you will only have one element in the S e t ). Unfortunately, you cannot use that approach with generated identifiers. Hibernate will only assign identifier values to objects that are persistent; a newly created instance will not have any identifier value. Furthermore, if an instance is unsaved and currently in a S e t , saving it will assign an identifier value to the object. If e q u a l s ( ) and
h a s h C o d e ( )are based on the identifier value, the hash code would change, breaking the contract of the S e t . See the Hibernate website for a full discussion of this problem. This is not a Hibernate issue, but
normal Java semantics of object identity and equality. It is recommended that you implement e q u a l s ( ) and h a s h C o d e ( ) using Business key equality. Business key equality means that the e q u a l s ( )method compares only the properties that form the business key. It is a key that would identify our instance in the real world (a natural candidate key):
p u b l i cc l a s sC a t{ . . . p u b l i cb o o l e a ne q u a l s ( O b j e c to t h e r ){ i f( t h i s= =o t h e r )r e t u r nt r u e ; i f(! ( o t h e ri n s t a n c e o fC a t ))r e t u r nf a l s e ; f i n a lC a tc a t=( C a t )o t h e r ; i f(! c a t . g e t L i t t e r I d ( ) . e q u a l s (g e t L i t t e r I d ( )))r e t u r nf a l s e ; i f(! c a t . g e t M o t h e r ( ) . e q u a l s (g e t M o t h e r ( )))r e t u r nf a l s e ; r e t u r nt r u e ; } p u b l i ci n th a s h C o d e ( ){ i n tr e s u l t ; r e s u l t=g e t M o t h e r ( ) . h a s h C o d e ( ) ; r e s u l t=2 9*r e s u l t+g e t L i t t e r I d ( ) ; r e t u r nr e s u l t ; } }
A business key does not have to be as solid as a database primary key candidate (see Section 13.1.3, Considering object identity). Immutable or unique properties are usually good candidates for a business key.
Persistent entities do not necessarily have to be represented as POJO classes or as JavaBean objects at runtime. Hibernate also supports dynamic models (using M a p s of M a p s at runtime). With this approach, you do not write persistent classes, only mapping files. By default, Hibernate works in normal POJO mode. You can set a default entity representation mode for a particular S e s s i o n F a c t o r y using the d e f a u l t _ e n t i t y _ m o d e configuration option (see Table 3.3, Hibernate Configuration Properties). The following examples demonstrate the representation using M a p s. First, in the mapping file an
e n t i t y n a m ehas to be declared instead of, or in addition to, a class name: < h i b e r n a t e m a p p i n g > < c l a s se n t i t y n a m e = " C u s t o m e r " > < i dn a m e = " i d " t y p e = " l o n g " c o l u m n = " I D " > < g e n e r a t o rc l a s s = " s e q u e n c e " / > < / i d > < p r o p e r t yn a m e = " n a m e " c o l u m n = " N A M E " t y p e = " s t r i n g " / > < p r o p e r t yn a m e = " a d d r e s s " c o l u m n = " A D D R E S S " t y p e = " s t r i n g " / > < m a n y t o o n en a m e = " o r g a n i z a t i o n " c o l u m n = " O R G A N I Z A T I O N _ I D " c l a s s = " O r g a n i z a t i o n " / > < b a gn a m e = " o r d e r s "
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
38/215
12/30/13
Even though associations are declared using target class names, the target type of associations can also be a dynamic entity instead of a POJO. After setting the default entity mode to d y n a m i c m a p for the S e s s i o n F a c t o r y , you can, at runtime, work with M a p s of M a p s:
S e s s i o ns=o p e n S e s s i o n ( ) ; T r a n s a c t i o nt x=s . b e g i n T r a n s a c t i o n ( ) ; / /C r e a t eac u s t o m e r M a pd a v i d=n e wH a s h M a p ( ) ; d a v i d . p u t ( " n a m e " ," D a v i d " ) ; / /C r e a t ea no r g a n i z a t i o n M a pf o o b a r=n e wH a s h M a p ( ) ; f o o b a r . p u t ( " n a m e " ," F o o b a rI n c . " ) ; / /L i n kb o t h d a v i d . p u t ( " o r g a n i z a t i o n " ,f o o b a r ) ; / /S a v eb o t h s . s a v e ( " C u s t o m e r " ,d a v i d ) ; s . s a v e ( " O r g a n i z a t i o n " ,f o o b a r ) ; t x . c o m m i t ( ) ; s . c l o s e ( ) ;
One of the main advantages of dynamic mapping is quick turnaround time for prototyping, without the need for entity class implementation. However, you lose compile-time type checking and will likely deal with many exceptions at runtime. As a result of the Hibernate mapping, the database schema can easily be normalized and sound, allowing to add a proper domain model implementation on top later on. Entity representation modes can also be set on a per S e s s i o nbasis:
S e s s i o nd y n a m i c S e s s i o n=p o j o S e s s i o n . g e t S e s s i o n ( E n t i t y M o d e . M A P ) ; / /C r e a t eac u s t o m e r M a pd a v i d=n e wH a s h M a p ( ) ; d a v i d . p u t ( " n a m e " ," D a v i d " ) ; d y n a m i c S e s s i o n . s a v e ( " C u s t o m e r " ,d a v i d ) ; . . . d y n a m i c S e s s i o n . f l u s h ( ) ; d y n a m i c S e s s i o n . c l o s e ( ) . . . / /C o n t i n u eo np o j o S e s s i o n
Please note that the call to g e t S e s s i o n ( ) using an E n t i t y M o d e is on the S e s s i o n API, not the
S e s s i o n F a c t o r y . That way, the new S e s s i o n shares the underlying JDBC connection, transaction, and
other context information. This means you do not have to call f l u s h ( ) and c l o s e ( ) on the secondary
S e s s i o n , and also leave the transaction and connection handling to the primary unit of work.
4.5. Tuplizers
o r g . h i b e r n a t e . t u p l e . T u p l i z e r and
representation of a piece of data given that representation's o r g . h i b e r n a t e . E n t i t y M o d e . If a given piece of data is thought of as a data structure, then a tuplizer is the thing that knows how to create such a data structure, how to extract values from such a data structure and how to inject values into such a data structure. For example, for the POJO entity mode, the corresponding tuplizer knows how create the POJO through its constructor. It also knows how to access the POJO properties using the defined property accessors. There are two (high-level) types of Tuplizers:
o r g . h i b e r n a t e . t u p l e . e n t i t y . E n t i t y T u p l i z e r which
is
responsible
for
managing
the
above
Users can also plug in their own tuplizers. Perhaps you require that j a v a . u t i l . M a pimplementation other than j a v a . u t i l . H a s h M a p be used while in the dynamic-map entity-mode. Or perhaps you need to define a different proxy generation strategy than the one used by default. Both would be achieved by defining a custom tuplizer implementation. Tuplizer definitions are attached to the entity or component mapping they are meant to manage. Going back to the example of our C u s t o m e r entity, Example 4.6, Specify custom tuplizers in annotations shows how to specify a custom
o r g . h i b e r n a t e . t u p l e . e n t i t y . E n t i t y T u p l i z e r using annotations while Example 4.7, Specify custom
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
39/215
12/30/13
4.6. EntityNameResolvers
o r g . h i b e r n a t e . E n t i t y N a m e R e s o l v e ris a contract for resolving the entity name of a given entity instance.
The interface defines a single method r e s o l v e E n t i t y N a m e 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). Generally speaking, an
o r g . h i b e r n a t e . E n t i t y N a m e R e s o l v e r is going to be most useful in the case of dynamic models. One
example might be using proxied interfaces as your domain model. The hibernate test suite has an example of this exact style of usage under the org.hibernate.test.dynamicentity.tuplizer2. Here is some of the code from that package for illustration.
/ * * *Av e r yt r i v i a lJ D KP r o x yI n v o c a t i o n H a n d l e ri m p l e m e n t a t i o nw h e r ew ep r o x ya n *i n t e r f a c ea st h ed o m a i nm o d e la n ds i m p l ys t o r ep e r s i s t e n ts t a t ei na ni n t e r n a l *M a p . T h i si sa ne x t r e m e l yt r i v i a le x a m p l em e a n to n l yf o ri l l u s t r a t i o n . * / p u b l i cf i n a lc l a s sD a t a P r o x y H a n d l e ri m p l e m e n t sI n v o c a t i o n H a n d l e r{ p r i v a t eS t r i n ge n t i t y N a m e ; p r i v a t eH a s h M a pd a t a=n e wH a s h M a p ( ) ; p u b l i cD a t a P r o x y H a n d l e r ( S t r i n ge n t i t y N a m e ,S e r i a l i z a b l ei d ){ t h i s . e n t i t y N a m e=e n t i t y N a m e ; d a t a . p u t (" I d " ,i d) ; } p u b l i cO b j e c ti n v o k e ( O b j e c tp r o x y ,M e t h o dm e t h o d ,O b j e c t [ ]a r g s )t h r o w sT h r o w a b l e{ S t r i n gm e t h o d N a m e=m e t h o d . g e t N a m e ( ) ; i f(m e t h o d N a m e . s t a r t s W i t h (" s e t ")){ S t r i n gp r o p e r t y N a m e=m e t h o d N a m e . s u b s t r i n g (3) ; d a t a . p u t (p r o p e r t y N a m e ,a r g s [ 0 ]) ; } e l s ei f(m e t h o d N a m e . s t a r t s W i t h (" g e t ")){ S t r i n gp r o p e r t y N a m e=m e t h o d N a m e . s u b s t r i n g (3) ; r e t u r nd a t a . g e t (p r o p e r t y N a m e) ; } e l s ei f(" t o S t r i n g " . e q u a l s (m e t h o d N a m e)){ r e t u r ne n t i t y N a m e+" # "+d a t a . g e t (" I d ") ; } e l s ei f(" h a s h C o d e " . e q u a l s (m e t h o d N a m e)){ r e t u r nn e wI n t e g e r (t h i s . h a s h C o d e ( )) ; } r e t u r nn u l l ; } p u b l i cS t r i n gg e t E n t i t y N a m e ( ){ r e t u r ne n t i t y N a m e ; } p u b l i cH a s h M a pg e t D a t a ( ){ r e t u r nd a t a ; } } p u b l i cc l a s sP r o x y H e l p e r{ p u b l i cs t a t i cS t r i n ge x t r a c t E n t i t y N a m e ( O b j e c to b j e c t ){ / /O u rc u s t o mj a v a . l a n g . r e f l e c t . P r o x yi n s t a n c e sa c t u a l l yb u n d l e / /t h e i ra p p r o p r i a t ee n t i t yn a m e ,s ow es i m p l ye x t r a c ti tf r o mt h e r e / /i ft h i sr e p r e s e n t so n eo fo u rp r o x i e s ;o t h e r w i s e ,w er e t u r nn u l l
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
40/215
12/30/13
In order to register an o r g . h i b e r n a t e . E n t i t y N a m e R e s o l v e rusers must either: 1. Implement a custom tuplizer (see Section 4.5, Tuplizers), implementing the
g e t E n t i t y N a m e R e s o l v e r smethod
2. Register it with the o r g . h i b e r n a t e . i m p l . S e s s i o n F a c t o r y I m p l (which is the implementation class for o r g . h i b e r n a t e . S e s s i o n F a c t o r y ) using the r e g i s t e r E n t i t y N a m e R e s o l v e rmethod.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
41/215
12/30/13
you (even without a specific "JPA" plugin, since JPA annotations are plain Java 5 annotations). Here is an example of mapping
p a c k a g ee g ; @ E n t i t y @ T a b l e ( n a m e = " c a t s " )@ I n h e r i t a n c e ( s t r a t e g y = S I N G L E _ T A B L E ) @ D i s c r i m i n a t o r V a l u e ( " C " )@ D i s c r i m i n a t o r C o l u m n ( n a m e = " s u b c l a s s " ,d i s c r i m i n a t o r T y p e = C H A R ) p u b l i cc l a s sC a t{ @ I d@ G e n e r a t e d V a l u e p u b l i cI n t e g e rg e t I d ( ){r e t u r ni d ;} p u b l i cv o i ds e t I d ( I n t e g e ri d ){t h i s . i d=i d ;} p r i v a t eI n t e g e ri d ; p u b l i cB i g D e c i m a lg e t W e i g h t ( ){r e t u r nw e i g h t ;} p u b l i cv o i ds e t W e i g h t ( B i g D e c i m a lw e i g h t ){t h i s . w e i g h t=w e i g h t ;} p r i v a t eB i g D e c i m a lw e i g h t ; @ T e m p o r a l ( D A T E )@ N o t N u l l@ C o l u m n ( u p d a t a b l e = f a l s e ) p u b l i cD a t eg e t B i r t h d a t e ( ){r e t u r nb i r t h d a t e ;} p u b l i cv o i ds e t B i r t h d a t e ( D a t eb i r t h d a t e ){t h i s . b i r t h d a t e=b i r t h d a t e ;} p r i v a t eD a t eb i r t h d a t e ; @ o r g . h i b e r n a t e . a n n o t a t i o n s . T y p e ( t y p e = " e g . t y p e s . C o l o r U s e r T y p e " ) @ N o t N u l l@ C o l u m n ( u p d a t a b l e = f a l s e ) p u b l i cC o l o r T y p eg e t C o l o r ( ){r e t u r nc o l o r ;} p u b l i cv o i ds e t C o l o r ( C o l o r T y p ec o l o r ){t h i s . c o l o r=c o l o r ;} p r i v a t eC o l o r T y p ec o l o r ; @ N o t N u l l@ C o l u m n ( u p d a t a b l e = f a l s e ) p u b l i cS t r i n gg e t S e x ( ){r e t u r ns e x ;} p u b l i cv o i ds e t S e x ( S t r i n gs e x ){t h i s . s e x=s e x ;} p r i v a t eS t r i n gs e x ; @ N o t N u l l@ C o l u m n ( u p d a t a b l e = f a l s e ) p u b l i cI n t e g e rg e t L i t t e r I d ( ){r e t u r nl i t t e r I d ;} p u b l i cv o i ds e t L i t t e r I d ( I n t e g e rl i t t e r I d ){t h i s . l i t t e r I d=l i t t e r I d ;} p r i v a t eI n t e g e rl i t t e r I d ; @ M a n y T o O n e@ J o i n C o l u m n ( n a m e = " m o t h e r _ i d " ,u p d a t a b l e = f a l s e ) p u b l i cC a tg e t M o t h e r ( ){r e t u r nm o t h e r ;} p u b l i cv o i ds e t M o t h e r ( C a tm o t h e r ){t h i s . m o t h e r=m o t h e r ;} p r i v a t eC a tm o t h e r ; @ O n e T o M a n y ( m a p p e d B y = " m o t h e r " )@ O r d e r B y ( " l i t t e r I d " ) p u b l i cS e t < C a t >g e t K i t t e n s ( ){r e t u r nk i t t e n s ;} p u b l i cv o i ds e t K i t t e n s ( S e t < C a t >k i t t e n s ){t h i s . k i t t e n s=k i t t e n s ;} p r i v a t eS e t < C a t >k i t t e n s=n e wH a s h S e t < C a t > ( ) ; } @ E n t i t y@ D i s c r i m i n a t o r V a l u e ( " D " ) p u b l i cc l a s sD o m e s t i c C a te x t e n d sC a t{ p u b l i cS t r i n gg e t N a m e ( ){r e t u r nn a m e ;} p u b l i cv o i ds e t N a m e ( S t r i n gn a m e ){t h i s . n a m e=n a m e} p r i v a t eS t r i n gn a m e ; } @ E n t i t y p u b l i cc l a s sD o g{. . .}
The legacy hbm.xml approach uses an XML schema designed to be readable and hand-editable. The mapping language is Java-centric, meaning that mappings are constructed around persistent class declarations and not table declarations. Please note that even though many Hibernate users choose to write the XML by hand, a number of tools exist to generate the mapping document. These include XDoclet, Middlegen and AndroMDA. Here is an example mapping:
< ? x m lv e r s i o n = " 1 . 0 " ? > < ! D O C T Y P Eh i b e r n a t e m a p p i n gP U B L I C " / / H i b e r n a t e / H i b e r n a t eM a p p i n gD T D3 . 0 / / E N " " h t t p : / / w w w . h i b e r n a t e . o r g / d t d / h i b e r n a t e m a p p i n g 3 . 0 . d t d " > < h i b e r n a t e m a p p i n gp a c k a g e = " e g " >
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
42/215
12/30/13
We will now discuss the concepts of the mapping documents (both annotations and XML). We will only describe, however, the document elements and attributes that are used by Hibernate at runtime. The mapping document also contains some extra optional attributes and elements that affect the database schemas exported by the schema export tool (for example, the n o t n u l lattribute).
5.1.1. Entity
An entity is a regular Java object (aka POJO) which will be persisted by Hibernate. To mark an object as an entity in annotations, use the @ E n t i t yannotation.
@ E n t i t y p u b l i cc l a s sF l i g h ti m p l e m e n t sS e r i a l i z a b l e{ L o n gi d ; @ I d p u b l i cL o n gg e t I d ( ){r e t u r ni d ;} p u b l i cv o i ds e t I d ( L o n gi d ){t h i s . i d=i d ;} }
That's pretty much it, the rest is optional. There are however any options to tweak your entity mapping, let's explore them.
@ T a b l e lets you define the table the entity will be persisted into. If undefined, the table name is the
unqualified class name of the entity. You can also optionally define the catalog, the schema as well as unique constraints on the table.
@ E n t i t y @ T a b l e ( n a m e = " T B L _ F L I G H T " , s c h e m a = " A I R _ C O M M A N D " , u n i q u e C o n s t r a i n t s = @ U n i q u e C o n s t r a i n t ( n a m e = " f l i g h t _ n u m b e r " , c o l u m n N a m e s = { " c o m p _ p r e f i x " ," f l i g h t _ n u m b e r " })) p u b l i cc l a s sF l i g h ti m p l e m e n t sS e r i a l i z a b l e{ @ C o l u m n ( n a m e = " c o m p _ p r e f i x " ) p u b l i cS t r i n gg e t C o m p a g n y P r e f i x ( ){r e t u r nc o m p a n y P r e f i x ;} @ C o l u m n ( n a m e = " f l i g h t _ n u m b e r " ) p u b l i cS t r i n gg e t N u m b e r ( ){r e t u r nn u m b e r ;} }
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
43/215
12/30/13
Tip
Be sure to use the database-level column names for the c o l u m n N a m e s property of a @ U n i q u e C o n s t r a i n t . For example, whilst for simple types the database-level column name may be the same as the entity-level property name, this is often not the case for relational properties.
@ E n t i t y . n a m elets you define the shortcut name of the entity you can used in JP-QL and HQL queries. It
defaults to the unqualified class name of the class. Hibernate goes beyond the JPA specification and provide additional configurations. Some of them are hosted on @ o r g . h i b e r n a t e . a n n o t a t i o n s . E n t i t y :
d y n a m i c I n s e r t/ d y n a m i c U p d a t e (defaults to false): specifies that I N S E R T/ U P D A T E SQL should be
generated at runtime and contain only the columns whose values are not null. The d y n a m i c u p d a t e and d y n a m i c i n s e r t settings are not inherited by subclasses. Although these settings can increase performance in some cases, they can actually decrease performance in others.
s e l e c t B e f o r e U p d a t e(defaults to false): specifies that Hibernate should never perform an SQL U P D A T E
unless it is certain that an object is actually modified. Only when a transient object has been associated with a new session using u p d a t e ( ) , will Hibernate perform an extra SQL S E L E C T to determine if an U P D A T E is actually required. Use of s e l e c t b e f o r e u p d a t e will usually decrease performance. It is useful to prevent a database update trigger being called unnecessarily if you reattach a graph of detached instances to a S e s s i o n .
p o l y m o r p h i s m s(defaults to I M P L I C I T ): determines whether implicit or explicit query polymorphisms is
used. Implicit polymorphisms means that instances of the class will be returned by a query that names any superclass or implemented interface or class, and that instances of any subclass of the class will be returned by a query that names the class itself. Explicit polymorphisms means that class instances will be returned only by queries that explicitly name that class. Queries that name the class will return only instances of subclasses mapped. For most purposes, the default
p o l y m o r p h i s m s = I M P L I C I T is appropriate. Explicit polymorphisms 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.
p e r s i s t e r : specifies a custom C l a s s P e r s i s t e r . The p e r s i s t e r attribute lets you customize the
persistence strategy used for the class. You can, for example, specify your own subclass of o r g . h i b e r n a t e . p e r s i s t e r . E n t i t y P e r s i s t e r , or you can even provide a completely new implementation of the interface o r g . h i b e r n a t e . p e r s i s t e r . C l a s s P e r s i s t e r that implements, for example, persistence via stored procedure calls, serialization to flat files or LDAP. See
o r g . h i b e r n a t e . t e s t . C u s t o m P e r s i s t e rfor a simple example of "persistence" to a H a s h t a b l e . o p t i m i s t i c L o c k (defaults to V E R S I O N ): determines the optimistic locking strategy. If you enable d y n a m i c U p d a t e , you will have a choice of optimistic locking strategies: v e r s i o n : check the version/timestamp columns a l l : check all columns d i r t y : check the changed columns, allowing some concurrent updates n o n e : do not use optimistic locking
It is strongly recommended that you use version/timestamp columns for optimistic locking with Hibernate. This strategy optimizes performance and correctly handles modifications made to detached instances (i.e. when S e s s i o n . m e r g e ( )is used).
Tip
Be sure to import @ j a v a x . p e r s i s t e n c e . E n t i t y to mark a class as an entity. It's a common mistake to import @ o r g . h i b e r n a t e . a n n o t a t i o n s . E n t i t y by accident.
Some entities are not mutable. They cannot be updated by the application. This allows Hibernate to make some minor performance optimizations.. Use the @ I m m u t a b l eannotation. You can also alter how Hibernate deals with lazy initialization for this class. On @ P r o x y , use l a z y =false to disable lazy fetching (not recommended). You can also specify an interface to use for lazy initializing proxies (defaults to the class itself): use p r o x y C l a s s on @ P r o x y . Hibernate will initially return proxies ( using bytecode provider defined by h i b e r n a t e . b y t e c o d e . p r o v i d e r ) that implement the named interface. The persistent object will load when a method of the proxy is invoked. See "Initializing collections and proxies" below.
@ B a t c h S i z e specifies a "batch size" for fetching instances of this class by identifier. Not yet loaded
instances are loaded batch-size at a time (default 1). You can specific an arbitrary SQL WHERE condition to be used when retrieving objects of this class. Use @ W h e r efor that. In the same vein, @ C h e c k lets you define an SQL expression used to generate a multi-row check
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
44/215
12/30/13
Declare the tables to synchronize this entity with, ensuring that auto-flush happens correctly and that queries against the derived entity do not return stale data. The < s u b s e l e c t > is available both as an attribute and a nested mapping element. We will now explore the same options using the hbm.xml structure. You can declare a persistent class using the c l a s selement. For example:
< c l a s s n a m e = " C l a s s N a m e " t a b l e = " t a b l e N a m e " d i s c r i m i n a t o r v a l u e = " d i s c r i m i n a t o r _ v a l u e " m u t a b l e = " t r u e | f a l s e " s c h e m a = " o w n e r " c a t a l o g = " c a t a l o g " p r o x y = " P r o x y I n t e r f a c e " d y n a m i c u p d a t e = " t r u e | f a l s e " d y n a m i c i n s e r t = " t r u e | f a l s e " s e l e c t b e f o r e u p d a t e = " t r u e | f a l s e " p o l y m o r p h i s m = " i m p l i c i t | e x p l i c i t " w h e r e = " a r b i t r a r ys q lw h e r ec o n d i t i o n " p e r s i s t e r = " P e r s i s t e r C l a s s " b a t c h s i z e = " N " o p t i m i s t i c l o c k = " n o n e | v e r s i o n | d i r t y | a l l " l a z y = " t r u e | f a l s e " e n t i t y n a m e = " E n t i t y N a m e " c h e c k = " a r b i t r a r ys q lc h e c kc o n d i t i o n " r o w x m l : i d = " r o w i d " s u b s e l e c t = " S Q Le x p r e s s i o n " a b s t r a c t = " t r u e | f a l s e " n o d e = " e l e m e n t n a m e " / > n a m e(optional): the fully qualified Java class name of the persistent class or interface. If this
( 1 6 ) ( 1 7 ) ( 1 8 ) ( 1 9 ) ( 2 0 ) ( 2 1 )
individual subclasses that is used for polymorphic behavior. Acceptable values include n u l land
n o tn u l l . m u t a b l e(optional - defaults to t r u e ): specifies that instances of the class are (not) mutable. s c h e m a(optional): overrides the schema name specified by the root < h i b e r n a t e m a p p i n g >
element.
c a t a l o g(optional): overrides the catalog name specified by the root < h i b e r n a t e m a p p i n g >
element.
p r o x y(optional): specifies an interface to use for lazy initializing proxies. You can specify the
runtime and can contain only those columns whose values have changed.
d y n a m i c i n s e r t(optional - defaults to f a l s e ): specifies that I N S E R TSQL should be generated at
runtime and contain only the columns whose values are not null.
s e l e c t b e f o r e u p d a t e(optional - defaults to f a l s e ): specifies that Hibernate should never
perform an SQL U P D A T Eunless it is certain that an object is actually modified. Only when a transient object has been associated with a new session using u p d a t e ( ) , will Hibernate perform an extra SQL S E L E C Tto determine if an U P D A T Eis actually required.
p o l y m o r p h i s m s(optional - defaults to i m p l i c i t ): determines whether implicit or explicit query
polymorphisms is used.
w h e r e(optional): specifies an arbitrary SQL W H E R Econdition to be used when retrieving objects
of this class.
p e r s i s t e r(optional): specifies a custom C l a s s P e r s i s t e r . b a t c h s i z e(optional - defaults to 1 ): specifies a "batch size" for fetching instances of this class
by identifier.
o p t i m i s t i c l o c k(optional - defaults to v e r s i o n ): determines the optimistic locking strategy.
(16) l a z y(optional): lazy fetching can be disabled by setting l a z y = " f a l s e " . (17) e n t i t y n a m e(optional - defaults to the class name): Hibernate allows a class to be mapped multiple times, potentially to different tables. It also allows entity mappings that are represented by Maps or XML at the Java level. In these cases, you should provide an explicit arbitrary name for the entity. See Section 4.4, Dynamic models and ??? for more information. (18) c h e c k(optional): an SQL expression used to generate a multi-row check constraint for automatic
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
45/215
12/30/13
schema generation.
The < s u b s e l e c t >is available both as an attribute and a nested mapping element.
5.1.2. Identifiers
Mapped classes must declare the primary key column of the database table. Most classes will also have a JavaBeans-style property holding the unique identifier of an instance. Mark the identifier property with @ I d .
@ E n t i t y p u b l i cc l a s sP e r s o n{ @ I dI n t e g e rg e t I d ( ){. . .} . . . }
In hbm.xml, use the < i d > element which defines the mapping from that property to the primary key column.
< i d n a m e = " p r o p e r t y N a m e " t y p e = " t y p e n a m e " c o l u m n = " c o l u m n _ n a m e " u n s a v e d v a l u e = " n u l l | a n y | n o n e | u n d e f i n e d | i d _ v a l u e " a c c e s s = " f i e l d | p r o p e r t y | C l a s s N a m e " > n o d e = " e l e m e n t n a m e | @ a t t r i b u t e n a m e | e l e m e n t / @ a t t r i b u t e | . " < g e n e r a t o rc l a s s = " g e n e r a t o r C l a s s " / > < / i d > n a m e(optional): the name of the identifier property. t y p e(optional): a name that indicates the Hibernate type. c o l u m n(optional - defaults to the property name): the name of the primary key column. u n s a v e d v a l u e(optional - defaults to a "sensible" value): an identifier property value that
indicates an instance is newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in a previous session.
a c c e s s(optional - defaults to p r o p e r t y ): the strategy Hibernate should use for accessing the
property value. If the n a m eattribute is missing, it is assumed that the class has no identifier property. The u n s a v e d v a l u e attribute is almost never needed in Hibernate and indeed has no corresponding element in annotations. You can also declare the identifier as a composite identifier. This allows access to legacy data with composite keys. Its use is strongly discouraged for anything else.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
46/215
12/30/13
is serializable. To override
the column
mapping, use
@ A t t r i b u t e O v e r r i d e .
In the embedded id object, the association is represented as the identifier of the associated entity. But you can link its value to a regular association in the entity via the @ M a p s I dannotation. The @ M a p s I d value correspond to the property name of the embedded id object containing the associated entity's identifier. In the database, it means that the C u s t o m e r . u s e r and the C u s t o m e r I d . u s e r I d properties share the same underlying column (u s e r _ f kin this case).
Tip
The component type used as identifier must implement e q u a l s ( ) and
h a s h C o d e ( ) .
In practice, your code only sets the C u s t o m e r . u s e rproperty and the user id value is copied by Hibernate into the C u s t o m e r I d . u s e r I dproperty.
Warning
The id value can be copied as late as flush time, don't rely on it until after flush time.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
47/215
12/30/13
Notice a few things in the previous example: the order of the properties (and column) matters. It must be the same between the association and the primary key of the associated entity the many to one uses the same columns as the primary key and thus must be marked as read only (i n s e r t a b l eand u p d a t a b l eto false). unlike with @ M a p s I d , the id value of the associated entity is not transparently copied, check the
f o r e i g nid generator for more information.
The last example shows how to map association directly in the embedded id component.
< c l a s sn a m e = " C u s t o m e r " > < c o m p o s i t e i dn a m e = " i d "c l a s s = " C u s t o m e r I d " > < k e y m a n y t o o n en a m e = " u s e r " > < c o l u m nn a m e = " u s e r f i r s t n a m e _ f k " / > < c o l u m nn a m e = " u s e r l a s t n a m e _ f k " / >
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
48/215
12/30/13
This is the recommended approach to map composite identifier. The following options should not be considered unless some constraint are present.
5.1.2.1.2. Multiple id properties without identifier type Another, arguably more natural, approach is to place @ I d on multiple properties of your entity. This approach is only supported by Hibernate (not JPA compliant) but does not require an extra embeddable component.
@ E n t i t y c l a s sC u s t o m e ri m p l e m e n t sS e r i a l i z a b l e{ @ I d@ O n e T o O n e @ J o i n C o l u m n s ( { @ J o i n C o l u m n ( n a m e = " u s e r f i r s t n a m e _ f k " ,r e f e r e n c e d C o l u m n N a m e = " f i r s t N a m e " ) , @ J o i n C o l u m n ( n a m e = " u s e r l a s t n a m e _ f k " ,r e f e r e n c e d C o l u m n N a m e = " l a s t N a m e " ) } ) U s e ru s e r ; @ I dS t r i n gc u s t o m e r N u m b e r ; b o o l e a np r e f e r r e d C u s t o m e r ; / / i m p l e m e n t se q u a l sa n dh a s h C o d e } @ E n t i t y c l a s sU s e r{ @ E m b e d d e d I dU s e r I di d ; I n t e g e ra g e ; } @ E m b e d d a b l e c l a s sU s e r I di m p l e m e n t sS e r i a l i z a b l e{ S t r i n gf i r s t N a m e ; S t r i n gl a s t N a m e ; / / i m p l e m e n t se q u a l sa n dh a s h C o d e }
In this case C u s t o m e r is its own identifier representation: it must implement S e r i a l i z a b l e and must implement e q u a l s ( )and h a s h C o d e ( ) . In hbm.xml, the same mapping is:
< c l a s sn a m e = " C u s t o m e r " > < c o m p o s i t e i d > < k e y m a n y t o o n en a m e = " u s e r " > < c o l u m nn a m e = " u s e r f i r s t n a m e _ f k " / > < c o l u m nn a m e = " u s e r l a s t n a m e _ f k " / > < / k e y m a n y t o o n e > < k e y p r o p e r t yn a m e = " c u s t o m e r N u m b e r " / > < / c o m p o s i t e i d > < p r o p e r t yn a m e = " p r e f e r r e d C u s t o m e r " / > < / c l a s s > < c l a s sn a m e = " U s e r " > < c o m p o s i t e i dn a m e = " i d "c l a s s = " U s e r I d " > < k e y p r o p e r t yn a m e = " f i r s t N a m e " / > < k e y p r o p e r t yn a m e = " l a s t N a m e " / > < / c o m p o s i t e i d > < p r o p e r t yn a m e = " a g e " / > < / c l a s s >
properties marked @ I don the entity must have their corresponding property on the @ I d C l a s s . The return type of search twin property must be either identical for basic properties or must correspond to the identifier class of the associated entity for an association.
Warning
This approach is inherited from the EJB 2 days and we recommend against its use. But, after all it's your application and Hibernate supports it.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
49/215
12/30/13
be S e r i a l i z a b l eand implement e q u a l s ( )and h a s h C o d e ( ) . While not JPA standard, Hibernate let's you declare the vanilla associated property in the @ I d C l a s s .
@ E n t i t y @ I d C l a s s ( C u s t o m e r I d . c l a s s ) c l a s sC u s t o m e ri m p l e m e n t sS e r i a l i z a b l e{ @ I d@ O n e T o O n e @ J o i n C o l u m n s ( { @ J o i n C o l u m n ( n a m e = " u s e r f i r s t n a m e _ f k " ,r e f e r e n c e d C o l u m n N a m e = " f i r s t N a m e " ) , @ J o i n C o l u m n ( n a m e = " u s e r l a s t n a m e _ f k " ,r e f e r e n c e d C o l u m n N a m e = " l a s t N a m e " ) } ) U s e ru s e r ; @ I dS t r i n gc u s t o m e r N u m b e r ; b o o l e a np r e f e r r e d C u s t o m e r ; } c l a s sC u s t o m e r I di m p l e m e n t sS e r i a l i z a b l e{ @ O n e T o O n eU s e ru s e r ; S t r i n gc u s t o m e r N u m b e r ; / / i m p l e m e n t se q u a l sa n dh a s h C o d e } @ E n t i t y c l a s sU s e r{ @ E m b e d d e d I dU s e r I di d ; I n t e g e ra g e ; / / i m p l e m e n t se q u a l sa n dh a s h C o d e } @ E m b e d d a b l e c l a s sU s e r I di m p l e m e n t sS e r i a l i z a b l e{ S t r i n gf i r s t N a m e ; S t r i n gl a s t N a m e ; }
This feature is of limited interest though as you are likely to have chosen the @ I d C l a s sapproach to stay JPA compliant or you have a quite twisted mind. Here are the equivalent on hbm.xml files:
< c l a s sn a m e = " C u s t o m e r " > < c o m p o s i t e i dc l a s s = " C u s t o m e r I d "m a p p e d = " t r u e " > < k e y m a n y t o o n en a m e = " u s e r " > < c o l u m nn a m e = " u s e r f i r s t n a m e _ f k " / > < c o l u m nn a m e = " u s e r l a s t n a m e _ f k " / > < / k e y m a n y t o o n e > < k e y p r o p e r t yn a m e = " c u s t o m e r N u m b e r " / > < / c o m p o s i t e i d > < p r o p e r t yn a m e = " p r e f e r r e d C u s t o m e r " / > < / c l a s s > < c l a s sn a m e = " U s e r " > < c o m p o s i t e i dn a m e = " i d "c l a s s = " U s e r I d " > < k e y p r o p e r t yn a m e = " f i r s t N a m e " / > < k e y p r o p e r t yn a m e = " l a s t N a m e " / > < / c o m p o s i t e i d > < p r o p e r t yn a m e = " a g e " / > < / c l a s s >
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
50/215
12/30/13
Important
We recommend all new projects to use the new enhanced identifier generators. They are deactivated by default for entities using annotations but can be activated using h i b e r n a t e . i d . n e w _ g e n e r a t o r _ m a p p i n g s = t r u e . These new generators are more efficient and closer to the JPA 2 specification semantic. However they are not backward compatible with existing Hibernate based application (if a sequence or a table is used for id generation). See XXXXXXX ??? for more information on how to activate them.
To mark an id property as generated, use the @ G e n e r a t e d V a l u eannotation. You can specify the strategy used (default to A U T O ) by setting s t r a t e g y .
@ E n t i t y p u b l i cc l a s sC u s t o m e r{ @ I d@ G e n e r a t e d V a l u e I n t e g e rg e t I d ( ){. . .} ; } @ E n t i t y p u b l i cc l a s sI n v o i c e{ @ I d@ G e n e r a t e d V a l u e ( s t r a t e g y = G e n e r a t i o n T y p e . I D E N T I T Y ) I n t e g e rg e t I d ( ){. . .} ; } S E Q U E N C E and T A B L E require additional configurations that you can set using @ S e q u e n c e G e n e r a t o r and @ T a b l e G e n e r a t o r : n a m e : name of the generator t a b l e / s e q u e n c e N a m e :
name
of
the
table
or
the
sequence
(defaulting
respectively
to
h i b e r n a t e _ s e q u e n c e sand h i b e r n a t e _ s e q u e n c e ) c a t a l o g/ s c h e m a : i n i t i a l V a l u e : the value from which the id is to start generating a l l o c a t i o n S i z e : the amount to increment by when allocating id numbers from the generator
To link a table or sequence generator definition with an actual generated property, use the same name in both the definition n a m eand the generator value g e n e r a t o ras shown below.
@ I d @ G e n e r a t e d V a l u e ( s t r a t e g y = G e n e r a t i o n T y p e . S E Q U E N C E , g e n e r a t o r = " S E Q _ G E N " ) @ j a v a x . p e r s i s t e n c e . S e q u e n c e G e n e r a t o r ( n a m e = " S E Q _ G E N " , s e q u e n c e N a m e = " m y _ s e q u e n c e " , a l l o c a t i o n S i z e = 2 0 ) p u b l i cI n t e g e rg e t I d ( ){. . .}
The scope of a generator definition can be the application or the class. Class-defined generators are not visible outside the class and can override application level generators. Application level generators are defined in JPA's XML deployment descriptors (see XXXXXX ???):
< t a b l e g e n e r a t o rn a m e = " E M P _ G E N " t a b l e = " G E N E R A T O R _ T A B L E " p k c o l u m n n a m e = " k e y " v a l u e c o l u m n n a m e = " h i "
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
51/215
12/30/13
If a JPA XML descriptor (like M E T A I N F / o r m . x m l ) is used to define the generators, E M P _ G E N and S E Q _ G E N are application level generators.
Note
Package level definition is not supported by the JPA specification. However, you can use the @ G e n e r i c G e n e r a t o rat the package level (see ???).
These are the four standard JPA generators. Hibernate goes beyond that and provide additional generators or additional options as we will see below. You can also write your own custom identifier generator by implementing o r g . h i b e r n a t e . i d . I d e n t i f i e r G e n e r a t o r . To define a custom generator, use the @ G e n e r i c G e n e r a t o r annotation (and its plural counter part
@ G e n e r i c G e n e r a t o r s ) that describes the class of the identifier generator or its short cut name (as
described below) and a list of key/value parameters. When using @ G e n e r i c G e n e r a t o rand assigning it via
@ G e n e r a t e d V a l u e . g e n e r a t o r , the @ G e n e r a t e d V a l u e . s t r a t e g yis ignored: leave it blank. @ I d@ G e n e r a t e d V a l u e ( g e n e r a t o r = " s y s t e m u u i d " ) @ G e n e r i c G e n e r a t o r ( n a m e = " s y s t e m u u i d " ,s t r a t e g y=" u u i d " ) p u b l i cS t r i n gg e t I d ( ){ @ I d@ G e n e r a t e d V a l u e ( g e n e r a t o r = " t r i g g e r g e n e r a t e d " ) @ G e n e r i c G e n e r a t o r ( n a m e = " t r i g g e r g e n e r a t e d " , s t r a t e g y=" s e l e c t " , p a r a m e t e r s=@ P a r a m e t e r ( n a m e = " k e y " ,v a l u e=" s o c i a l S e c u r i t y N u m b e r " ) ) p u b l i cS t r i n gg e t I d ( ){
The hbm.xml approach uses the optional < g e n e r a t o r > child element inside < i d > . If any parameters are required to configure or initialize the generator instance, they are passed using the < p a r a m >element.
< i dn a m e = " i d "t y p e = " l o n g "c o l u m n = " c a t _ i d " > < g e n e r a t o rc l a s s = " o r g . h i b e r n a t e . i d . T a b l e H i L o G e n e r a t o r " > < p a r a mn a m e = " t a b l e " > u i d _ t a b l e < / p a r a m > < p a r a mn a m e = " c o l u m n " > n e x t _ h i _ v a l u e _ c o l u m n < / p a r a m > < / g e n e r a t o r > < / i d >
5.1.2.2.1. Various additional generators All generators implement the interface o r g . h i b e r n a t e . i d . I d e n t i f i e r G e n e r a t o r . This is a very simple interface. Some applications can choose to provide their own specialized implementations, however, Hibernate provides a range of built-in implementations. The shortcut names for the built-in generators are as follows:
i n c r e m e n t
generates identifiers of type l o n g , s h o r t or i n t that are unique only when no other process is inserting data into the same table. Do not use in a cluster.
i d e n t i t y
supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type l o n g ,s h o r tor i n t .
s e q u e n c e
uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type l o n g ,s h o r tor i n t
h i l o
uses a hi/lo algorithm to efficiently generate identifiers of type l o n g ,s h o r t or i n t , given a table and column (by default h i b e r n a t e _ u n i q u e _ k e y and n e x t _ h i respectively) as a source of hi values. The
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
52/215
12/30/13
uses a hi/lo algorithm to efficiently generate identifiers of type l o n g ,s h o r t or i n t , given a named database sequence.
u u i d
Generates a 128-bit UUID based on a custom algorithm. The value generated is represented as a string of 32 hexidecimal digits. Users can also configure it to use a separator (config parameter "separator") which separates the hexidecimal digits into 8{sep}8{sep}4{sep}8{sep}4. Note specifically that this is different than the IETF RFC 4122 representation of 8-4-4-4-12. If you need RFC 4122 compliant UUIDs, consider using "uuid2" generator discussed below.
u u i d 2
Generates a IETF RFC 4122 compliant (variant 2) 128-bit UUID. The exact "version" (the RFC term) generated depends on the pluggable "generation strategy" used (see below). Capable of generating values as j a v a . u t i l . U U I D ,j a v a . l a n g . S t r i n g or as a byte array of length 16 (b y t e [ 1 6 ] ). The "generation strategy" is defined by the interface o r g . h i b e r n a t e . i d . U U I D G e n e r a t i o n S t r a t e g y . The generator defines 2 configuration parameters for defining which generation strategy to use:
u u i d _ g e n _ s t r a t e g y _ c l a s s
Names the UUIDGenerationStrategy instance to use Out of the box, comes with the following strategies:
o r g . h i b e r n a t e . i d . u u i d . S t a n d a r d R a n d o m S t r a t e g y (the default) - generates "version 3" (aka,
address since mac address not available. If you need mac address to be used, consider leveraging one of the existing third party UUID generators which sniff out mac address and integrating it via the o r g . h i b e r n a t e . i d . U U I D G e n e r a t i o n S t r a t e g y contract. Two such libraries known at time of this writing include http://johannburkard.de/software/uuid/ http://commons.apache.org/sandbox/id/uuid.html
g u i d
and
lets the application assign an identifier to the object before s a v e ( ) is called. This is the default strategy if no < g e n e r a t o r >element is specified.
s e l e c t
retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value.
f o r e i g n
uses the identifier of another associated object. It is usually used in conjunction with a < o n e t o o n e > primary key association.
s e q u e n c e i d e n t i t y
a specialized sequence generation strategy that utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to return the generated identifier value as part of the insert statement execution. This strategy is only supported on Oracle 10g drivers targeted for JDK 1.4. Comments on these insert statements are disabled due to a bug in the Oracle drivers.
5.1.2.2.2. Hi/lo algorithm The h i l o and s e q h i l ogenerators provide two alternate implementations of the hi/lo algorithm. The first implementation requires a "special" database table to hold the next available "hi" value. Where supported, the second uses an Oracle-style sequence.
< i dn a m e = " i d "t y p e = " l o n g "c o l u m n = " c a t _ i d " > < g e n e r a t o rc l a s s = " h i l o " > < p a r a mn a m e = " t a b l e " > h i _ v a l u e < / p a r a m > < p a r a mn a m e = " c o l u m n " > n e x t _ v a l u e < / p a r a m > < p a r a mn a m e = " m a x _ l o " > 1 0 0 < / p a r a m > < / g e n e r a t o r > < / i d > < i dn a m e = " i d "t y p e = " l o n g "c o l u m n = " c a t _ i d " > < g e n e r a t o rc l a s s = " s e q h i l o " > < p a r a mn a m e = " s e q u e n c e " > h i _ v a l u e < / p a r a m > < p a r a mn a m e = " m a x _ l o " > 1 0 0 < / p a r a m > < / g e n e r a t o r >
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
53/215
12/30/13
< / i d >
Unfortunately, you cannot use h i l owhen supplying your own C o n n e c t i o n to Hibernate. When Hibernate uses an application server datasource to obtain connections enlisted with JTA, you must configure the h i b e r n a t e . t r a n s a c t i o n . m a n a g e r _ l o o k u p _ c l a s s .
5.1.2.2.3. UUID algorithm The UUID contains: IP address, startup time of the JVM that is accurate to a quarter second, system time and a counter value that is unique within the JVM. It is not possible to obtain a MAC address or memory address from Java code, so this is the best option without using JNI.
5.1.2.2.4. Identity columns and sequences For databases that support identity columns (DB2, MySQL, Sybase, MS SQL), you can use i d e n t i t y key generation. For databases that support sequences (DB2, Oracle, PostgreSQL, Interbase, McKoi, SAP DB) you can use s e q u e n c estyle key generation. Both of these strategies require two SQL queries to insert a new object. For example:
< i dn a m e = " i d "t y p e = " l o n g "c o l u m n = " p e r s o n _ i d " > < g e n e r a t o rc l a s s = " s e q u e n c e " > < p a r a mn a m e = " s e q u e n c e " > p e r s o n _ i d _ s e q u e n c e < / p a r a m > < / g e n e r a t o r > < / i d > < i dn a m e = " i d "t y p e = " l o n g "c o l u m n = " p e r s o n _ i d "u n s a v e d v a l u e = " 0 " > < g e n e r a t o rc l a s s = " i d e n t i t y " / > < / i d >
For cross-platform development, the n a t i v e strategy will, depending on the capabilities of the underlying database, choose from the i d e n t i t y ,s e q u e n c eand h i l ostrategies.
5.1.2.2.5. Assigned identifiers If you want the application to assign identifiers, as opposed to having Hibernate generate them, you can use the a s s i g n e dgenerator. This special generator uses the identifier value already assigned to the object's identifier property. The generator is used when the primary key is a natural key instead of a surrogate key. This is the default behavior if you do not specify @ G e n e r a t e d V a l u e nor < g e n e r a t o r > elements. The a s s i g n e d generator makes Hibernate use u n s a v e d v a l u e = " u n d e f i n e d " . This forces Hibernate to go to the database to determine if an instance is transient or detached, unless there is a version or timestamp property, or you define I n t e r c e p t o r . i s U n s a v e d ( ) .
5.1.2.2.6. Primary keys assigned by triggers Hibernate does not generate DDL with triggers. It is for legacy schemas only.
< i dn a m e = " i d "t y p e = " l o n g "c o l u m n = " p e r s o n _ i d " > < g e n e r a t o rc l a s s = " s e l e c t " > < p a r a mn a m e = " k e y " > s o c i a l S e c u r i t y N u m b e r < / p a r a m > < / g e n e r a t o r > < / i d >
In the above example, there is a unique valued property named s o c i a l S e c u r i t y N u m b e r . It is defined by the class, as a natural key and a surrogate key named p e r s o n _ i d , whose value is generated by a trigger.
5.1.2.2.7. Identity copy (foreign generator) Finally, you can ask Hibernate to copy the identifier from another associated entity. In the Hibernate jargon, it is known as a foreign generator but the JPA mapping reads better and is encouraged.
@ E n t i t y c l a s sM e d i c a l H i s t o r yi m p l e m e n t sS e r i a l i z a b l e{ @ I d@ O n e T o O n e @ J o i n C o l u m n ( n a m e=" p e r s o n _ i d " ) P e r s o np a t i e n t ; } @ E n t i t y p u b l i cc l a s sP e r s o ni m p l e m e n t sS e r i a l i z a b l e{ @ I d@ G e n e r a t e d V a l u eI n t e g e ri d ; }
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
54/215
12/30/13
Or alternatively
@ E n t i t y c l a s sM e d i c a l H i s t o r yi m p l e m e n t sS e r i a l i z a b l e{ @ I dI n t e g e ri d ; @ M a p s I d@ O n e T o O n e @ J o i n C o l u m n ( n a m e=" p a t i e n t _ i d " ) P e r s o np a t i e n t ; } @ E n t i t y c l a s sP e r s o n{ @ I d@ G e n e r a t e d V a l u eI n t e g e ri d ; }
used.
i n i t i a l _ v a l u e (optional, defaults to 1 ): the initial value to be retrieved from the sequence/table. In
sequence creation terms, this is analogous to the clause typically named "STARTS WITH".
i n c r e m e n t _ s i z e(optional - defaults to 1 ): the value by which subsequent calls to the sequence/table
should differ. In sequence creation terms, this is analogous to the clause typically named "INCREMENT BY".
f o r c e _ t a b l e _ u s e (optional - defaults to f a l s e ): should we force the use of a table as the backing
sequence.
o p t i m i z e r(optional - defaults to n o n e ): See Section 5.1.2.3.1, Identifier generator optimization
The second of these new generators is o r g . h i b e r n a t e . i d . e n h a n c e d . T a b l e G e n e r a t o r , which is intended, firstly, as a replacement for the t a b l e generator, even though it actually functions much more like
o r g . h i b e r n a t e . i d . M u l t i p l e H i L o P e r T a b l e G e n e r a t o r ,
and
secondly,
as
re-implementation
of
Essentially this generator defines a table capable of holding a number of different increment values simultaneously by using multiple distinctly keyed rows. This generator has a number of configuration parameters:
t a b l e _ n a m e(optional - defaults to h i b e r n a t e _ s e q u e n c e s ): the name of the table to be used. v a l u e _ c o l u m n _ n a m e (optional - defaults to n e x t _ v a l ): the name of the column on the table that is
that is used to hold the "segment key". This is the value which identifies which increment value to use.
s e g m e n t _ v a l u e(optional - defaults to d e f a u l t ): The "segment key" value for the segment from which
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
55/215
12/30/13
differ.
o p t i m i z e r(optional - defaults to ? ? ): See Section 5.1.2.3.1, Identifier generator optimization.
5.1.2.3.1. Identifier generator optimization For identifier generators that store values in the database, it is inefficient for them to hit the database on each and every call to generate a new identifier value. Instead, you can group a bunch of them in memory and only hit the database when you have exhausted your in-memory value group. This is the role of the pluggable optimizers. Currently only the two enhanced generators (Section 5.1.2.3, Enhanced identifier generators support this operation.
n o n e (generally this is the default if no optimizer was specified): this will not perform any
optimizations and hit the database for each and every request.
h i l o : applies a hi/lo algorithm around the database retrieved values. The values from the database
for this optimizer are expected to be sequential. The values retrieved from the database structure for this optimizer indicates the "group number". The i n c r e m e n t _ s i z e is multiplied by that value in memory to define a group "hi value".
p o o l e d : as with the case of h i l o , this optimizer attempts to minimize the number of hits to the
database. Here, however, 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. Here, i n c r e m e n t _ s i z erefers to the values coming from the database.
Warning
The Hibernate team has always felt such a construct as fundamentally wrong. Try hard to fix your data model before using this feature.
@ E n t i t y p u b l i cc l a s sC u s t o m e r I n v e n t o r yi m p l e m e n t sS e r i a l i z a b l e{ @ I d @ T a b l e G e n e r a t o r ( n a m e=" i n v e n t o r y " , t a b l e=" U _ S E Q U E N C E S " , p k C o l u m n N a m e=" S _ I D " , v a l u e C o l u m n N a m e=" S _ N E X T N U M " , p k C o l u m n V a l u e=" i n v e n t o r y " , a l l o c a t i o n S i z e=1 0 0 0 ) @ G e n e r a t e d V a l u e ( s t r a t e g y=G e n e r a t i o n T y p e . T A B L E ,g e n e r a t o r=" i n v e n t o r y " ) I n t e g e ri d ; @ I d@ M a n y T o O n e ( c a s c a d e=C a s c a d e T y p e . M E R G E ) C u s t o m e rc u s t o m e r ; } @ E n t i t y p u b l i cc l a s sC u s t o m e ri m p l e m e n t sS e r i a l i z a b l e{ @ I d p r i v a t ei n ti d ; }
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
56/215
12/30/13
The version property will be mapped to the O P T L O C Kcolumn, and the entity manager will use it to detect conflicting updates (preventing lost updates you might otherwise see with the last-commit-wins strategy). The version column may be a numeric. Hibernate supports any kind of type provided that you define and implement the appropriate U s e r V e r s i o n T y p e . The application must not alter the version number set up by Hibernate in any way. To artificially increase the version number, check in Hibernate Entity Manager's reference documentation
L o c k M o d e T y p e . O P T I M I S T I C _ F O R C E _ I N C R E M E N Tor L o c k M o d e T y p e . P E S S I M I S T I C _ F O R C E _ I N C R E M E N T .
If the version number is generated by the database (via a trigger for example), make sure to use
@ o r g . h i b e r n a t e . a n n o t a t i o n s . G e n e r a t e d ( G e n e r a t i o n T i m e . A L W A Y S ) .
number.
n a m e : the name of a property of the persistent class. t y p e(optional - defaults to i n t e g e r ): the type of the version number. a c c e s s(optional - defaults to p r o p e r t y ): the strategy Hibernate uses to access the property
value.
u n s a v e d v a l u e(optional - defaults to u n d e f i n e d ): a version property value that indicates that an
instance is newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in a previous session. U n d e f i n e dspecifies that the identifier property value should be used.
g e n e r a t e d(optional - defaults to n e v e r ): specifies that this version property value is generated
by the database. See the discussion of generated properties for more information.
i n s e r t(optional - defaults to t r u e ): specifies whether the version column should be included in
SQL insert statements. It can be set to f a l s eif the database column is defined with a default value of 0 .
5.1.3.2. Timestamp
Alternatively, you can use a timestamp. Timestamps are a less safe implementation of optimistic locking. However, sometimes an application might use the timestamps in other ways as well. Simply mark a property of type D a t eor C a l e n d a ras @ V e r s i o n .
@ E n t i t y p u b l i cc l a s sF l i g h ti m p l e m e n t sS e r i a l i z a b l e{ . . . @ V e r s i o n p u b l i cD a t eg e t L a s t U p d a t e ( ){. . .} }
When using timestamp versioning you can tell Hibernate where to retrieve the timestamp value from database or JVM - by optionally adding the @ o r g . h i b e r n a t e . a n n o t a t i o n s . S o u r c e annotation to the property. Possible values for the value attribute of the annotation are
o r g . h i b e r n a t e . a n n o t a t i o n s . S o u r c e T y p e . V M and o r g . h i b e r n a t e . a n n o t a t i o n s . S o u r c e T y p e . D B . The default
is S o u r c e T y p e . D Bwhich is also used in case there is no @ S o u r c eannotation at all. Like in the case of version numbers, the timestamp can also be generated by the database instead of Hibernate. To do that, use @ o r g . h i b e r n a t e . a n n o t a t i o n s . G e n e r a t e d ( G e n e r a t i o n T i m e . A L W A Y S ) . In hbm.xml, use the < t i m e s t a m p >element:
< t i m e s t a m p c o l u m n = " t i m e s t a m p _ c o l u m n " n a m e = " p r o p e r t y N a m e " a c c e s s = " f i e l d | p r o p e r t y | C l a s s N a m e "
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
57/215
12/30/13
class.
a c c e s s(optional - defaults to p r o p e r t y ): the strategy Hibernate uses for accessing the property
value.
u n s a v e d v a l u e(optional - defaults to n u l l ): a version property value that indicates that an
instance is newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in a previous session. U n d e f i n e dspecifies that the identifier property value should be used.
s o u r c e(optional - defaults to v m ): Where should Hibernate retrieve the timestamp value from?
From the database, or from the current JVM? Database-based timestamps incur an overhead because Hibernate must hit the database in order to determine the "next value". It is safer to use in clustered environments. Not all D i a l e c t sare known to support the retrieval of the database's current timestamp. Others may also be unsafe for usage in locking due to lack of precision (Oracle 8, for example).
g e n e r a t e d(optional - defaults to n e v e r ): specifies that this timestamp property value is actually
generated by the database. See the discussion of generated properties for more information.
Note
< T i m e s t a m p >
is
equivalent
to
< v e r s i o n
And
5.1.4. Property
You need to decide which property needs to be made persistent in a given entity. This differs slightly between the annotation driven metadata and the hbm.xml files.
that a better approach is to use the @ N o t N u l lannotation of the Bean Validation specification. Let's look at a few examples:
p u b l i ct r a n s i e n ti n tc o u n t e r ;/ / t r a n s i e n tp r o p e r t y p r i v a t eS t r i n gf i r s t n a m e ;/ / p e r s i s t e n tp r o p e r t y @ T r a n s i e n t S t r i n gg e t L e n g t h I n M e t e r ( ){. . .}/ / t r a n s i e n tp r o p e r t y S t r i n gg e t N a m e ( ){ . . .}/ /p e r s i s t e n tp r o p e r t y @ B a s i c i n tg e t L e n g t h ( ){. . .}/ /p e r s i s t e n tp r o p e r t y @ B a s i c ( f e t c h=F e t c h T y p e . L A Z Y ) S t r i n gg e t D e t a i l e d C o m m e n t ( ){. . .}/ /p e r s i s t e n tp r o p e r t y @ T e m p o r a l ( T e m p o r a l T y p e . T I M E ) j a v a . u t i l . D a t eg e t D e p a r t u r e T i m e ( ){. . .}/ /p e r s i s t e n tp r o p e r t y @ E n u m e r a t e d ( E n u m T y p e . S T R I N G ) S t a r r e dg e t N o t e ( ){. . .}/ / e n u mp e r s i s t e da sS t r i n gi nd a t a b a s e c o u n t e r , a transient field, and l e n g t h I n M e t e r , a method annotated as @ T r a n s i e n t , and will be ignored
by the Hibernate. n a m e ,l e n g t h , and f i r s t n a m e properties are mapped persistent and eagerly fetched (the default for simple properties). The d e t a i l e d C o m m e n t property value will be lazily fetched from the database once a lazy property of the entity is accessed for the first time. Usually you don't need to lazy simple properties (not to be confused with lazy association fetching). The recommended alternative is to use the projection capability of JP-QL (Java Persistence Query Language) or Criteria queries. JPA support property mapping of all basic types supported by Hibernate (all basic Java types , their respective wrappers and serializable classes). Hibernate Annotations supports out of the box enum type mapping either into a ordinal column (saving the enum ordinal) or a string based column (saving
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
58/215
12/30/13
tune that.
@ L o bindicates that the property should be persisted in a Blob or a Clob depending on the property type: j a v a . s q l . C l o b , C h a r a c t e r [ ] , c h a r [ ] and java.lang.S t r i n g will be persisted in a Clob. j a v a . s q l . B l o b , B y t e [ ] ,b y t e [ ] and S e r i a l i z a b l etype will be persisted in a Blob. @ L o b p u b l i cS t r i n gg e t F u l l T e x t ( ){ r e t u r nf u l l T e x t ; } @ L o b p u b l i cb y t e [ ]g e t F u l l C o d e ( ){ r e t u r nf u l l C o d e ; }
If the property type implements j a v a . i o . S e r i a l i z a b l eand is not a basic type, and if the property is not annotated with @ L o b , then the Hibernate s e r i a l i z a b l etype is used.
5.1.4.1.1. Type You can also manually specify a type using the @ o r g . h i b e r n a t e . a n n o t a t i o n s . T y p eand some parameters if needed. @ T y p e . t y p ecould be: 1. The etc. 2. The name of a Java class with a default basic type:
i n t ,f l o a t ,c h a r ,j a v a . l a n g . S t r i n g ,j a v a . u t i l . D a t e ,j a v a . l a n g . I n t e g e r ,j a v a . s q l . C l o betc.
name
of
Hibernate
basic
type:
i n t e g e r ,s t r i n g , c h a r a c t e r ,d a t e , t i m e s t a m p , f l o a t , b i n a r y ,s e r i a l i z a b l e , o b j e c t , b l o b
3. The name of a serializable Java class. 4. The class name of a custom type: c o m . i l l f l o w . t y p e . M y C u s t o m T y p eetc. If you do not specify a type, Hibernate will use reflection upon the named property and guess the correct Hibernate type. Hibernate will attempt to interpret the name of the return class of the property getter using, in order, rules 2, 3, and 4.
@ o r g . h i b e r n a t e . a n n o t a t i o n s . T y p e D e f and @ o r g . h i b e r n a t e . a n n o t a t i o n s . T y p e D e f s allows you to declare
type definitions. These annotations can be placed at the class or package level. Note that these definitions are global for the session factory (even when defined at the class level). If the type is used on a single entity, you can place the definition on the entity itself. Otherwise, it is recommended to place the definition at the package level. In the example below, when Hibernate encounters a property of class P h o n e N u m e r , it delegates the persistence strategy to the custom mapping type P h o n e N u m b e r T y p e . However, properties belonging to other classes, too, can delegate their persistence strategy to P h o n e N u m b e r T y p e , by explicitly using the @ T y p eannotation.
Note
Package level annotations are placed in a file named p a c k a g e i n f o . j a v a in the appropriate package. Place your annotations before the package declaration.
The following example shows the usage of the p a r a m e t e r sattribute to customize the TypeDef.
/ / i no r g / h i b e r n a t e / t e s t / a n n o t a t i o n s / e n t i t y / p a c k a g e i n f o . j a v a @ T y p e D e f s ( { @ T y p e D e f ( n a m e = " c a s t e r " , t y p e C l a s s=C a s t e r S t r i n g T y p e . c l a s s , p a r a m e t e r s={ @ P a r a m e t e r ( n a m e = " c a s t " ,v a l u e = " l o w e r " ) } ) } )
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
59/215
12/30/13
When using composite user type, you will have to express column definitions. The @ C o l u m n s has been introduced for that purpose.
@ T y p e ( t y p e = " o r g . h i b e r n a t e . t e s t . a n n o t a t i o n s . e n t i t y . M o n e t a r y A m o u n t U s e r T y p e " ) @ C o l u m n s ( c o l u m n s={ @ C o l u m n ( n a m e = " r _ a m o u n t " ) , @ C o l u m n ( n a m e = " r _ c u r r e n c y " ) } ) p u b l i cM o n e t a r y A m o u n tg e t A m o u n t ( ){ r e t u r na m o u n t ; } p u b l i cc l a s sM o n e t a r y A m o u n ti m p l e m e n t sS e r i a l i z a b l e{ p r i v a t eB i g D e c i m a la m o u n t ; p r i v a t eC u r r e n c yc u r r e n c y ; . . . }
5.1.4.1.2. Access type By default the access type of a class hierarchy is defined by the position of the @ I d or @ E m b e d d e d I d annotations. If these annotations are on a field, then only fields are considered for persistence and the state is accessed via the field. If these annotations are on a getter, then only the getters are considered for persistence and the state is accessed via the getter/setter. That works well in practice and is the recommended approach.
Note
The placement of annotations within a class hierarchy has to be consistent (either field or on property) to be able to determine the default access type. It is recommended to stick to one single annotation placement strategy throughout your whole application.
However in some situations, you need to: force the access type of the entity hierarchy override the access type of a specific entity in the class hierarchy override the access type of an embeddable type The best use case is an embeddable class used by several entities that might not use the same access type. In this case it is better to force the access type at the embeddable class level. To force the access type on a given class, use the @ A c c e s sannotation as showed below:
@ E n t i t y p u b l i cc l a s sO r d e r{ @ I dp r i v a t eL o n gi d ; p u b l i cL o n gg e t I d ( ){r e t u r ni d ;} p u b l i cv o i ds e t I d ( L o n gi d ){t h i s . i d=i d ;} @ E m b e d d e dp r i v a t eA d d r e s sa d d r e s s ; p u b l i cA d d r e s sg e t A d d r e s s ( ){r e t u r na d d r e s s ;} p u b l i cv o i ds e t A d d r e s s ( ){t h i s . a d d r e s s=a d d r e s s ;} } @ E n t i t y p u b l i cc l a s sU s e r{ p r i v a t eL o n gi d ; @ I dp u b l i cL o n gg e t I d ( ){r e t u r ni d ;} p u b l i cv o i ds e t I d ( L o n gi d ){t h i s . i d=i d ;} p r i v a t eA d d r e s sa d d r e s s ; @ E m b e d d e dp u b l i cA d d r e s sg e t A d d r e s s ( ){r e t u r na d d r e s s ;} p u b l i cv o i ds e t A d d r e s s ( ){t h i s . a d d r e s s=a d d r e s s ;} } @ E m b e d d a b l e @ A c c e s s ( A c e s s T y p e . P R O P E R T Y ) p u b l i cc l a s sA d d r e s s{ p r i v a t eS t r i n gs t r e e t 1 ; p u b l i cS t r i n gg e t S t r e e t 1 ( ){r e t u r ns t r e e t 1 ;} p u b l i cv o i ds e t S t r e e t 1 ( ){t h i s . s t r e e t 1=s t r e e t 1 ;} p r i v a t eh a s h C o d e ;/ / n o tp e r s i s t e n t }
You can also override the access type of a single property while keeping the other properties standard.
@ E n t i t y p u b l i cc l a s sO r d e r{ @ I dp r i v a t eL o n gi d ; p u b l i cL o n gg e t I d ( ){r e t u r ni d ;} p u b l i cv o i ds e t I d ( L o n gi d ){t h i s . i d=i d ;}
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
60/215
12/30/13
In this example, the default access type is F I E L D except for the o r d e r N u m b e r property. Note that the corresponding field, if any must be marked as @ T r a n s i e n tor t r a n s i e n t .
@org.hibernate.annotations.AccessType
The annotation
@ o r g . h i b e r n a t e . a n n o t a t i o n s . A c c e s s T y p e
should
be
considered deprecated for FIELD and PROPERTY access. It is still useful however if you need to use a custom access type.
5.1.4.1.3. Optimistic lock It is sometimes useful to avoid increasing the version number even if a given property is dirty (particularly collections). You can do that by annotating the property (or collection) with
@ O p t i m i s t i c L o c k ( e x c l u d e d = t r u e ) .
More formally, specifies that updates to this property do not require acquisition of the optimistic lock.
5.1.4.1.4. Declaring column attributes The column(s) used for a property mapping can be defined using the @ C o l u m n annotation. Use it to override default values (see the JPA specification for more information on the defaults). You can use this annotation at the property level for properties that are: not annotated at all annotated with @ B a s i c annotated with @ V e r s i o n annotated with @ L o b annotated with @ T e m p o r a l
The n a m eproperty is mapped to the f l i g h t _ n a m ecolumn, which is not nullable, has a length of 50 and is not updatable (making the property immutable). This annotation can be applied to regular properties as well as @ I dor @ V e r s i o nproperties.
@ C o l u m n ( n a m e = " c o l u m n N a m e " ; b o o l e a nu n i q u e ( )d e f a u l tf a l s e ; b o o l e a nn u l l a b l e ( )d e f a u l tt r u e ; b o o l e a ni n s e r t a b l e ( )d e f a u l tt r u e ; b o o l e a nu p d a t a b l e ( )d e f a u l tt r u e ; S t r i n gc o l u m n D e f i n i t i o n ( )d e f a u l t" " ; S t r i n gt a b l e ( )d e f a u l t" " ; i n tl e n g t h ( )d e f a u l t2 5 5 ; i n tp r e c i s i o n ( )d e f a u l t0 ;/ /d e c i m a lp r e c i s i o n i n ts c a l e ( )d e f a u l t0 ;/ /d e c i m a ls c a l e n a m e(optional): the column name (default to the property name) u n i q u e(optional): set a unique constraint on this column or not (default false) n u l l a b l e(optional): set the column as nullable (default true). i n s e r t a b l e(optional): whether or not the column will be part of the insert statement (default
true)
u p d a t a b l e(optional): whether or not the column will be part of the update statement (default
true)
c o l u m n D e f i n i t i o n(optional): override the sql DDL fragment for this particular column (non
portable)
t a b l e(optional): define the targeted table (default primary table) l e n g t h(optional): column length (default 255) p r e c i s i o n(optional): column decimal precision (default 0) s c a l e(optional): column decimal scale if useful (default 0)
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
61/215
12/30/13
5.1.4.1.5. Formula
Sometimes, you want the Database to do some computation for you rather than in the JVM, you might also create some kind of virtual column. You ca n use a SQL fragment (aka formula) instead of mapping a property into a column. This kind of property is read only (its value is calculated by your formula fragment).
@ F o r m u l a ( " o b j _ l e n g t h*o b j _ h e i g h t*o b j _ w i d t h " ) p u b l i cl o n gg e t O b j e c t V o l u m e ( )
The SQL fragment can be as complex as you want and even include subselects.
5.1.4.1.6. Non-annotated property defaults If a property is not annotated, the following rules apply: If the property is of a single type, it is mapped as @Basic Otherwise, if the type of the property is annotated as @Embeddable, it is mapped as @Embedded Otherwise, if the type of the property is S e r i a l i z a b l e , it is mapped as @ B a s i cin a column holding the object in its serialized version Otherwise, if the type of the property is j a v a . s q l . C l o b or j a v a . s q l . B l o b , it is mapped as @ L o b with the appropriate L o b T y p e
included in SQL U P D A T Eand/or I N S E R Tstatements. Setting both to f a l s eallows a pure "derived" property whose value is initialized from some other property that maps to the same column(s), or by a trigger or other application.
f o r m u l a(optional): an SQL expression that defines the value for a computed property. Computed
value.
l a z y(optional - defaults to f a l s e ): specifies that this property should be fetched lazily when the
not require acquisition of the optimistic lock. In other words, it determines if a version increment should occur when this property is dirty.
g e n e r a t e d(optional - defaults to n e v e r ): specifies that this property value is actually generated
by the database. See the discussion of generated properties for more information. typename could be: 1. The etc. 2. The name of a Java class with a default basic type:
i n t ,f l o a t ,c h a r ,j a v a . l a n g . S t r i n g ,j a v a . u t i l . D a t e ,j a v a . l a n g . I n t e g e r ,j a v a . s q l . C l o betc.
name
of
Hibernate
basic
type:
i n t e g e r ,s t r i n g , c h a r a c t e r ,d a t e , t i m e s t a m p , f l o a t , b i n a r y ,s e r i a l i z a b l e , o b j e c t , b l o b
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
62/215
12/30/13
You can reference the entity table by not declaring an alias on a particular column. This would be c u s t o m e r I din the given example. You can also use the nested < f o r m u l a >mapping element if you do not want to use the attribute.
An embeddable object inherits the access type of its owning entity (note that you can override that using the @ A c c e s sannotation). The P e r s o n entity has two component properties, h o m e A d d r e s s and b o r n I n . h o m e A d d r e s s property has not been annotated, but Hibernate will guess that it is a persistent component by looking for the @ E m b e d d a b l e annotation in the Address class. We also override the mapping of a column name (to
b o r n C o u n t r y N a m e ) with the @ E m b e d d e dand @ A t t r i b u t e O v e r r i d e annotations for each mapped attribute of C o u n t r y . As you can see, C o u n t r y is also a ne sted component of A d d r e s s , again using auto-detection by
Hibernate and JPA defaults. Overriding columns of embedded objects of embedded objects is through dotted expressions.
@ E m b e d d e d @ A t t r i b u t e O v e r r i d e s ({ @ A t t r i b u t e O v e r r i d e ( n a m e = " c i t y " ,c o l u m n=@ C o l u m n ( n a m e = " f l d _ c i t y " )) , @ A t t r i b u t e O v e r r i d e ( n a m e = " n a t i o n a l i t y . i s o 2 " ,c o l u m n=@ C o l u m n ( n a m e = " n a t _ I s o 2 " )) , @ A t t r i b u t e O v e r r i d e ( n a m e = " n a t i o n a l i t y . n a m e " ,c o l u m n=@ C o l u m n ( n a m e = " n a t _ C o u n t r y N a m e " )) / / n a t i o n a l i t yc o l u m n si nh o m e A d d r e s sa r eo v e r r i d d e n
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
63/215
12/30/13
Hibernate Annotations supports something that is not explicitly supported by the JPA specification. You can annotate a embedded object with the @ M a p p e d S u p e r c l a s s annotation to make the superclass properties persistent (see @ M a p p e d S u p e r c l a s sfor more informations). You can also use association annotations in an embeddable object (ie @ O n e T o O n e , @ M a n y T o O n e ,
@ O n e T o M a n yor @ M a n y T o M a n y ). To override the association columns you can use @ A s s o c i a t i o n O v e r r i d e .
If you want to have the same embeddable object type twice in the same entity, the column name defaulting will not work as several embedded objects would share the same set of columns. In plain JPA, you need to override at least one set of columns. Hibernate, however, allows you to enhance the default naming mechanism through the N a m i n g S t r a t e g y interface. You can write a strategy that prevent name clashing in such a situation. D e f a u l t C o m p o n e n t S a f e N a m i n g S t r a t e g yis an example of this. If a property of the embedded object points back to the owning entity, annotate it with the @ P a r e n t annotation. Hibernate will make sure this property is properly loaded with the entity reference. In XML, use the < c o m p o n e n t >element.
< c o m p o n e n t n a m e = " p r o p e r t y N a m e " c l a s s = " c l a s s N a m e " i n s e r t = " t r u e | f a l s e " u p d a t e = " t r u e | f a l s e " a c c e s s = " f i e l d | p r o p e r t y | C l a s s N a m e " l a z y = " t r u e | f a l s e " o p t i m i s t i c l o c k = " t r u e | f a l s e " u n i q u e = " t r u e | f a l s e " n o d e = " e l e m e n t n a m e | . " > < p r o p e r t y. . . . . / > < m a n y t o o n e. . . ./ > . . . . . . . . < / c o m p o n e n t > n a m e : the name of the property. c l a s s(optional - defaults to the property type determined by reflection): the name of the
value.
l a z y(optional - defaults to f a l s e ): specifies that this component should be fetched lazily when
or do not require acquisition of the optimistic lock. It determines if a version increment should occur when this property is dirty.
u n i q u e(optional - defaults to f a l s e ): specifies that a unique constraint exists upon all mapped
columns of the component. The child < p r o p e r t y >tags map properties of the child class to table columns. The < c o m p o n e n t >element allows a < p a r e n t >subelement that maps a property of the component class as a reference back to the containing entity. The < d y n a m i c c o m p o n e n t > element allows a M a p to be mapped as a component, where the property names refer to keys of the map. See Section 9.5, Dynamic components for more information. This feature is not supported in annotations.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
64/215
12/30/13
In hbm.xml, for the table-per-class-hierarchy mapping strategy, the < s u b c l a s s > declaration is used. For example:
< s u b c l a s s n a m e = " C l a s s N a m e " d i s c r i m i n a t o r v a l u e = " d i s c r i m i n a t o r _ v a l u e " p r o x y = " P r o x y I n t e r f a c e " l a z y = " t r u e | f a l s e " d y n a m i c u p d a t e = " t r u e | f a l s e " d y n a m i c i n s e r t = " t r u e | f a l s e " e n t i t y n a m e = " E n t i t y N a m e " n o d e = " e l e m e n t n a m e " e x t e n d s = " S u p e r c l a s s N a m e " > < p r o p e r t y. . . ./ > . . . . . < / s u b c l a s s > n a m e : the fully qualified class name of the subclass. d i s c r i m i n a t o r v a l u e(optional - defaults to the class name): a value that distinguishes individual
subclasses.
p r o x y(optional): specifies a class or interface used for lazy initializing proxies. l a z y(optional - defaults to t r u e ): setting l a z y = " f a l s e "disables the use of lazy fetching.
For information about inheritance mappings see Chapter 10, Inheritance mapping.
5.1.6.1.1. Discriminator Discriminators are required for polymorphic persistence using the table-per-class-hierarchy mapping strategy. It declares a discriminator column of the table. The discriminator column contains marker values that tell the persistence layer what subclass to instantiate for a particular row. Hibernate Core supports the follwoing restricted set of types as discriminator column: s t r i n g ,c h a r a c t e r ,i n t e g e r ,b y t e ,
s h o r t ,b o o l e a n ,y e s _ n o ,t r u e _ f a l s e .
Use the @ D i s c r i m i n a t o r C o l u m nto define the discriminator column as well as the discriminator type.
Note
T h e e n u m D i s c r i m i n a t o r T y p e
used
in
j a v a x . p e r s i t e n c e . D i s c r i m i n a t o r C o l u m n only contains the values S T R I N G , C H A R and I N T E G E R which means that not all Hibernate supported types are
You can also use @ D i s c r i m i n a t o r F o r m u l a to express in SQL a virtual discriminator column. This is particularly useful when the discriminator value can be extracted from one or more columns of the table. Both @ D i s c r i m i n a t o r C o l u m n and @ D i s c r i m i n a t o r F o r m u l a are to be set on the root entity (once per persisted hierarchy).
@ o r g . h i b e r n a t e . a n n o t a t i o n s . D i s c r i m i n a t o r O p t i o n s allows
discriminator options which are not standardized in JPA. The available options are f o r c eand i n s e r t . The
f o r c eattribute is useful if the table contains rows with "extra" discriminator values that are not mapped
to a persistent class. This could for example occur when working with a legacy database. If f o r c e is set to t r u eHibernate will specify the allowed discriminator values in the S E L E C Tquery, even when retrieving all instances of the root class. The second option - i n s e r t- tells Hibernate whether or not to include the discriminator column in SQL I N S E R T s . Usually the column should be part of the I N S E R T statement, but if your discriminator column is also part of a mapped composite identifier you have to set this option to
f a l s e .
Tip
There is also which a
@ o r g . h i b e r n a t e . a n n o t a t i o n s . F o r c e D i s c r i m i n a t o r
is deprecated @ D i s c r i m i n a t o r O p t i o n sinstead.
annotation
since
version
3.6.
Use
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
65/215
12/30/13
In hbm.xml, the < d i s c r i m i n a t o r >element is used to define the discriminator column or formula:
< d i s c r i m i n a t o r c o l u m n = " d i s c r i m i n a t o r _ c o l u m n " t y p e = " d i s c r i m i n a t o r _ t y p e " f o r c e = " t r u e | f a l s e " i n s e r t = " t r u e | f a l s e " f o r m u l a = " a r b i t r a r ys q le x p r e s s i o n " / > c o l u m n(optional - defaults to c l a s s ): the name of the discriminator column. t y p e(optional - defaults to s t r i n g ): a name that indicates the Hibernate type f o r c e(optional - defaults to f a l s e ): "forces" Hibernate to specify the allowed discriminator
mapped composite identifier. It tells Hibernate not to include the column in SQL I N S E R T s .
f o r m u l a(optional): an arbitrary SQL expression that is executed when a type has to be
evaluated. It allows content-based discrimination. Actual values of the discriminator column are specified by the d i s c r i m i n a t o r v a l u e attribute of the
< c l a s s >and < s u b c l a s s >elements.
The f o r m u l a attribute allows you to declare an arbitrary SQL expression that will be used to evaluate the type of a row. For example:
< d i s c r i m i n a t o r f o r m u l a = " c a s ew h e nC L A S S _ T Y P Ei n( ' a ' ,' b ' ,' c ' )t h e n0e l s e1e n d " t y p e = " i n t e g e r " / >
Note
The table name still defaults to the non qualified class name. Also if @ P r i m a r y K e y J o i n C o l u m nis not set, the primary key / foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
66/215
12/30/13
Use the < k e y >element to declare the primary key / foreign key column. The mapping at the start of the chapter would then be re-written as:
< ? x m lv e r s i o n = " 1 . 0 " ? > < ! D O C T Y P Eh i b e r n a t e m a p p i n gP U B L I C " / / H i b e r n a t e / H i b e r n a t eM a p p i n gD T D / / E N " " h t t p : / / w w w . h i b e r n a t e . o r g / d t d / h i b e r n a t e m a p p i n g 3 . 0 . d t d " > < h i b e r n a t e m a p p i n gp a c k a g e = " e g " > < c l a s sn a m e = " C a t "t a b l e = " C A T S " > < i dn a m e = " i d "c o l u m n = " u i d "t y p e = " l o n g " > < g e n e r a t o rc l a s s = " h i l o " / > < / i d > < p r o p e r t yn a m e = " b i r t h d a t e "t y p e = " d a t e " / > < p r o p e r t yn a m e = " c o l o r "n o t n u l l = " t r u e " / > < p r o p e r t yn a m e = " s e x "n o t n u l l = " t r u e " / > < p r o p e r t yn a m e = " w e i g h t " / > < m a n y t o o n en a m e = " m a t e " / > < s e tn a m e = " k i t t e n s " > < k e yc o l u m n = " M O T H E R " / > < o n e t o m a n yc l a s s = " C a t " / > < / s e t > < j o i n e d s u b c l a s sn a m e = " D o m e s t i c C a t "t a b l e = " D O M E S T I C _ C A T S " > < k e yc o l u m n = " C A T " / > < p r o p e r t yn a m e = " n a m e "t y p e = " s t r i n g " / > < / j o i n e d s u b c l a s s > < / c l a s s > < c l a s sn a m e = " e g . D o g " > < ! -m a p p i n gf o rD o gc o u l dg oh e r e> < / c l a s s > < / h i b e r n a t e m a p p i n g >
For information about inheritance mappings see Chapter 10, Inheritance mapping.
Or in hbm.xml:
< u n i o n s u b c l a s s n a m e = " C l a s s N a m e " t a b l e = " t a b l e n a m e " p r o x y = " P r o x y I n t e r f a c e " l a z y = " t r u e | f a l s e " d y n a m i c u p d a t e = " t r u e | f a l s e " d y n a m i c i n s e r t = " t r u e | f a l s e " s c h e m a = " s c h e m a " c a t a l o g = " c a t a l o g " e x t e n d s = " S u p e r c l a s s N a m e " a b s t r a c t = " t r u e | f a l s e " p e r s i s t e r = " C l a s s N a m e " s u b s e l e c t = " S Q Le x p r e s s i o n " e n t i t y n a m e = " E n t i t y N a m e " n o d e = " e l e m e n t n a m e " > < p r o p e r t y. . . ./ > . . . . . < / u n i o n s u b c l a s s > n a m e : the fully qualified class name of the subclass. t a b l e : the name of the subclass table. p r o x y(optional): specifies a class or interface to use for lazy initializing proxies. l a z y(optional, defaults to t r u e ): setting l a z y = " f a l s e "disables the use of lazy fetching.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
67/215
12/30/13
subclasses. Remember that the embeddable superclass is not the root of the hierarchy though.
Note
Properties from superclasses not mapped ignored. as @ M a p p e d S u p e r c l a s s are
Note
The default access type (field or methods) is used, unless you use the
@ A c c e s sannotation.
Note
The same notion can be applied to @ E m b e d d a b l eobjects to persist properties from their superclasses. You also need to use @ M a p p e d S u p e r c l a s s to do that (this should not be considered as a standard EJB3 feature though)
Note
It is allowed to mark a class as @ M a p p e d S u p e r c l a s s in the middle of the mapped inheritance hierarchy.
Note
Any class in the hierarchy non annotated with @ M a p p e d S u p e r c l a s s nor
@ E n t i t ywill be ignored.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
68/215
12/30/13
The a l t i t u d e property will be persisted in an f l d _ a l t i t u d e column of table P l a n e and the propulsion association will be materialized in a f l d _ p r o p u l s i o n _ f kforeign key column. You can define
@ A t t r i b u t e O v e r r i d e (s)
and
@ A s s o c i a t i o n O v e r r i d e (s)
on
@ E n t i t y
classes,
In hbm.xml, simply map the properties of the superclass in the < c l a s s >element of the entity that needs to inherit them.
In this example, n a m e will be in M a i n C a t .s t o r y P a r t 1 will be in C a t 1 and s t o r y P a r t 2 will be in C a t 2 .C a t 1 will be joined to M a i n C a t using the c a t _ i d as a foreign key, and C a t 2 using i d (ie the same column name, the M a i n C a tid column has). Plus a unique constraint on s t o r y P a r t 2has been set. There is also additional tuning accessible via the @ o r g . h i b e r n a t e . a n n o t a t i o n s . T a b l eannotation:
f e t c h : If set to JOIN, the default, Hibernate will use an inner join to retrieve a secondary table
defined by a class or its superclasses and an outer join for a secondary table defined by a subclass. If set to S E L E C T then Hibernate will use a sequential select for a secondary table defined on a subclass, which will be issued only if a row turns out to represent an instance of the subclass. Inner joins will still be used to retrieve a secondary defined by the class and its superclasses.
i n v e r s e : If true, Hibernate will not try to insert or update the properties defined by this join. Default
to false.
o p t i o n a l : If enabled (the default), 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.
f o r e i g n K e y : defines the Foreign Key name of a secondary table pointing back to the primary table.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
69/215
12/30/13
element.
c a t a l o g(optional): overrides the catalog name specified by the root < h i b e r n a t e m a p p i n g >
element.
f e t c h(optional - defaults to j o i n ): if set to j o i n , the default, Hibernate will use an inner join to
retrieve a < j o i n >defined by a class or its superclasses. It will use an outer join for a < j o i n > defined by a subclass. If set to s e l e c tthen Hibernate will use a sequential select for a < j o i n > defined on a subclass. This will be issued only if a row represents an instance of the subclass. Inner joins will still be used to retrieve a < j o i n >defined by the class and its superclasses.
i n v e r s e(optional - defaults to f a l s e ): if enabled, Hibernate will not insert or update the
properties defined by this join are non-null. It will always use an outer join to retrieve the properties. For example, address information for a person can be mapped to a separate table while preserving value type semantics for all properties:
< c l a s sn a m e = " P e r s o n " t a b l e = " P E R S O N " > < i dn a m e = " i d "c o l u m n = " P E R S O N _ I D " > . . . < / i d > < j o i nt a b l e = " A D D R E S S " > < k e yc o l u m n = " A D D R E S S _ I D " / > < p r o p e r t yn a m e = " a d d r e s s " / > < p r o p e r t yn a m e = " z i p " / > < p r o p e r t yn a m e = " c o u n t r y " / > < / j o i n > . . .
This feature is often only useful for legacy data models. We recommend fewer tables than classes and a fine-grained domain model. However, it is useful for switching between inheritance mapping strategies in a single hierarchy, as explained later.
name. You usually don't need this parameter since the default value (the type of the property that stores the association) is good in almost all cases. However this is useful when you want to use interfaces as the return type instead of the regular entity. Setting a value of the c a s c a d e attribute to any meaningful value other than nothing will propagate certain operations to the associated object. The meaningful values are divided into three categories. 1. basic operations, which include:
p e r s i s t ,m e r g e ,d e l e t e ,s a v e u p d a t e ,e v i c t ,r e p l i c a t e ,l o c ka n dr e f r e s h ;
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
70/215
12/30/13
3. comma-separated
c a s c a d e = " a l l , d e l e t e o r p h a n " . See Section 11.11, Transitive persistence for a full explanation.
Note that single valued many-to-one associations do not support orphan delete.
By default, single point associations are eagerly fetched in JPA 2. You can mark it as lazily fetched by using @ M a n y T o O n e ( f e t c h = F e t c h T y p e . L A Z Y ) in which case Hibernate will proxy the association and load it when the state of the associated entity is reached. You can force Hibernate not to use a proxy by using
@ L a z y T o O n e ( N O _ P R O X Y ) . In this case, the property is fetched lazily when the instance variable is first
accessed. This requires build-time bytecode instrumentation. lazy="false" specifies that the association will always be eagerly fetched. With the default JPA options, single-ended associations are loaded with a subsequent select if set to
L A Z Y , or a SQL JOIN is used for E A G E Rassociations. You can however adjust the fetching strategy, ie how
data is fetched by using @ F e t c h .F e t c h M o d e can be S E L E C T (a select is triggered when the association needs to be loaded) or J O I N (use a SQL JOIN to load the association while loading the owner entity).
J O I Noverrides any lazy attribute (an association loaded through a J O I Nstrategy cannot be lazy).
and a foreign key in one table is referencing the primary key column(s) of the target table.
@ E n t i t y p u b l i cc l a s sF l i g h ti m p l e m e n t sS e r i a l i z a b l e{ @ M a n y T o O n e (c a s c a d e={ C a s c a d e T y p e . P E R S I S T ,C a s c a d e T y p e . M E R G E }) @ J o i n C o l u m n ( n a m e = " C O M P _ I D " ) p u b l i cC o m p a n yg e t C o m p a n y ( ){ r e t u r nc o m p a n y ; } . . . }
The @ J o i n C o l u m n attribute is optional, the default value(s) is the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column in the owned side. In this example c o m p a n y _ i dbecause the property name is c o m p a n yand the column id of Company is
i d . @ E n t i t y p u b l i cc l a s sF l i g h ti m p l e m e n t sS e r i a l i z a b l e{ @ M a n y T o O n e (c a s c a d e={ C a s c a d e T y p e . P E R S I S T ,C a s c a d e T y p e . M E R G E } ,t a r g e t E n t i t y = C o m p a n y I m p l . c l a s s) @ J o i n C o l u m n ( n a m e = " C O M P _ I D " ) p u b l i cC o m p a n yg e t C o m p a n y ( ){ r e t u r nc o m p a n y ; } . . . } p u b l i ci n t e r f a c eC o m p a n y{ . . . }
You can also map a to one association through an association table. This association table described by the @ J o i n T a b l e annotation will contains a foreign key referencing back the entity table (through
@ J o i n T a b l e . j o i n C o l u m n s )
and
foreign
key
referencing
the
target
entity
table
(through
Note
You can use a SQL fragment to simulate a physical join column using the @ J o i n C o l u m n O r F o r m u l a/ @ J o i n C o l u m n O r f o r m u l a s annotations (just like you can use a SQL fragment to simulate a property column via the @ F o r m u l a annotation).
@ E n t i t y p u b l i cc l a s sT i c k e ti m p l e m e n t sS e r i a l i z a b l e{ @ M a n y T o O n e @ J o i n C o l u m n O r F o r m u l a ( f o r m u l a = " ( f i r s t n a m e+''+l a s t n a m e ) " ) p u b l i cP e r s o ng e t O w n e r ( ){ r e t u r np e r s o n ;
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
71/215
12/30/13
} . . . }
You can mark an association as mandatory by using the o p t i o n a l = f a l s e attribute. We recommend to use Bean Validation's @ N o t N u l l annotation as a better alternative however. As a consequence, the foreign key column(s) will be marked as not nullable (if possible). When Hibernate cannot resolve the association because the expected associated element is not in database (wrong id on the association column), an exception is raised. This might be inconvenient for legacy and badly maintained schemas. You can ask Hibernate to ignore such elements instead of raising an exception using the @ N o t F o u n dannotation.
Sometimes you want to delegate to your database the deletion of cascade when a given entity is deleted. In this case Hibernate generates a cascade delete constraint at the database level.
Foreign key constraints, while generated by Hibernate, have a fairly unreadable name. You can override the constraint name using @ F o r e i g n K e y .
Sometimes, you want to link one entity to an other not by the target entity primary key but by a different unique key. You can achieve that by referencing the unique key column(s) in @ J o i n C o l u m n . r e f e r e n c e C o l u m n N a m e .
@ E n t i t y c l a s sP e r s o n{ @ I dI n t e g e rp e r s o n N u m b e r ; S t r i n gf i r s t N a m e ; @ C o l u m n ( n a m e = " I " ) S t r i n gi n i t i a l ; S t r i n gl a s t N a m e ; } @ E n t i t y c l a s sH o m e{ @ M a n y T o O n e @ J o i n C o l u m n s ( { @ J o i n C o l u m n ( n a m e = " f i r s t _ n a m e " ,r e f e r e n c e d C o l u m n N a m e = " f i r s t N a m e " ) , @ J o i n C o l u m n ( n a m e = " i n i t " ,r e f e r e n c e d C o l u m n N a m e = " I " ) , @ J o i n C o l u m n ( n a m e = " l a s t _ n a m e " ,r e f e r e n c e d C o l u m n N a m e = " l a s t N a m e " ) , } ) P e r s o no w n e r }
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
72/215
12/30/13
associated class.
c a s c a d e(optional): specifies which operations should be cascaded from the parent object to the
associated object.
f e t c h(optional - defaults to s e l e c t ): chooses between outer-join fetching or sequential select
fetching.
u p d a t e ,i n s e r t(optional - defaults to t r u e ): specifies that the mapped columns should be
included in SQL U P D A T Eand/or I N S E R Tstatements. Setting both to f a l s eallows a pure "derived" association whose value is initialized from another property that maps to the same column(s), or by a trigger or other application.
p r o p e r t y r e f(optional): the name of a property of the associated class that is joined to this
foreign key. If not specified, the primary key of the associated class is used.
a c c e s s(optional - defaults to p r o p e r t y ): the strategy Hibernate uses for accessing the property
value.
u n i q u e(optional): enables the DDL generation of a unique constraint for the foreign-key column.
By allowing this to be the target of a p r o p e r t y r e f , you can make the association multiplicity one-to-one.
n o t n u l l(optional): enables the DDL generation of a nullability constraint for the foreign key
columns.
o p t i m i s t i c l o c k(optional - defaults to t r u e ): specifies that updates to this property do or do
not require acquisition of the optimistic lock. In other words, it determines if a version increment should occur when this property is dirty.
l a z y(optional - defaults to p r o x y ): by default, single point associations are proxied. l a z y = " n o p r o x y "specifies that the property should be fetched lazily when the instance variable
is first accessed. This requires build-time bytecode instrumentation. l a z y = " f a l s e "specifies that the association will always be eagerly fetched.
n o t f o u n d(optional - defaults to e x c e p t i o n ): specifies how foreign keys that reference missing
Setting a value of the c a s c a d e attribute to any meaningful value other than n o n e will propagate certain operations to the associated object. The meaningful values are divided into three categories. First, basic operations, which include: p e r s i s t ,m e r g e ,d e l e t e ,s a v e u p d a t e ,e v i c t ,r e p l i c a t e ,l o c ka n dr e f r e s h ; second, special values:
d e l e t e o r p h a n ;
and
third,a l l
comma-separated
combinations See
of Section
operation
names:
c a s c a d e = " p e r s i s t , m e r g e , e v i c t " or
c a s c a d e = " a l l , d e l e t e o r p h a n " .
11.11, Transitive
persistence for a full explanation. Note that single valued, many-to-one and one-to-one, associations do not support orphan delete. Here is an example of a typical m a n y t o o n edeclaration:
< m a n y t o o n en a m e = " p r o d u c t "c l a s s = " P r o d u c t "c o l u m n = " P R O D U C T _ I D " / >
The p r o p e r t y r e fattribute 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. This is a complicated and confusing relational model. For example, if the P r o d u c t class had a unique serial number that is not the primary key. The u n i q u eattribute controls Hibernate's DDL generation with the SchemaExport tool.
< p r o p e r t yn a m e = " s e r i a l N u m b e r "u n i q u e = " t r u e "t y p e = " s t r i n g "c o l u m n = " S E R I A L _ N U M B E R " / >
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
73/215
12/30/13
Note
Many people got confused by these primary key based one to one associations. They can only be lazily loaded if Hibernate knows that the other side of the association is always present. To indicate to Hibernate that it is the case, use @ O n e T o O n e ( o p t i o n a l = f a l s e ) .
associated class.
c a s c a d e(optional): specifies which operations should be cascaded from the parent object to the
associated object.
c o n s t r a i n e d(optional): specifies that a foreign key constraint on the primary key of the mapped
table and references the table of the associated class. This option affects the order in which
s a v e ( )and d e l e t e ( )are cascaded, and determines whether the association can be proxied. It is
fetching.
p r o p e r t y r e f(optional): the name of a property of the associated class that is joined to the
primary key of this class. If not specified, the primary key of the associated class is used.
a c c e s s(optional - defaults to p r o p e r t y ): the strategy Hibernate uses for accessing the property
value.
f o r m u l a(optional): almost all one-to-one associations map to the primary key of the owning
entity. If this is not the case, you can specify another column, columns or expression to join on using an SQL formula. See o r g . h i b e r n a t e . t e s t . o n e t o o n e f o r m u l afor an example.
l a z y(optional - defaults to p r o x y ): by default, single point associations are proxied. l a z y = " n o p r o x y "specifies that the property should be fetched lazily when the instance variable
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
74/215
12/30/13
Primary key associations do not need an extra table column. If two rows are related by the association, then the two table rows share the same primary key value. To relate two objects by a primary key association, ensure that they are assigned the same identifier value. For a primary key association, add the following mappings to E m p l o y e eand P e r s o nrespectively:
< o n e t o o n en a m e = " p e r s o n "c l a s s = " P e r s o n " / > < o n e t o o n en a m e = " e m p l o y e e "c l a s s = " E m p l o y e e "c o n s t r a i n e d = " t r u e " / >
Ensure that the primary keys of the related rows in the PERSON and EMPLOYEE tables are equal. You use a special Hibernate identifier generation strategy called f o r e i g n :
< c l a s sn a m e = " p e r s o n "t a b l e = " P E R S O N " > < i dn a m e = " i d "c o l u m n = " P E R S O N _ I D " > < g e n e r a t o rc l a s s = " f o r e i g n " > < p a r a mn a m e = " p r o p e r t y " > e m p l o y e e < / p a r a m > < / g e n e r a t o r > < / i d > . . . < o n e t o o n en a m e = " e m p l o y e e " c l a s s = " E m p l o y e e " c o n s t r a i n e d = " t r u e " / > < / c l a s s >
A newly saved instance of P e r s o n is assigned the same primary key value as the E m p l o y e e instance referred with the e m p l o y e eproperty of that P e r s o n .
5.1.8. Natural-id
Although we recommend the use of surrogate keys as primary keys, you should try to identify natural keys for all entities. A natural key is a property or combination of properties that is unique and non-null. It is also immutable. Map the properties of the natural key as @ N a t u r a l I d or map them inside the
< n a t u r a l i d >element. Hibernate will generate the necessary unique key and nullability constraints and,
Or in XML,
< n a t u r a l i dm u t a b l e = " t r u e | f a l s e " / > < p r o p e r t y. . ./ > < m a n y t o o n e. . ./ > . . . . . . < / n a t u r a l i d >
It is recommended that you implement e q u a l s ( )and h a s h C o d e ( ) to compare the natural key properties of the entity. This mapping is not intended for use with entities that have natural primary keys.
m u t a b l e (optional - defaults to f a l s e ): by default, natural identifier properties are assumed to be
immutable (constant).
5.1.9. Any
There is one more type of property mapping. The @ A n y mapping defines a polymorphic association to classes from multiple tables. This type of mapping requires more than one column. The first column contains the type of the associated entity. The remaining columns contain the identifier. It is impossible
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
75/215
12/30/13
persistent classes that have identifier properties of the type specified by i d T y p e . You must specify the mapping from values of the m e t a T y p eto class names.
@ A n y (m e t a C o l u m n=@ C o l u m n (n a m e=" p r o p e r t y _ t y p e ") ,f e t c h = F e t c h T y p e . E A G E R) @ A n y M e t a D e f ( i d T y p e=" i n t e g e r " , m e t a T y p e=" s t r i n g " , m e t a V a l u e s={ @ M e t a V a l u e (v a l u e=" S " ,t a r g e t E n t i t y=S t r i n g P r o p e r t y . c l a s s) , @ M e t a V a l u e (v a l u e=" I " ,t a r g e t E n t i t y=I n t e g e r P r o p e r t y . c l a s s) }) @ J o i n C o l u m n (n a m e=" p r o p e r t y _ i d ") p u b l i cP r o p e r t yg e t M a i n P r o p e r t y ( ){ r e t u r nm a i n P r o p e r t y ; }
Note that @ A n y D e fcan be mutualized and reused. It is recommended to place it as a package metadata in this case.
/ / o nap a c k a g e @ A n y M e t a D e f (n a m e = " p r o p e r t y " i d T y p e=" i n t e g e r " , m e t a T y p e=" s t r i n g " , m e t a V a l u e s={ @ M e t a V a l u e (v a l u e=" S " ,t a r g e t E n t i t y=S t r i n g P r o p e r t y . c l a s s) , @ M e t a V a l u e (v a l u e=" I " ,t a r g e t E n t i t y=I n t e g e r P r o p e r t y . c l a s s) }) p a c k a g eo r g . h i b e r n a t e . t e s t . a n n o t a t i o n s . a n y ; / / i nac l a s s @ A n y (m e t a D e f = " p r o p e r t y " ,m e t a C o l u m n=@ C o l u m n (n a m e=" p r o p e r t y _ t y p e ") ,f e t c h = F e t c h T y p e . E A G E R) @ J o i n C o l u m n (n a m e=" p r o p e r t y _ i d ") p u b l i cP r o p e r t yg e t M a i n P r o p e r t y ( ){ r e t u r nm a i n P r o p e r t y ; }
Note
You cannot mutualize the metadata in hbm.xml as you can in annotations.
< a n y n a m e = " p r o p e r t y N a m e " i d t y p e = " i d t y p e n a m e " m e t a t y p e = " m e t a t y p e n a m e " c a s c a d e = " c a s c a d e _ s t y l e " a c c e s s = " f i e l d | p r o p e r t y | C l a s s N a m e " o p t i m i s t i c l o c k = " t r u e | f a l s e " > < m e t a v a l u e. . ./ > < m e t a v a l u e. . ./ > . . . . . < c o l u m n. . . ./ > < c o l u m n. . . ./ > . . . . . < / a n y > n a m e : the property name. i d t y p e : the identifier type. m e t a t y p e(optional - defaults to s t r i n g ): any type that is allowed for a discriminator mapping. c a s c a d e(optional- defaults to n o n e ): the cascade style. a c c e s s(optional - defaults to p r o p e r t y ): the strategy Hibernate uses for accessing the property
value.
o p t i m i s t i c l o c k(optional - defaults to t r u e ): specifies that updates to this property either do or
do not require acquisition of the optimistic lock. It defines whether a version increment should occur if this property is dirty.
5.1.10. Properties
The < p r o p e r t i e s >element allows the definition of a named, logical grouping of the properties of a class. The most important use of the construct is that it allows a combination of properties to be the target of
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
76/215
12/30/13
do or do not require acquisition of the optimistic lock. It determines if a version increment should occur when these properties are dirty.
u n i q u e(optional - defaults to f a l s e ): specifies that a unique constraint exists upon all mapped
columns of the component. For example, if we have the following < p r o p e r t i e s >mapping:
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " p e r s o n N u m b e r " / > . . . < p r o p e r t i e sn a m e = " n a m e " u n i q u e = " t r u e "u p d a t e = " f a l s e " > < p r o p e r t yn a m e = " f i r s t N a m e " / > < p r o p e r t yn a m e = " i n i t i a l " / > < p r o p e r t yn a m e = " l a s t N a m e " / > < / p r o p e r t i e s > < / c l a s s >
You might have some legacy data association that refers to this unique key of the P e r s o n table, instead of to the primary key:
< m a n y t o o n en a m e = " o w n e r " c l a s s = " P e r s o n "p r o p e r t y r e f = " n a m e " > < c o l u m nn a m e = " f i r s t N a m e " / > < c o l u m nn a m e = " i n i t i a l " / > < c o l u m nn a m e = " l a s t N a m e " / > < / m a n y t o o n e >
Note
When using annotations as a mapping strategy, such construct is not necessary as the binding between a column and its related column on the associated table is done directly
@ E n t i t y c l a s sP e r s o n{ @ I dI n t e g e rp e r s o n N u m b e r ; S t r i n gf i r s t N a m e ; @ C o l u m n ( n a m e = " I " ) S t r i n gi n i t i a l ; S t r i n gl a s t N a m e ; } @ E n t i t y c l a s sH o m e{ @ M a n y T o O n e @ J o i n C o l u m n s ( { @ J o i n C o l u m n ( n a m e = " f i r s t _ n a m e " ,r e f e r e n c e d C o l u m n N a m e = " f i r s t N a m e " ) , @ J o i n C o l u m n ( n a m e = " i n i t " ,r e f e r e n c e d C o l u m n N a m e = " I " ) , @ J o i n C o l u m n ( n a m e = " l a s t _ n a m e " ,r e f e r e n c e d C o l u m n N a m e = " l a s t N a m e " ) , } ) P e r s o no w n e r }
The use of this outside the context of mapping legacy data is not recommended.
5.1.11.1. Doctype
All XML mappings should declare the doctype shown. The actual DTD can be found at the URL above, in
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
77/215
12/30/13
5.1.11.1.1. EntityResolver Hibernate will first attempt to resolve DTDs in its classpath. It does this is by registering a custom o r g . x m l . s a x . E n t i t y R e s o l v e r implementation with the SAXReader it uses to read in the xml files. This custom E n t i t y R e s o l v e rrecognizes two different systemId namespaces: a h i b e r n a t e n a m e s p a c e is recognized whenever the resolver encounters a systemId starting with
h t t p : / / w w w . h i b e r n a t e . o r g / d t d / . The resolver attempts to resolve these entities via the classloader
which loaded the Hibernate classes. au s e rn a m e s p a c e is recognized whenever the resolver encounters a systemId using a c l a s s p a t h : / / URL protocol. 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 following is an example of utilizing user namespacing:
< ? x m lv e r s i o n = " 1 . 0 " ? > < ! D O C T Y P Eh i b e r n a t e m a p p i n gP U B L I C " / / H i b e r n a t e / H i b e r n a t eM a p p i n gD T D3 . 0 / / E N " " h t t p : / / h i b e r n a t e . s o u r c e f o r g e . n e t / h i b e r n a t e m a p p i n g 3 . 0 . d t d "[ < ! E N T I T Yt y p e sS Y S T E M" c l a s s p a t h : / / y o u r / d o m a i n / t y p e s . x m l " > ] > < h i b e r n a t e m a p p i n gp a c k a g e = " y o u r . d o m a i n " > < c l a s sn a m e = " M y E n t i t y " > < i dn a m e = " i d "t y p e = " m y c u s t o m i d t y p e " > . . . < / i d > < c l a s s > & t y p e s ; < / h i b e r n a t e m a p p i n g >
5.1.11.2. Hibernate-mapping
This element has several optional attributes. The s c h e m a and c a t a l o g attributes specify that tables referred to in this mapping belong to the named schema and/or catalog. If they are specified, tablenames will be qualified by the given schema and catalog names. If they are missing, tablenames will be unqualified. The d e f a u l t c a s c a d e attribute specifies what cascade style should be assumed for properties and collections that do not specify a c a s c a d e attribute. By default, the a u t o i m p o r t attribute allows you to use unqualified class names in the query language.
< h i b e r n a t e m a p p i n g s c h e m a = " s c h e m a N a m e " c a t a l o g = " c a t a l o g N a m e " d e f a u l t c a s c a d e = " c a s c a d e _ s t y l e " d e f a u l t a c c e s s = " f i e l d | p r o p e r t y | C l a s s N a m e " d e f a u l t l a z y = " t r u e | f a l s e " a u t o i m p o r t = " t r u e | f a l s e " p a c k a g e = " p a c k a g e . n a m e " / > s c h e m a(optional): the name of a database schema. c a t a l o g(optional): the name of a database catalog. d e f a u l t c a s c a d e(optional - defaults to n o n e ): a default cascade style. d e f a u l t a c c e s s(optional - defaults to p r o p e r t y ): the strategy Hibernate should use for
document. If you have two persistent classes with the same unqualified name, you should set
a u t o i m p o r t = " f a l s e " . An exception will result if you attempt to assign two classes to the same
"imported" name. The h i b e r n a t e m a p p i n g element allows you to nest several persistent < c l a s s > mappings, as shown above. 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. For example, C a t . h b m . x m l ,D o g . h b m . x m l , or if using inheritance, A n i m a l . h b m . x m l .
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
78/215
12/30/13
5.1.11.3. Key
The < k e y > element is featured a few times within this guide. It appears anywhere the parent mapping element defines a join to a new table that references the primary key of the original table. It also defines the foreign key in the joined table:
< k e y c o l u m n = " c o l u m n n a m e " o n d e l e t e = " n o a c t i o n | c a s c a d e " p r o p e r t y r e f = " p r o p e r t y N a m e " n o t n u l l = " t r u e | f a l s e " u p d a t e = " t r u e | f a l s e " u n i q u e = " t r u e | f a l s e " / > c o l u m n(optional): the name of the foreign key column. This can also be specified by nested < c o l u m n >element(s). o n d e l e t e(optional - defaults to n o a c t i o n ): specifies whether the foreign key constraint has
whenever the foreign key is also the primary key. For systems where delete performance is important, we recommend that all keys should be defined o n d e l e t e = " c a s c a d e " . Hibernate uses a database-level O NC A S C A D ED E L E T E constraint, instead of many individual D E L E T E statements. Be aware that this feature bypasses Hibernate's usual optimistic locking strategy for versioned data. The n o t n u l l and u p d a t eattributes are useful when mapping a unidirectional one-to-many association. If you map a unidirectional one-to-many association to a non-nullable foreign key, you must declare the key column using < k e yn o t n u l l = " t r u e " > .
5.1.11.4. Import
If your application has two persistent classes with the same name, and you do not want to specify the fully qualified package name in Hibernate queries, classes can be "imported" explicitly, rather than relying upon a u t o i m p o r t = " t r u e " . You can also import classes and interfaces that are not explicitly mapped:
< i m p o r tc l a s s = " j a v a . l a n g . O b j e c t "r e n a m e = " U n i v e r s e " / > < i m p o r t c l a s s = " C l a s s N a m e " r e n a m e = " S h o r t N a m e " / > c l a s s : the fully qualified class name of any Java class. r e n a m e(optional - defaults to the unqualified class name): a name that can be used in the query
language.
Note
This feature is unique to hbm.xml and is not supported in annotations.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
79/215
12/30/13
Type mappings from Java primitives or wrapper classes to appropriate (vendor-specific) SQL column types. b o o l e a n , y e s _ n o and t r u e _ f a l s e are all alternative encodings for a Java b o o l e a n or
j a v a . l a n g . B o o l e a n . s t r i n g
Type mappings from j a v a . u t i l . D a t e and its subclasses to SQL types D A T E ,T I M E and T I M E S T A M P (or equivalent).
c a l e n d a r ,c a l e n d a r _ d a t e
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
80/215
12/30/13
A type mapping from j a v a . l a n g . C l a s s to V A R C H A R(or Oracle V A R C H A R 2 ). A C l a s s is mapped to its fully qualified name.
b i n a r y
Maps serializable Java types to an appropriate SQL binary type. You can also indicate the Hibernate type s e r i a l i z a b l e with the name of a serializable Java class or interface that does not default to a basic type.
c l o b ,b l o b
Type mappings for the JDBC classes j a v a . s q l . C l o b and j a v a . s q l . B l o b . These types can be inconvenient for some applications, since the blob or clob object cannot be reused outside of a transaction. Driver support is patchy and inconsistent.
m a t e r i a l i z e d _ c l o b
Maps long Java strings to a SQL C L O B type. When read, the C L O B value is immediately materialized into a Java string. Some drivers require the C L O B value to be read within a transaction. Once materialized, the Java string is available outside of the transaction.
m a t e r i a l i z e d _ b l o b
Maps long Java byte arrays to a SQL B L O B type. When read, the B L O B value is immediately materialized into a byte array. Some drivers require the B L O B value to be read within a transaction. Once materialized, the byte array is available outside of the transaction.
i m m _ d a t e ,i m m _ t i m e ,i m m _ t i m e s t a m p ,i m m _ c a l e n d a r ,i m m _ c a l e n d a r _ d a t e ,i m m _ s e r i a l i z a b l e ,i m m _ b i n a r y
Type mappings for what are considered mutable Java types. This is where Hibernate makes certain optimizations appropriate only for immutable Java types, and the application treats the object as immutable. For example, you should not call D a t e . s e t T i m e ( ) for an instance mapped as
i m m _ t i m e s t a m p . To change the value of the property, and have that change made persistent, the
application must assign a new, nonidentical, object to the property. Unique identifiers of entities and collections can be of any basic type except b i n a r y , b l o b and c l o b . Composite identifiers are also allowed. See below for more information. The basic value types have corresponding T y p e constants defined on o r g . h i b e r n a t e . H i b e r n a t e . For example, H i b e r n a t e . S T R I N Grepresents the s t r i n gtype.
To
implement
custom
type,
implement
either
o r g . h i b e r n a t e . U s e r T y p e
or
o r g . h i b e r n a t e . C o m p o s i t e U s e r T y p eand declare properties using the fully qualified classname of the type.
Notice the use of < c o l u m n >tags to map a property to multiple columns. The C o m p o s i t e U s e r T y p e ,E n h a n c e d U s e r T y p e ,U s e r C o l l e c t i o n T y p e , and U s e r V e r s i o n T y p e interfaces provide support for more specialized uses. You can even supply parameters to a U s e r T y p e in the mapping file. To do this, your U s e r T y p e must implement the o r g . h i b e r n a t e . u s e r t y p e . P a r a m e t e r i z e d T y p e interface. To supply parameters to your custom type, you can use the < t y p e >element in your mapping files.
< p r o p e r t yn a m e = " p r i o r i t y " > < t y p en a m e = " c o m . m y c o m p a n y . u s e r t y p e s . D e f a u l t V a l u e I n t e g e r T y p e " > < p a r a mn a m e = " d e f a u l t " > 0 < / p a r a m > < / t y p e > < / p r o p e r t y >
The U s e r T y p e can now retrieve the value for the parameter named d e f a u l t from the P r o p e r t i e s object
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
81/215
12/30/13
passed to it.
If you regularly use a certain U s e r T y p e , it is useful to define a shorter name for it. You can do this using the < t y p e d e f > element. Typedefs assign a name to a custom type, and can also contain a list of default parameter values if the type is parameterized.
< t y p e d e fc l a s s = " c o m . m y c o m p a n y . u s e r t y p e s . D e f a u l t V a l u e I n t e g e r T y p e "n a m e = " d e f a u l t _ z e r o " > < p a r a mn a m e = " d e f a u l t " > 0 < / p a r a m > < / t y p e d e f > < p r o p e r t yn a m e = " p r i o r i t y "t y p e = " d e f a u l t _ z e r o " / >
It is also possible to override the parameters supplied in a typedef on a case-by-case basis by using type parameters on the property mapping. Even though Hibernate's rich range of built-in types and support for components means you will rarely need to use a custom type, it is considered good practice to use custom types for non-entity classes that occur frequently in your application. For example, a M o n e t a r y A m o u n t class is a good candidate for a
C o m p o s i t e U s e r T y p e , even though it could be mapped as a component. One reason for this is abstraction.
With a custom type, your mapping documents would be protected against changes to the way monetary values are represented.
Note
This feature is not supported in Annotations
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
82/215
12/30/13
Properties like created-date fall into this category. Even though version and timestamp properties can be marked as generated, this option is not available.
a l w a y s : the property value is generated both on insert and on update.
or in XML
< p r o p e r t yn a m e = " c r e d i t C a r d N u m b e r " > < c o l u m n n a m e = " c r e d i t _ c a r d _ n u m " r e a d = " d e c r y p t ( c r e d i t _ c a r d _ n u m ) " w r i t e = " e n c r y p t ( ? ) " / > < / p r o p e r t y >
Note
You can use the plural form @ C o l u m n T r a n s f o r m e r s if more than one columns need to define either of these rules.
If a property uses more that one column, you must use the f o r C o l u m nattribute to specify which column, the expressions are targeting.
@ E n t i t y c l a s sU s e r{ @ T y p e ( t y p e = " c o m . a c m e . t y p e . C r e d i t C a r d T y p e " ) @ C o l u m n s ({ @ C o l u m n ( n a m e = " c r e d i t _ c a r d _ n u m " ) , @ C o l u m n ( n a m e = " e x p _ d a t e " )}) @ C o l u m n T r a n s f o r m e r ( f o r C o l u m n = " c r e d i t _ c a r d _ n u m " , r e a d = " d e c r y p t ( c r e d i t _ c a r d _ n u m ) " , w r i t e = " e n c r y p t ( ? ) " ) p u b l i cC r e d i t C a r dg e t C r e d i t C a r d ( ){r e t u r nc r e d i t C a r d ;} p u b l i cv o i ds e t C r e d i t C a r d ( C r e d i t C a r dc a r d ){t h i s . c r e d i t C a r d=c a r d ;} p r i v a t eC r e d i t C a r dc r e d i t C a r d ; }
Hibernate applies the custom expressions automatically whenever the property is referenced in a query. This functionality is similar to a derived-property f o r m u l awith two differences: The property is backed by one or more columns that are exported as part of automatic schema generation. The property is read-write, not read-only. The w r i t eexpression, if specified, must contain exactly one '?' placeholder for the value.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
83/215
12/30/13
The second mode is to supply a custom class that constructs the CREATE and DROP commands. This custom class must implement the o r g . h i b e r n a t e . m a p p i n g . A u x i l i a r y D a t a b a s e O b j e c tinterface.
< h i b e r n a t e m a p p i n g > . . . < d a t a b a s e o b j e c t > < d e f i n i t i o nc l a s s = " M y T r i g g e r D e f i n i t i o n " / > < / d a t a b a s e o b j e c t > < / h i b e r n a t e m a p p i n g >
Additionally, these database objects can be optionally scoped so that they only apply when certain dialects are used.
< h i b e r n a t e m a p p i n g > . . . < d a t a b a s e o b j e c t > < d e f i n i t i o nc l a s s = " M y T r i g g e r D e f i n i t i o n " / > < d i a l e c t s c o p en a m e = " o r g . h i b e r n a t e . d i a l e c t . O r a c l e 9 i D i a l e c t " / > < d i a l e c t s c o p en a m e = " o r g . h i b e r n a t e . d i a l e c t . O r a c l e 1 0 g D i a l e c t " / > < / d a t a b a s e o b j e c t > < / h i b e r n a t e m a p p i n g >
Note
This feature is not supported in Annotations
Chapter 6. Types
Table of Contents 6.1. Value types 6.1.1. Basic value types 6.1.2. Composite types 6.1.3. Collection types 6.2. Entity types 6.3. Significance of type categories 6.4. Custom types 6.4.1. Custom types using o r g . h i b e r n a t e . t y p e . T y p e 6.4.2. Custom types using o r g . h i b e r n a t e . u s e r t y p e . U s e r T y p e 6.4.3. Custom types using o r g . h i b e r n a t e . u s e r t y p e . C o m p o s i t e U s e r T y p e 6.5. Type registry As an Object/Relational Mapping solution, Hibernate deals with both the Java and JDBC representations of application data. An online catalog application, for example, most likely has P r o d u c t object with a number of attributes such as a s k u ,n a m e , etc. For these individual attributes, Hibernate must be able to read the values out of the database and write them back. This 'marshalling' is the function of a Hibernate type, which is an implementation of the o r g . h i b e r n a t e . t y p e . T y p e interface. In addition, a Hibernate type describes various aspects of behavior of the Java type such as "how is equality checked?" or "how are values cloned?".
Important
A Hibernate type is neither a Java type nor a SQL datatype; it provides a information about both. When you encounter the term type in regards to Hibernate be aware that usage might refer to the Java type, the SQL/JDBC type or the Hibernate type.
Hibernate categorizes types into two high-level groups: value types (see Section 6.1, Value types) and entity types (see Section 6.2, Entity types).
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
84/215
12/30/13
6.1.1.1. java.lang.String
o r g . h i b e r n a t e . t y p e . S t r i n g T y p e
Maps a string to the JDBC VARCHAR type. This is the standard mapping for a string if no Hibernate type is specified. Registered under s t r i n g and j a v a . l a n g . S t r i n g in the type registry (see Section 6.5, Type registry).
o r g . h i b e r n a t e . t y p e . M a t e r i a l i z e d C l o b
Maps a string to a JDBC CLOB type Registered under m a t e r i a l i z e d _ c l o bin the type registry (see Section 6.5, Type registry).
o r g . h i b e r n a t e . t y p e . T e x t T y p e
Maps a string to a JDBC LONGVARCHAR type Registered under t e x tin the type registry (see Section 6.5, Type registry).
Maps a char or j a v a . l a n g . C h a r a c t e rto a JDBC CHAR Registered under c h a r and j a v a . l a n g . C h a r a c t e r in the type registry (see Section 6.5, Type registry).
Maps a boolean to a JDBC BIT type Registered under b o o l e a n and j a v a . l a n g . B o o l e a n in the type registry (see Section 6.5, Type registry).
o r g . h i b e r n a t e . t y p e . N u m e r i c B o o l e a n T y p e
Maps a boolean to a JDBC INTEGER type as 0 = false, 1 = true Registered under n u m e r i c _ b o o l e a nin the type registry (see Section 6.5, Type registry).
o r g . h i b e r n a t e . t y p e . Y e s N o T y p e
Maps a boolean to a JDBC CHAR type as ('N' | 'n') = false, ( 'Y' | 'y' ) = true Registered under y e s _ n oin the type registry (see Section 6.5, Type registry).
o r g . h i b e r n a t e . t y p e . T r u e F a l s e T y p e
Maps a boolean to a JDBC CHAR type as ('F' | 'f') = false, ( 'T' | 't' ) = true Registered under t r u e _ f a l s ein the type registry (see Section 6.5, Type registry).
Maps a byte or j a v a . l a n g . B y t eto a JDBC TINYINT Registered under b y t eand j a v a . l a n g . B y t ein the type registry (see Section 6.5, Type registry).
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
85/215
12/30/13
Maps a short or j a v a . l a n g . S h o r tto a JDBC SMALLINT Registered under s h o r tand j a v a . l a n g . S h o r tin the type registry (see Section 6.5, Type registry).
Maps an int or j a v a . l a n g . I n t e g e rto a JDBC INTEGER Registered under i n tand j a v a . l a n g . I n t e g e r in the type registry (see Section 6.5, Type registry).
Maps a long or j a v a . l a n g . L o n gto a JDBC BIGINT Registered under l o n gand j a v a . l a n g . L o n gin the type registry (see Section 6.5, Type registry).
Maps a float or j a v a . l a n g . F l o a tto a JDBC FLOAT Registered under f l o a tand j a v a . l a n g . F l o a tin the type registry (see Section 6.5, Type registry).
Maps a double or j a v a . l a n g . D o u b l eto a JDBC DOUBLE Registered under d o u b l e and j a v a . l a n g . D o u b l e in the type registry (see Section 6.5, Type registry).
6.1.1.10. j a v a . m a t h . B i g I n t e g e r
o r g . h i b e r n a t e . t y p e . B i g I n t e g e r T y p e
Maps a j a v a . m a t h . B i g I n t e g e rto a JDBC NUMERIC Registered under b i g _ i n t e g e rand j a v a . m a t h . B i g I n t e g e rin the type registry (see Section 6.5, Type registry).
6.1.1.11. j a v a . m a t h . B i g D e c i m a l
o r g . h i b e r n a t e . t y p e . B i g D e c i m a l T y p e
Maps a j a v a . m a t h . B i g D e c i m a lto a JDBC NUMERIC Registered under b i g _ d e c i m a land j a v a . m a t h . B i g D e c i m a lin the type registry (see Section 6.5, Type registry).
6.1.1.12. j a v a . u t i l . D a t eor j a v a . s q l . T i m e s t a m p
o r g . h i b e r n a t e . t y p e . T i m e s t a m p T y p e
Maps a j a v a . s q l . T i m e s t a m pto a JDBC TIMESTAMP Registered under t i m e s t a m p , j a v a . s q l . T i m e s t a m p and j a v a . u t i l . D a t e in the type registry (see Section 6.5, Type registry).
6.1.1.13. j a v a . s q l . T i m e
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
86/215
12/30/13
Maps a j a v a . s q l . T i m eto a JDBC TIME Registered under t i m eand j a v a . s q l . T i m ein the type registry (see Section 6.5, Type registry).
6.1.1.14. j a v a . s q l . D a t e
o r g . h i b e r n a t e . t y p e . D a t e T y p e
Maps a j a v a . s q l . D a t eto a JDBC DATE Registered under d a t eand j a v a . s q l . D a t ein the type registry (see Section 6.5, Type registry).
6.1.1.15. j a v a . u t i l . C a l e n d a r
o r g . h i b e r n a t e . t y p e . C a l e n d a r T y p e
Maps a j a v a . u t i l . C a l e n d a rto a JDBC TIMESTAMP Registered under c a l e n d a r , j a v a . u t i l . C a l e n d a r and j a v a . u t i l . G r e g o r i a n C a l e n d a r in the type registry (see Section 6.5, Type registry).
o r g . h i b e r n a t e . t y p e . C a l e n d a r D a t e T y p e
Maps a j a v a . u t i l . C a l e n d a rto a JDBC DATE Registered under c a l e n d a r _ d a t ein the type registry (see Section 6.5, Type registry).
6.1.1.16. j a v a . u t i l . C u r r e n c y
o r g . h i b e r n a t e . t y p e . C u r r e n c y T y p e
Maps a j a v a . u t i l . C u r r e n c yto a JDBC VARCHAR (using the Currency code) Registered under c u r r e n c y and j a v a . u t i l . C u r r e n c y in the type registry (see Section 6.5, Type registry).
6.1.1.17. j a v a . u t i l . L o c a l e
o r g . h i b e r n a t e . t y p e . L o c a l e T y p e
Maps a j a v a . u t i l . L o c a l eto a JDBC VARCHAR (using the Locale code) Registered under l o c a l e and j a v a . u t i l . L o c a l e in the type registry (see Section 6.5, Type registry).
6.1.1.18. j a v a . u t i l . T i m e Z o n e
o r g . h i b e r n a t e . t y p e . T i m e Z o n e T y p e
Maps a j a v a . u t i l . T i m e Z o n eto a JDBC VARCHAR (using the TimeZone ID) Registered under t i m e z o n e and j a v a . u t i l . T i m e Z o n e in the type registry (see Section 6.5, Type registry).
6.1.1.19. j a v a . n e t . U R L
o r g . h i b e r n a t e . t y p e . U r l T y p e
Maps a j a v a . n e t . U R Lto a JDBC VARCHAR (using the external form) Registered under u r land j a v a . n e t . U R Lin the type registry (see Section 6.5, Type registry).
6.1.1.20. j a v a . l a n g . C l a s s
o r g . h i b e r n a t e . t y p e . C l a s s T y p e
Maps a j a v a . l a n g . C l a s sto a JDBC VARCHAR (using the Class name) Registered under c l a s sand j a v a . l a n g . C l a s sin the type registry (see Section 6.5, Type registry).
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
87/215
12/30/13
6.1.1.21. j a v a . s q l . B l o b
o r g . h i b e r n a t e . t y p e . B l o b T y p e
Maps a j a v a . s q l . B l o bto a JDBC BLOB Registered under b l o band j a v a . s q l . B l o bin the type registry (see Section 6.5, Type registry).
6.1.1.22. j a v a . s q l . C l o b
o r g . h i b e r n a t e . t y p e . C l o b T y p e
Maps a j a v a . s q l . C l o bto a JDBC CLOB Registered under c l o band j a v a . s q l . C l o bin the type registry (see Section 6.5, Type registry).
6.1.1.23. byte[]
o r g . h i b e r n a t e . t y p e . B i n a r y T y p e
Maps a primitive byte[] to a JDBC VARBINARY Registered under b i n a r yand b y t e [ ]in the type registry (see Section 6.5, Type registry).
o r g . h i b e r n a t e . t y p e . M a t e r i a l i z e d B l o b T y p e
Maps a primitive byte[] to a JDBC BLOB Registered under m a t e r i a l i z e d _ b l o bin the type registry (see Section 6.5, Type registry).
o r g . h i b e r n a t e . t y p e . I m a g e T y p e
Maps a primitive byte[] to a JDBC LONGVARBINARY Registered under i m a g ein the type registry (see Section 6.5, Type registry).
6.1.1.24. Byte[]
o r g . h i b e r n a t e . t y p e . B i n a r y T y p e
Maps a java.lang.Byte[] to a JDBC VARBINARY Registered under w r a p p e r b i n a r y , B y t e [ ] and j a v a . l a n g . B y t e [ ] in the type registry (see
6.1.1.25. char[]
o r g . h i b e r n a t e . t y p e . C h a r A r r a y T y p e
Maps a char[] to a JDBC VARCHAR Registered under c h a r a c t e r sand c h a r [ ]in the type registry (see Section 6.5, Type registry).
6.1.1.26. Character[]
o r g . h i b e r n a t e . t y p e . C h a r a c t e r A r r a y T y p e
Maps a java.lang.Character[] to a JDBC VARCHAR Registered under w r a p p e r c h a r a c t e r s ,C h a r a c t e r [ ] and j a v a . l a n g . C h a r a c t e r [ ] in the type registry (see Section 6.5, Type registry).
6.1.1.27. j a v a . u t i l . U U I D
o r g . h i b e r n a t e . t y p e . U U I D B i n a r y T y p e
Maps a java.util.UUID to a JDBC BINARY Registered under u u i d b i n a r y and j a v a . u t i l . U U I D in the type registry (see Section 6.5, Type registry).
o r g . h i b e r n a t e . t y p e . U U I D C h a r T y p e
Maps a java.util.UUID to a JDBC CHAR (though VARCHAR is fine too for existing schemas)
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
88/215
12/30/13
Maps a java.util.UUID to the PostgreSQL UUID data type (through T y p e s # O T H E R which is how the PostgreSQL JDBC driver defines it). Registered under p g u u i din the type registry (see Section 6.5, Type registry).
6.1.1.28. j a v a . i o . S e r i a l i z a b l e
o r g . h i b e r n a t e . t y p e . S e r i a l i z a b l e T y p e
Maps implementors of java.lang.Serializable to a JDBC VARBINARY Unlike the other value types, there are multiple instances of this type. It gets registered once under
j a v a . i o . S e r i a l i z a b l e . Additionally it gets registered under the specific j a v a . i o . S e r i a l i z a b l e
Components represent aggregations of values into a single Java type. For example, you might have an Address class that aggregates street, city, state, etc information or a Name class that aggregates the parts of a person's Name. In many ways a component looks exactly like an entity. They are both (generally speaking) classes written specifically for the application. They both might have references to other application-specific classes, as well as to collections and simple JDK types. As discussed before, the only distinguishing factory is the fact that a component does not own its own lifecycle nor does it define an identifier.
Note
This notion of entity independence can be modified by the application developer using the concept of cascades. Cascades allow certain operations to continue (or "cascade") across an association from one entity to another. Cascades are covered in detail in Chapter 8, Association Mappings .
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
89/215
12/30/13
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
90/215
12/30/13
Important
It is important that we registered the type before adding mappings.
and added to
o r g . h i b e r n a t e . u s e r t y p e . C o m p o s i t e U s e r T y p e
were
originally
The second approach is the use the o r g . h i b e r n a t e . u s e r t y p e . U s e r T y p e interface, which presents a somewhat simplified view of the
o r g . h i b e r n a t e . t y p e . T y p e
interface.
Using
There
is
not
much
difference
between
the
o r g . h i b e r n a t e . t y p e . T y p e
example
and
the
choose the o r g . h i b e r n a t e . t y p e . T y p e approach there are quite a few more methods you would need to implement as compared to the o r g . h i b e r n a t e . u s e r t y p e . U s e r T y p e .
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
91/215
12/30/13
The argument to r e g i s t e r T y p e O v e r r i d e is a o r g . h i b e r n a t e . t y p e . B a s i c T y p e which is a specialization of the o r g . h i b e r n a t e . t y p e . T y p ewe saw before. It adds a single method:
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
92/215
12/30/13
implementation of o r g . h i b e r n a t e . u s e r t y p e . U s e r C o l l e c t i o n T y p e ). Notice how in Example 7.2, Collection mapping using @OneToMany and @JoinColumn the instance variable p a r t s was initialized with an instance of H a s h S e t . This is the best way to initialize collection valued properties of newly instantiated (non-persistent) instances. When you make the instance persistent, by calling p e r s i s t ( ) , Hibernate will actually replace the H a s h S e t with an instance of Hibernate's own implementation of S e t . Be aware of the following error:
Collections instances have the usual behavior of value types. They are automatically persisted when referenced by a persistent object and are automatically deleted when unreferenced. If a collection is
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
93/215
12/30/13
Note
Use persistent collections the same way you use ordinary Java collections. However, ensure you understand the semantics of bidirectional associations (see Section 7.3.2, Bidirectional associations).
Product describes a unidirectional relationship with Part using the join column PART_ID. In this unidirectional one to many scenario you can also use a join table as seen in Example 7.3, Collection mapping using @OneToMany and @JoinTable.
Without describing any physical mapping (no @ J o i n C o l u m n or @ J o i n T a b l e ), a unidirectional one to many with join table is used. The table name is the concatenation of the owner table name, _, and the other side table name. The foreign key name(s) referencing the owner table is the concatenation of the owner table, _, and the owner primary key column(s) name. The foreign key name(s) referencing the other side is the concatenation of the owner property name, _, and the other side primary key column(s) name. A unique constraint is added to the foreign key referencing the other side table to reflect the one to many. Lets have a look now how collections are mapped using Hibernate mapping files. In this case the first
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
94/215
12/30/13
In Example 7.4, Mapping a Set using <set> a one-to-many association links the P r o d u c t and P a r t entities. This association requires the existence of a foreign key column and possibly an index column to the P a r ttable. This mapping loses certain semantics of normal Java collections: An instance of the contained entity class cannot belong to more than one instance of the collection. An instance of the contained entity class cannot appear at more than one value of the collection index. Looking closer at the used < o n e t o m a n y >tag we see that it has the following options.
missing rows will be handled. i g n o r ewill treat a missing row as a null association.
e n t i t y n a m e(optional): the entity name of the associated class, as an alternative to c l a s s .
The < o n e t o m a n y > element does not need to declare any columns. Nor is it necessary to specify the
t a b l ename anywhere.
Warning
If the foreign key column of a < o n e t o m a n y > association is declared
N O T N U L L , you must declare the < k e y > mapping n o t n u l l = " t r u e " or use a
bidirectional association with the collection mapping marked i n v e r s e = " t r u e " . See Section 7.3.2, Bidirectional associations.
Apart from the < s e t > tag as shown in Example 7.4, Mapping a Set using <set>, there is also < l i s t > ,
< m a p > ,< b a g > ,< a r r a y >and < p r i m i t i v e a r r a y >mapping elements. The < m a p >element is representative:
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
95/215
12/30/13
element
l a z y(optional - defaults to t r u e ): disables lazy fetching and specifies that the association is
always eagerly fetched. It can also be used to enable "extra-lazy" fetching where most operations do not initialize the collection. This is suitable for large collections.
i n v e r s e(optional - defaults to f a l s e ): marks this collection as the "inverse" end of a
bidirectional association.
c a s c a d e(optional - defaults to n o n e ): enables operations to cascade to child entities. s o r t(optional): specifies a sorted collection with n a t u r a lsort order or a given comparator
class.
o r d e r b y(optional): specifies a table column or columns that define the iteration order of the M a p ,S e tor bag, together with an optional a s cor d e s c . w h e r e(optional): specifies an arbitrary SQL W H E R Econdition that is used when retrieving or
removing the collection. This is useful if the collection needs to contain only a subset of the available data.
f e t c h(optional, defaults to s e l e c t ): chooses between outer-join fetching, fetching by
collection.
a c c e s s(optional - defaults to p r o p e r t y ): the strategy Hibernate uses for accessing the
collection results in increments of the owning entity's version. For one-to-many associations you may want to disable this setting.
m u t a b l e(optional - defaults to t r u e ): a value of f a l s especifies that the elements of the
collection never change. This allows for minor performance optimization in some cases.
After exploring the basic mapping of collections in the preceding paragraphs we will now focus details like physical mapping considerations, indexed collections and collections of value types.
or
< k e yc o l u m n = " p r o d u c t S e r i a l N u m b e r "n o t n u l l = " t r u e " / >
The foreign key constraint can use O ND E L E T EC A S C A D E . In XML this can be expressed via:
< k e yc o l u m n = " p r o d u c t S e r i a l N u m b e r "o n d e l e t e = " c a s c a d e " / >
See Section 5.1.11.3, Key for more information about the < k e y >element.
7.2.2.1. Lists
Lists can be mapped in two different ways: as ordered lists, where the order is not materialized in the database as indexed lists, where the order is materialized in the database
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
96/215
12/30/13
To store the index value in a dedicated column, use the @ j a v a x . p e r s i s t e n c e . O r d e r C o l u m n annotation on your property. This annotations describes the column name and attributes of the column keeping the index value. This column is hosted on the table containing the association foreign key. If the column name is not specified, the default is the name of the referencing property, followed by underscore, followed by O R D E R(in the following example, it would be o r d e r s _ O R D E R ).
Note
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741 97/215
12/30/13
We
convert to
If you are leveraging a custom list index base (maybe currently using the o r g . h i b e r n a t e . a n n o t a t i o n s . I n d e x C o l u m n . l i t e r a l attribute), you can specify in Java. this using the
@ o r g . h i b e r n a t e . a n n o t a t i o n s . L i s t I n d e x B a s e in
Looking again at the Hibernate mapping file equivalent, the index of an array or list is always of type
i n t e g e r and is mapped using the < l i s t i n d e x > element. The mapped column contains sequential
If your table does not have an index column, and you still wish to use L i s t as the property type, you can map the property as a Hibernate <bag>. A bag does not retain its order when it is retrieved from the database, but it can be optionally sorted or ordered.
7.2.2.2. Maps
The question with M a p s is where the key value is stored. There are everal options. Maps can borrow their keys from one of the associated entity properties or have dedicated columns to store an explicit key. To use one of the target entity property as a key of the map, use @ M a p K e y ( n a m e = " m y P r o p e r t y " ) , where
m y P r o p e r t y is a property name in the target entity. When using @ M a p K e y without the name attribuate,
the target entity primary key is used. The map key uses the same column as the property pointed out. There is no additional column defined to hold the map key, because the map key represent a target property. Be aware that once loaded, the key is no longer kept in sync with the property. In other words, if you change the property value, the key will not change automatically in your Java model.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
98/215
12/30/13
prefix for your embeddable object property names. You can also use @ M a p K e y C l a s sto define the type of the key if you don't use generics.
Note
We recommend you to migrate from @ o r g . h i b e r n a t e . a n n o t a t i o n s . M a p K e y/
@ o r g . h i b e r n a t e . a n n o t a t i o n . M a p K e y M a n y T o M a n y
to
the
new
standard
Using Hibernate mapping files there exists equivalent concepts to the descibed annotations. You have to use < m a p k e y > , < m a p k e y m a n y t o m a n y > and < c o m p o s i t e m a p k e y > . < m a p k e y > is used for any basic type, < m a p k e y m a n y t o m a n y >for an entity reference and < c o m p o s i t e m a p k e y >for a composite type.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
99/215
12/30/13
The collection table holding the collection data is set using the @ C o l l e c t i o n T a b l e annotation. If omitted the collection table name defaults to the concatenation of the name of the containing entity and the name of the collection attribute, separated by an underscore. In our example, it would be U s e r _ n i c k n a m e s . The column holding the basic type is set using the @ C o l u m n annotation. If omitted, the column name defaults to the property name: in our example, it would be n i c k n a m e s . But you are not limited to basic types, the collection type can be any embeddable object. To override the columns of the embeddable object in the collection table, use the @ A t t r i b u t e O v e r r i d eannotation.
Note
in @ A t t r i b u t e O v e r r i d e , you must use the v a l u e . prefix to override properties of the embeddable object used in the map value and the k e y . prefix to override properties of the embeddable object used in the map key.
@ E n t i t y p u b l i cc l a s sU s e r{ @ E l e m e n t C o l l e c t i o n @ A t t r i b u t e O v e r r i d e s ( { @ A t t r i b u t e O v e r r i d e ( n a m e = " k e y . s t r e e t 1 " ,c o l u m n = @ C o l u m n ( n a m e = " f l d _ s t r e e t " ) ) , @ A t t r i b u t e O v e r r i d e ( n a m e = " v a l u e . s t a r s " ,c o l u m n = @ C o l u m n ( n a m e = " f l d _ n o t e " ) ) } ) p u b l i cM a p < A d d r e s s , R a t i n g >g e t F a v H o m e s ( ){. . .}
Note
We recommend you to migrate from
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
100/215
12/30/13
to
the
new
Using the mapping file approach a collection of values is mapped using the < e l e m e n t >tag. For example:
Example 7.16. <element> tag for collection values using mapping files
< e l e m e n t c o l u m n = " c o l u m n _ n a m e " f o r m u l a = " a n yS Q Le x p r e s s i o n " t y p e = " t y p e n a m e " l e n g t h = " L " p r e c i s i o n = " P " s c a l e = " S " n o t n u l l = " t r u e | f a l s e " u n i q u e = " t r u e | f a l s e " n o d e = " e l e m e n t n a m e " / > c o l u m n(optional): the name of the column holding the collection element values. f o r m u l a(optional): an SQL formula used to evaluate the element. t y p e(required): the type of the collection element.
Using Hibernate mapping files you specify a comparator in the mapping file with < s o r t > :
Allowed values of the s o r t attribute are u n s o r t e d , n a t u r a l and the name of a class implementing
j a v a . u t i l . C o m p a r a t o r .
Tip
Sorted collections actually behave like
j a v a . u t i l . T r e e S e t
or
j a v a . u t i l . T r e e M a p .
If you want the database itself to order the collection elements, use the o r d e r b y attribute of s e t ,b a g
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
101/215
12/30/13
Note
The value of the o r d e r b yattribute is an SQL ordering, not an HQL ordering.
Example 7.21. Bidirectional one to many with many to one side as association owner
@ E n t i t y p u b l i cc l a s sT r o o p{ @ O n e T o M a n y ( m a p p e d B y = " t r o o p " ) p u b l i cS e t < S o l d i e r >g e t S o l d i e r s ( ){ . . . } @ E n t i t y p u b l i cc l a s sS o l d i e r{ @ M a n y T o O n e @ J o i n C o l u m n ( n a m e = " t r o o p _ f k " ) p u b l i cT r o o pg e t T r o o p ( ){ . . . }
T r o o p has a bidirectional one to many relationship with S o l d i e r through the t r o o p property. You don't
have to (must not) define any physical mapping in the m a p p e d B yside. To map a bidirectional one to many, with the one-to-many side as the owning side, you have to remove the m a p p e d B y element and set the many to one @ J o i n C o l u m n as insertable and updatable to false. This solution is not optimized and will produce additional UPDATE statements.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
102/215
12/30/13
How does the mappping of a bidirectional mapping look like in Hibernate mapping xml? There you define a bidirectional one-to-many association by mapping a one-to-many association to the same table column(s) as a many-to-one association and declaring the many-valued end i n v e r s e = " t r u e " .
Mapping one end of an association with i n v e r s e = " t r u e " does not affect the operation of cascades as these are orthogonal concepts. A many-to-many association is defined logically using the @ M a n y T o M a n y annotation. You also have to describe the association table and the join conditions using the @ J o i n T a b l e annotation. If the association is bidirectional, one side has to be the owner and one side has to be the inverse end (ie. it will be ignored when updating the relationship values in the association table):
In this example @ J o i n T a b l e defines a n a m e , an array of join columns, and an array of inverse join columns. The latter ones are the columns of the association table which refer to the E m p l o y e e primary key (the "other side"). As seen previously, the other side don't have to (must not) describe the physical mapping: a simple m a p p e d B yargument containing the owner side property name bind the two. As any other annotations, most values are guessed in a many to many relationship. Without describing any physical mapping in a unidirectional many to many the following rules applied. The table name is the concatenation of the owner table name, _ and the other side table name. The foreign key name(s) referencing the owner table is the concatenation of the owner table name, _ and the owner primary key column(s). The foreign key name(s) referencing the other side is the concatenation of the owner property name, _ , and the other side primary key column(s). These are the same rules used for a unidirectional one to many relationship.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
103/215
12/30/13
AS t o r e _ C i t y is used as the join table. The S t o r e _ i d column is a foreign key to the S t o r e table. The
i m p l a n t e d I n _ i dcolumn is a foreign key to the C i t ytable.
Without describing any physical mapping in a bidirectional many to many the following rules applied. The table name is the concatenation of the owner table name, _ and the other side table name. The foreign key name(s) referencing the owner table is the concatenation of the other side property name, _ , and the owner primary key column(s). The foreign key name(s) referencing the other side is the concatenation of the owner property name, _ , and the other side primary key column(s). These are the same rules used for a unidirectional one to many relationship.
AS t o r e _ C u s t o m e ris used as the join table. The s t o r e s _ i dcolumn is a foreign key to the S t o r etable. The
c u s t o m e r s _ i dcolumn is a foreign key to the C u s t o m e rtable.
Using Hibernate mapping files you can map a bidirectional many-to-many association by mapping two many-to-many associations to the same database table and declaring one end as inverse.
Note
You cannot select an indexed collection.
Example 7.27, Many to many association using Hibernate mapping files shows a bidirectional many-tomany association that illustrates how each category can have many items and each item can be in many categories:
Changes made only to the inverse end of the association are not persisted. This means that Hibernate has two representations in memory for every bidirectional association: one link from A to B and another link from B to A. This is easier to understand if you think about the Java object model and how a many-
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
104/215
12/30/13
Example 7.28. Effect of inverse vs. non-inverse side of many to many associations
c a t e g o r y . g e t I t e m s ( ) . a d d ( i t e m ) ; i t e m . g e t C a t e g o r i e s ( ) . a d d ( c a t e g o r y ) ; s e s s i o n . p e r s i s t ( i t e m ) ; s e s s i o n . p e r s i s t ( c a t e g o r y ) ; / /T h ec a t e g o r yn o w" k n o w s "a b o u tt h er e l a t i o n s h i p / /T h ei t e mn o w" k n o w s "a b o u tt h er e l a t i o n s h i p / /T h er e l a t i o n s h i pw o n ' tb es a v e d ! / /T h er e l a t i o n s h i pw i l lb es a v e d
The non-inverse side is used to save the in-memory representation to the database.
If there is no such property on the child class, the association cannot be considered truly bidirectional. That is, there is information available at one end of the association that is not available at the other end. In this case, you cannot map the collection i n v e r s e = " t r u e " . Instead, you could use the following mapping:
Example 7.30. Bidirectional association with indexed collection, but no index column
< c l a s sn a m e = " P a r e n t " > < i dn a m e = " i d "c o l u m n = " p a r e n t _ i d " / > . . . . < m a pn a m e = " c h i l d r e n " > < k e yc o l u m n = " p a r e n t _ i d " n o t n u l l = " t r u e " / > < m a p k e yc o l u m n = " n a m e " t y p e = " s t r i n g " / > < o n e t o m a n yc l a s s = " C h i l d " / > < / m a p > < / c l a s s > < c l a s sn a m e = " C h i l d " > < i dn a m e = " i d "c o l u m n = " c h i l d _ i d " / > . . . . < m a n y t o o n en a m e = " p a r e n t " c l a s s = " P a r e n t " c o l u m n = " p a r e n t _ i d " i n s e r t = " f a l s e " u p d a t e = " f a l s e " n o t n u l l = " t r u e " / > < / c l a s s >
Note that in this mapping, the collection-valued end of the association is responsible for updates to the foreign key.
12/30/13
A second approach is to remodel the association as an entity class. This is the most common approach. A final alternative is to use composite elements, which will be discussed later.
An < i d b a g >has a synthetic id generator, just like an entity class. A different surrogate key is assigned to each collection row. Hibernate does not, however, provide any mechanism for discovering the surrogate key value of a particular row. The update performance of an < i d b a g >supersedes a regular < b a g > . Hibernate can locate individual rows efficiently and update or delete them individually, similar to a list, map or set. In the current implementation, the n a t i v e identifier generation strategy is not supported for < i d b a g > collection identifiers.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
106/215
12/30/13
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
107/215
12/30/13
/ /g e t t e r / s e t t e r . . . }
Alternatively, if this association must be unidirectional you can enforce the N O TN U L Lconstraint.
Example 7.39. Enforcing NOT NULL constraint in unidirectional relation using annotations
p u b l i cc l a s sP a r e n t{ @ I d @ G e n e r a t e d V a l u e p r i v a t el o n gi d ; @ O n e T o M a n y ( o p t i o n a l = f a l s e ) p r i v a t eS e t < C h i l d >c h i l d r e n ; / /g e t t e r / s e t t e r . . . } p u b l i cc l a s sC h i l d{ @ I d @ G e n e r a t e d V a l u e p r i v a t el o n gi d ; p r i v a t eS t r i n gn a m e ; / /g e t t e r / s e t t e r . . . }
Example 7.40. Enforcing NOT NULL constraint in unidirectional relation using mapping files
< h i b e r n a t e m a p p i n g > < c l a s sn a m e = " P a r e n t " > < i dn a m e = " i d " > < g e n e r a t o rc l a s s = " s e q u e n c e " / > < / i d > < s e tn a m e = " c h i l d r e n " > < k e yc o l u m n = " p a r e n t _ i d "n o t n u l l = " t r u e " / > < o n e t o m a n yc l a s s = " C h i l d " / > < / s e t > < / c l a s s > < c l a s sn a m e = " C h i l d " > < i dn a m e = " i d " >
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
108/215
12/30/13
On the other hand, if a child has multiple parents, a many-to-many association is appropriate.
Table definitions:
For more examples and a complete explanation of a parent/child relationship mapping, see Chapter 23, Example: Parent/Child for more information. Even more complex association mappings are covered in the next chapter.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
109/215
12/30/13
8.4. Bidirectional associations 8.4.1. one-to-many / many-to-one 8.4.2. One-to-one 8.5. Bidirectional associations with join tables 8.5.1. one-to-many / many-to-one 8.5.2. one to one 8.5.3. Many-to-many 8.6. More complex association mappings
8.1. Introduction
Association mappings are often the most difficult thing to implement correctly. In this section we examine some canonical cases one by one, starting with unidirectional mappings and then bidirectional cases. We will use P e r s o nand A d d r e s sin all the examples. Associations will be classified by multiplicity and whether or not they map to an intervening join table. Nullable foreign keys are not considered to be good practice in traditional data modelling, so our examples do not use nullable foreign keys. This is not a requirement of Hibernate, and the mappings will work if you drop the nullability constraints.
8.2.1. Many-to-one
A unidirectional many-to-one association is the most common kind of unidirectional association.
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " i d "c o l u m n = " p e r s o n I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < m a n y t o o n en a m e = " a d d r e s s " c o l u m n = " a d d r e s s I d " n o t n u l l = " t r u e " / > < / c l a s s > < c l a s sn a m e = " A d d r e s s " > < i dn a m e = " i d "c o l u m n = " a d d r e s s I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < / c l a s s > c r e a t et a b l eP e r s o n(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y ,a d d r e s s I db i g i n tn o tn u l l) c r e a t et a b l eA d d r e s s(a d d r e s s I db i g i n tn o tn u l lp r i m a r yk e y)
8.2.2. One-to-one
A unidirectional one-to-one association on a foreign key is almost identical. The only difference is the column unique constraint.
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " i d "c o l u m n = " p e r s o n I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < m a n y t o o n en a m e = " a d d r e s s " c o l u m n = " a d d r e s s I d " u n i q u e = " t r u e " n o t n u l l = " t r u e " / > < / c l a s s > < c l a s sn a m e = " A d d r e s s " > < i dn a m e = " i d "c o l u m n = " a d d r e s s I d " > < g e n e r a t o rc l a s s = " n a t i v e " / >
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
110/215
12/30/13
< / i d > < / c l a s s >
c r e a t et a b l eP e r s o n(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y ,a d d r e s s I db i g i n tn o tn u l lu n i q u e) c r e a t et a b l eA d d r e s s(a d d r e s s I db i g i n tn o tn u l lp r i m a r yk e y)
A unidirectional one-to-one association on a primary key usually uses a special id generator In this example, however, we have reversed the direction of the association:
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " i d "c o l u m n = " p e r s o n I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < / c l a s s > < c l a s sn a m e = " A d d r e s s " > < i dn a m e = " i d "c o l u m n = " p e r s o n I d " > < g e n e r a t o rc l a s s = " f o r e i g n " > < p a r a mn a m e = " p r o p e r t y " > p e r s o n < / p a r a m > < / g e n e r a t o r > < / i d > < o n e t o o n en a m e = " p e r s o n "c o n s t r a i n e d = " t r u e " / > < / c l a s s > c r e a t et a b l eP e r s o n(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y) c r e a t et a b l eA d d r e s s(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y)
8.2.3. One-to-many
A unidirectional one-to-many association on a foreign key is an unusual case, and is not recommended.
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " i d "c o l u m n = " p e r s o n I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < s e tn a m e = " a d d r e s s e s " > < k e yc o l u m n = " p e r s o n I d " n o t n u l l = " t r u e " / > < o n e t o m a n yc l a s s = " A d d r e s s " / > < / s e t > < / c l a s s > < c l a s sn a m e = " A d d r e s s " > < i dn a m e = " i d "c o l u m n = " a d d r e s s I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < / c l a s s > c r e a t et a b l eP e r s o n(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y) c r e a t et a b l eA d d r e s s(a d d r e s s I db i g i n tn o tn u l lp r i m a r yk e y ,p e r s o n I db i g i n tn o tn u l l)
You should instead use a join table for this kind of association.
8.3.1. One-to-many
A unidirectional one-to-many association on a join table is the preferred option. Specifying u n i q u e = " t r u e " , changes the multiplicity from many-to-many to one-to-many.
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " i d "c o l u m n = " p e r s o n I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < s e tn a m e = " a d d r e s s e s "t a b l e = " P e r s o n A d d r e s s " > < k e yc o l u m n = " p e r s o n I d " / > < m a n y t o m a n yc o l u m n = " a d d r e s s I d " u n i q u e = " t r u e " c l a s s = " A d d r e s s " / > < / s e t > < / c l a s s > < c l a s sn a m e = " A d d r e s s " > < i dn a m e = " i d "c o l u m n = " a d d r e s s I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < / c l a s s > c r e a t et a b l eP e r s o n(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y) c r e a t et a b l eP e r s o n A d d r e s s(p e r s o n I db i g i n tn o tn u l l ,a d d r e s s I db i g i n tn o tn u l lp r i m a r yk e y) c r e a t et a b l eA d d r e s s(a d d r e s s I db i g i n tn o tn u l lp r i m a r yk e y)
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
111/215
12/30/13
8.3.2. Many-to-one
A unidirectional many-to-one association on a join table is common when the association is optional. For example:
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " i d "c o l u m n = " p e r s o n I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < j o i nt a b l e = " P e r s o n A d d r e s s " o p t i o n a l = " t r u e " > < k e yc o l u m n = " p e r s o n I d "u n i q u e = " t r u e " / > < m a n y t o o n en a m e = " a d d r e s s " c o l u m n = " a d d r e s s I d " n o t n u l l = " t r u e " / > < / j o i n > < / c l a s s > < c l a s sn a m e = " A d d r e s s " > < i dn a m e = " i d "c o l u m n = " a d d r e s s I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < / c l a s s > c r e a t et a b l eP e r s o n(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y) c r e a t et a b l eP e r s o n A d d r e s s(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y ,a d d r e s s I db i g i n tn o tn u l l) c r e a t et a b l eA d d r e s s(a d d r e s s I db i g i n tn o tn u l lp r i m a r yk e y)
8.3.3. One-to-one
A unidirectional one-to-one association on a join table is possible, but extremely unusual.
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " i d "c o l u m n = " p e r s o n I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < j o i nt a b l e = " P e r s o n A d d r e s s " o p t i o n a l = " t r u e " > < k e yc o l u m n = " p e r s o n I d " u n i q u e = " t r u e " / > < m a n y t o o n en a m e = " a d d r e s s " c o l u m n = " a d d r e s s I d " n o t n u l l = " t r u e " u n i q u e = " t r u e " / > < / j o i n > < / c l a s s > < c l a s sn a m e = " A d d r e s s " > < i dn a m e = " i d "c o l u m n = " a d d r e s s I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < / c l a s s > c r e a t et a b l eP e r s o n(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y) c r e a t et a b l eP e r s o n A d d r e s s(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y ,a d d r e s s I db i g i n tn o tn u l lu n i q u e) c r e a t et a b l eA d d r e s s(a d d r e s s I db i g i n tn o tn u l lp r i m a r yk e y)
8.3.4. Many-to-many
Finally, here is an example of a unidirectional many-to-many association .
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " i d "c o l u m n = " p e r s o n I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < s e tn a m e = " a d d r e s s e s "t a b l e = " P e r s o n A d d r e s s " > < k e yc o l u m n = " p e r s o n I d " / > < m a n y t o m a n yc o l u m n = " a d d r e s s I d " c l a s s = " A d d r e s s " / > < / s e t > < / c l a s s > < c l a s sn a m e = " A d d r e s s " > < i dn a m e = " i d "c o l u m n = " a d d r e s s I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < / c l a s s > c r e a t et a b l eP e r s o n(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y) c r e a t et a b l eP e r s o n A d d r e s s(p e r s o n I db i g i n tn o tn u l l ,a d d r e s s I db i g i n tn o tn u l l ,p r i m a r yk e y( p e r s o n I d ,a d d r e s s I d )) c r e a t et a b l eA d d r e s s(a d d r e s s I db i g i n tn o tn u l lp r i m a r yk e y)
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
112/215
12/30/13
If you use a L i s t , or other indexed collection, set the k e y column of the foreign key to n o t n u l l . Hibernate will manage the association from the collections side to maintain the index of each element, making the other side virtually inverse by setting u p d a t e = " f a l s e "and i n s e r t = " f a l s e " :
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " i d " / > . . . < m a n y t o o n en a m e = " a d d r e s s " c o l u m n = " a d d r e s s I d " n o t n u l l = " t r u e " i n s e r t = " f a l s e " u p d a t e = " f a l s e " / > < / c l a s s > < c l a s sn a m e = " A d d r e s s " > < i dn a m e = " i d " / > . . . < l i s tn a m e = " p e o p l e " > < k e yc o l u m n = " a d d r e s s I d "n o t n u l l = " t r u e " / > < l i s t i n d e xc o l u m n = " p e o p l e I d x " / > < o n e t o m a n yc l a s s = " P e r s o n " / > < / l i s t > < / c l a s s >
If the underlying foreign key column is N O TN U L L , it is important that you define n o t n u l l = " t r u e " on the
< k e y > element of the collection mapping. Do not only declare n o t n u l l = " t r u e " on a possible nested < c o l u m n >element, but on the < k e y >element.
8.4.2. One-to-one
A bidirectional one-to-one association on a foreign key is common:
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " i d "c o l u m n = " p e r s o n I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < m a n y t o o n en a m e = " a d d r e s s " c o l u m n = " a d d r e s s I d " u n i q u e = " t r u e " n o t n u l l = " t r u e " / > < / c l a s s > < c l a s sn a m e = " A d d r e s s " > < i dn a m e = " i d "c o l u m n = " a d d r e s s I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < o n e t o o n en a m e = " p e r s o n " p r o p e r t y r e f = " a d d r e s s " / > < / c l a s s > c r e a t et a b l eP e r s o n(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y ,a d d r e s s I db i g i n tn o tn u l lu n i q u e) c r e a t et a b l eA d d r e s s(a d d r e s s I db i g i n tn o tn u l lp r i m a r yk e y)
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
113/215
12/30/13
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
114/215
12/30/13
8.5.3. Many-to-many
Here is an example of a bidirectional many-to-many association .
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " i d "c o l u m n = " p e r s o n I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < s e tn a m e = " a d d r e s s e s "t a b l e = " P e r s o n A d d r e s s " > < k e yc o l u m n = " p e r s o n I d " / > < m a n y t o m a n yc o l u m n = " a d d r e s s I d " c l a s s = " A d d r e s s " / > < / s e t > < / c l a s s > < c l a s sn a m e = " A d d r e s s " > < i dn a m e = " i d "c o l u m n = " a d d r e s s I d " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < s e tn a m e = " p e o p l e "i n v e r s e = " t r u e "t a b l e = " P e r s o n A d d r e s s " > < k e yc o l u m n = " a d d r e s s I d " / > < m a n y t o m a n yc o l u m n = " p e r s o n I d " c l a s s = " P e r s o n " / > < / s e t > < / c l a s s > c r e a t et a b l eP e r s o n(p e r s o n I db i g i n tn o tn u l lp r i m a r yk e y) c r e a t et a b l eP e r s o n A d d r e s s(p e r s o n I db i g i n tn o tn u l l ,a d d r e s s I db i g i n tn o tn u l l ,p r i m a r yk e y( p e r s o n I d ,a d d r e s s I d )) c r e a t et a b l eA d d r e s s(a d d r e s s I db i g i n tn o tn u l lp r i m a r yk e y)
You can then map an association to the current instance, the one with null e f f e c t i v e E n d D a t e , by using:
< m a n y t o o n en a m e = " c u r r e n t A c c o u n t I n f o " p r o p e r t y r e f = " c u r r e n t A c c o u n t K e y " c l a s s = " A c c o u n t I n f o " > < c o l u m nn a m e = " a c c o u n t N u m b e r " / > < f o r m u l a > ' 1 ' < / f o r m u l a > < / m a n y t o o n e >
In a more complex example, imagine that the association between E m p l o y e e and O r g a n i z a t i o n is maintained in an E m p l o y m e n t table full of historical employment data. An association to the employee's most recent employer, the one with the most recent s t a r t D a t e , could be mapped in the following way:
< j o i n > < k e yc o l u m n = " e m p l o y e e I d " / > < s u b s e l e c t > s e l e c te m p l o y e e I d ,o r g I d f r o mE m p l o y m e n t s g r o u pb yo r g I d h a v i n gs t a r t D a t e=m a x ( s t a r t D a t e ) < / s u b s e l e c t > < m a n y t o o n en a m e = " m o s t R e c e n t E m p l o y e r " c l a s s = " O r g a n i z a t i o n " c o l u m n = " o r g I d " / > < / j o i n >
This functionality allows a degree of creativity and flexibility, but it is more practical to handle these kinds of cases using HQL or a criteria query.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
115/215
12/30/13
Now N a m e can be persisted as a component of P e r s o n .N a m e defines getter and setter methods for its persistent properties, but it does not need to declare any interfaces or identifier properties. Our Hibernate mapping would look like this:
< c l a s sn a m e = " e g . P e r s o n "t a b l e = " p e r s o n " > < i dn a m e = " K e y "c o l u m n = " p i d "t y p e = " s t r i n g " > < g e n e r a t o rc l a s s = " u u i d " / > < / i d > < p r o p e r t yn a m e = " b i r t h d a y "t y p e = " d a t e " / > < c o m p o n e n tn a m e = " N a m e "c l a s s = " e g . N a m e " >< ! -c l a s sa t t r i b u t eo p t i o n a l> < p r o p e r t yn a m e = " i n i t i a l " / > < p r o p e r t yn a m e = " f i r s t " / > < p r o p e r t yn a m e = " l a s t " / > < / c o m p o n e n t > < / c l a s s >
The person table would have the columns p i d ,b i r t h d a y ,i n i t i a l ,f i r s tand l a s t . Like value types, components do not support shared references. In other words, two persons could have the same name, but the two person objects would contain two independent name objects that were only "the same" by value. The null value semantics of a component are ad hoc. When reloading the containing object, Hibernate will assume that if all component columns are null, then the entire component is null. This is suitable for most purposes. The properties of a component can be of any Hibernate type (collections, many-to-one associations, other components, etc). Nested components should not be considered an exotic usage. Hibernate is intended to support a fine-grained object model. The < c o m p o n e n t >element allows a < p a r e n t >subelement that maps a property of the component class as a reference back to the containing entity.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
116/215
12/30/13
Important
If you define a S e t of composite elements, it is important to implement
e q u a l s ( )and h a s h C o d e ( )correctly.
Composite elements can contain components but not collections. If your composite element contains components, use the < n e s t e d c o m p o s i t e e l e m e n t > tag. This case is a collection of components which themselves have components. You may want to consider if a one-to-many association is more appropriate. Remodel the composite element as an entity, but be aware that even though the Java model is the same, the relational model and persistence semantics are still slightly different. A composite element mapping does not support null-able properties if you are using a < s e t > . There is no separate primary key column in the composite element table. Hibernate uses each column's value to identify a record when deleting objects, which is not possible with null values. You have to either use only not-null properties in a composite-element or choose a < l i s t > ,< m a p > ,< b a g >or < i d b a g > . A special case of a composite element is a composite element with a nested < m a n y t o o n e > element. This mapping allows you to map extra columns of a many-to-many association table to the composite element class. The following is a many-to-many association from O r d e r to I t e m , where p u r c h a s e D a t e ,
p r i c eand q u a n t i t yare properties of the association: < c l a s sn a m e = " e g . O r d e r ". . . .> . . . . < s e tn a m e = " p u r c h a s e d I t e m s "t a b l e = " p u r c h a s e _ i t e m s "l a z y = " t r u e " > < k e yc o l u m n = " o r d e r _ i d " > < c o m p o s i t e e l e m e n tc l a s s = " e g . P u r c h a s e " > < p r o p e r t yn a m e = " p u r c h a s e D a t e " / > < p r o p e r t yn a m e = " p r i c e " / > < p r o p e r t yn a m e = " q u a n t i t y " / > < m a n y t o o n en a m e = " i t e m "c l a s s = " e g . I t e m " / >< ! -c l a s sa t t r i b u t ei so p t i o n a l> < / c o m p o s i t e e l e m e n t > < / s e t > < / c l a s s >
There cannot be a reference to the purchase on the other side for bidirectional association navigation. Components are value types and do not allow shared references. A single P u r c h a s ecan be in the set of an O r d e r , but it cannot be referenced by the I t e mat the same time. Even ternary (or quaternary, etc) associations are possible:
< c l a s sn a m e = " e g . O r d e r ". . . .> . . . . < s e tn a m e = " p u r c h a s e d I t e m s "t a b l e = " p u r c h a s e _ i t e m s "l a z y = " t r u e " > < k e yc o l u m n = " o r d e r _ i d " > < c o m p o s i t e e l e m e n tc l a s s = " e g . O r d e r L i n e " > < m a n y t o o n en a m e = " p u r c h a s e D e t a i l sc l a s s = " e g . P u r c h a s e " / > < m a n y t o o n en a m e = " i t e m "c l a s s = " e g . I t e m " / > < / c o m p o s i t e e l e m e n t > < / s e t > < / c l a s s >
Composite elements can appear in queries using the same syntax as associations to other entities.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
117/215
12/30/13
Note
In Hibernate, although the second requirement is not an absolutely hard requirement of Hibernate, it is recommended.
You cannot use an I d e n t i f i e r G e n e r a t o r to generate composite keys. Instead the application must assign its own identifiers. Use the < c o m p o s i t e i d > tag, with nested < k e y p r o p e r t y > elements, in place of the usual < i d > declaration. For example, the O r d e r L i n e class has a primary key that depends upon the (composite) primary key of O r d e r .
< c l a s sn a m e = " O r d e r L i n e " > < c o m p o s i t e i dn a m e = " i d "c l a s s = " O r d e r L i n e I d " > < k e y p r o p e r t yn a m e = " l i n e I d " / > < k e y p r o p e r t yn a m e = " o r d e r I d " / > < k e y p r o p e r t yn a m e = " c u s t o m e r I d " / > < / c o m p o s i t e i d > < p r o p e r t yn a m e = " n a m e " / > < m a n y t o o n en a m e = " o r d e r "c l a s s = " O r d e r " i n s e r t = " f a l s e "u p d a t e = " f a l s e " > < c o l u m nn a m e = " o r d e r I d " / > < c o l u m nn a m e = " c u s t o m e r I d " / > < / m a n y t o o n e > . . . . < / c l a s s >
Any foreign keys referencing the O r d e r L i n e table are now composite. Declare this in your mappings for other classes. An association to O r d e r L i n eis mapped like this:
< m a n y t o o n en a m e = " o r d e r L i n e "c l a s s = " O r d e r L i n e " > < ! -t h e" c l a s s "a t t r i b u t ei so p t i o n a l ,a su s u a l> < c o l u m nn a m e = " l i n e I d " / > < c o l u m nn a m e = " o r d e r I d " / > < c o l u m nn a m e = " c u s t o m e r I d " / > < / m a n y t o o n e >
Tip
The c o l u m n element is an alternative to the c o l u m n attribute everywhere. Using the c o l u m n element just gives more declaration options, which are mostly useful when utilizing h b m 2 d d l
The < o n e t o m a n y >element declares no columns. If O r d e r L i n eitself owns a collection, it also has a composite foreign key.
< c l a s sn a m e = " O r d e r L i n e " > . . . . . . . . < l i s tn a m e = " d e l i v e r y A t t e m p t s " > < k e y > < ! -ac o l l e c t i o ni n h e r i t st h ec o m p o s i t ek e yt y p e> < c o l u m nn a m e = " l i n e I d " / >
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
118/215
12/30/13
The semantics of a < d y n a m i c c o m p o n e n t > mapping are identical to < c o m p o n e n t > . The advantage of this kind of mapping is the ability to determine the actual properties of the bean at deployment time just by editing the mapping document. Runtime manipulation of the mapping document is also possible, using a DOM parser. You can also access, and change, Hibernate's configuration-time metamodel via the C o n f i g u r a t i o nobject.
10.2. Limitations
table per hierarchy and table per subclass strategies under the the same < c l a s s > element, by combining the < s u b c l a s s >and < j o i n >elements (see below for an example). It is possible to define s u b c l a s s ,u n i o n s u b c l a s s , and j o i n e d s u b c l a s s mappings in separate mapping documents directly beneath h i b e r n a t e m a p p i n g . This allows you to extend a class hierarchy by adding a new mapping file. You must specify an e x t e n d s attribute in the subclass mapping, naming a previously mapped superclass. Previously this feature made the ordering of the mapping documents important. Since Hibernate, the ordering of mapping files is irrelevant when using the extends keyword. The ordering inside a single mapping file still needs to be defined as superclasses before subclasses.
< h i b e r n a t e m a p p i n g > < s u b c l a s sn a m e = " D o m e s t i c C a t "e x t e n d s = " C a t "d i s c r i m i n a t o r v a l u e = " D " > < p r o p e r t yn a m e = " n a m e "t y p e = " s t r i n g " / > < / s u b c l a s s > < / h i b e r n a t e m a p p i n g >
12/30/13
Exactly one table is required. There is a limitation of this mapping strategy: columns declared by the subclasses, such as C C T Y P E , cannot have N O TN U L Lconstraints.
Four tables are required. The three subclass tables have primary key associations to the superclass table so the relational model is actually a one-to-one association.
The optional f e t c h = " s e l e c t " declaration tells Hibernate not to fetch the C h e q u e P a y m e n t subclass data using an outer join when querying the superclass.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
120/215
12/30/13
10.1.4. Mixing table per class hierarchy with table per subclass
You can even mix the table per hierarchy and table per subclass strategies using the following approach:
< c l a s sn a m e = " P a y m e n t "t a b l e = " P A Y M E N T " > < i dn a m e = " i d "t y p e = " l o n g "c o l u m n = " P A Y M E N T _ I D " > < g e n e r a t o rc l a s s = " n a t i v e " / > < / i d > < d i s c r i m i n a t o rc o l u m n = " P A Y M E N T _ T Y P E "t y p e = " s t r i n g " / > < p r o p e r t yn a m e = " a m o u n t "c o l u m n = " A M O U N T " / > . . . < s u b c l a s sn a m e = " C r e d i t C a r d P a y m e n t "d i s c r i m i n a t o r v a l u e = " C R E D I T " > < j o i nt a b l e = " C R E D I T _ P A Y M E N T " > < p r o p e r t yn a m e = " c r e d i t C a r d T y p e "c o l u m n = " C C T Y P E " / > . . . < / j o i n > < / s u b c l a s s > < s u b c l a s sn a m e = " C a s h P a y m e n t "d i s c r i m i n a t o r v a l u e = " C A S H " > . . . < / s u b c l a s s > < s u b c l a s sn a m e = " C h e q u e P a y m e n t "d i s c r i m i n a t o r v a l u e = " C H E Q U E " > . . . < / s u b c l a s s > < / c l a s s >
For any of these mapping strategies, a polymorphic association to the root P a y m e n t class is mapped using < m a n y t o o n e > .
< m a n y t o o n en a m e = " p a y m e n t "c o l u m n = " P A Y M E N T _ I D "c l a s s = " P a y m e n t " / >
Three tables are involved for the subclasses. Each table defines columns for all properties of the class, including inherited properties. The limitation of this approach is that if a property is mapped on the superclass, the column name must be the same on all subclass tables. The identity generator strategy is not allowed in union subclass inheritance. The primary key seed has to be shared across all unioned subclasses of a hierarchy. If your superclass is abstract, map it with a b s t r a c t = " t r u e " . If it is not abstract, an additional table (it defaults to P A Y M E N Tin the example above), is needed to hold instances of the superclass.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
121/215
12/30/13
The disadvantage of this approach is that Hibernate does not generate SQL U N I O N s when performing polymorphic queries. For this mapping strategy, a polymorphic association to P a y m e n tis usually mapped using < a n y > .
< a n yn a m e = " p a y m e n t "m e t a t y p e = " s t r i n g "i d t y p e = " l o n g " > < m e t a v a l u ev a l u e = " C R E D I T "c l a s s = " C r e d i t C a r d P a y m e n t " / > < m e t a v a l u ev a l u e = " C A S H "c l a s s = " C a s h P a y m e n t " / > < m e t a v a l u ev a l u e = " C H E Q U E "c l a s s = " C h e q u e P a y m e n t " / > < c o l u m nn a m e = " P A Y M E N T _ C L A S S " / > < c o l u m nn a m e = " P A Y M E N T _ I D " / > < / a n y >
Once again, P a y m e n tis not mentioned explicitly. If we execute a query against the P a y m e n t interface, for example f r o m P a y m e n t , Hibernate automatically returns instances of C r e d i t C a r d P a y m e n t (and its subclasses, since they also implement P a y m e n t ), C a s h P a y m e n t and C h e q u e P a y m e n t , but not instances of
N o n e l e c t r o n i c T r a n s a c t i o n .
10.2. Limitations
There are limitations to the "implicit polymorphism" approach to the table per concrete-class mapping strategy. There are somewhat less restrictive limitations to < u n i o n s u b c l a s s >mappings. The following table shows the limitations of table per concrete-class mappings, and of implicit polymorphism, in Hibernate.
Table 10.1. Features of inheritance mappings Inheritance strategy table per classhierarchy table per subclass table per concrete-class (unionsubclass)
< m a n y t o o n e > < o n e t o o n e > < m a n y t o o n e > < o n e t o o n e > < o n e t o m a n y > < m a n y t o m a n y > s . g e t ( P a y m e n t . c l a s s ,i d )
Polymorphic many-to-one
Polymorphic one-to-one
Polymorphic one-to-many
Polymorphic many-to-many
Polymorphic l o a d ( ) / g e t ( )
< m a n y t o m a n y > s . g e t ( P a y m e n t . c l a s s ,i d )
(for
i n v e r s e = " t r u e "
< m a n y t o m a n y > s . g e t ( P a y m e n t . c l a s s ,i d )
only)
< m a n y t o a n y >
s . c r e a t e C r i t e r i a ( P a y m e n t . c l a s s ) . a d d (R e s t r i c t i o n s . i d E q ( i d )
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
122/215
12/30/13
Modifying persistent objects Modifying detached objects Automatic state detection Deleting persistent objects
11.9. Replicating object between two different datastores 11.10. Flushing the Session 11.11. Transitive persistence 11.12. Using metadata Hibernate is a full object/relational mapping solution that not only shields the developer from the details of the underlying database management system, but also offers state management of objects. This is, contrary to the management of SQL s t a t e m e n t s in common JDBC/SQL persistence layers, a natural object-oriented view of persistence in Java applications. In other words, Hibernate application developers should always think about the state of their objects, and not necessarily about the execution of SQL statements. This part is taken care of by Hibernate and is only relevant for the application developer when tuning the performance of the system.
If C a t has a generated identifier, the identifier is generated and assigned to the c a t when s a v e ( ) is called. If C a thas an a s s i g n e didentifier, or a composite key, the identifier should be assigned to the c a t instance before calling s a v e ( ) . You can also use p e r s i s t ( )instead of s a v e ( ) , with the semantics defined in the EJB3 early draft.
p e r s i s t ( ) makes a transient instance persistent. However, it does not guarantee that the identifier
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
123/215
12/30/13
s a v e ( )does guarantee to return an identifier. If an INSERT has to be executed to get the identifier (
e.g. "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is problematic in a long-running conversation with an extended Session/persistence context. Alternatively, you can assign the identifier using an overloaded version of s a v e ( ) .
D o m e s t i c C a tp k=n e wD o m e s t i c C a t ( ) ; p k . s e t C o l o r ( C o l o r . T A B B Y ) ; p k . s e t S e x ( ' F ' ) ; p k . s e t N a m e ( " P K " ) ; p k . s e t K i t t e n s (n e wH a s h S e t ( )) ; p k . a d d K i t t e n ( f r i t z ) ; s e s s . s a v e (p k ,n e wL o n g ( 1 2 3 4 )) ;
If the object you make persistent has associated objects (e.g. the k i t t e n s collection in the previous example), these objects can be made persistent in any order you like unless you have a N O T N U L L constraint upon a foreign key column. There is never a risk of violating foreign key constraints. However, you might violate a N O TN U L Lconstraint if you s a v e ( )the objects in the wrong order. Usually you do not bother with this detail, as you will normally use Hibernate's transitive persistence feature to save the associated objects automatically. Then, even N O TN U L L constraint violations do not occur - Hibernate will take care of everything. Transitive persistence is discussed later in this chapter.
Be aware that l o a d ( )will throw an unrecoverable exception if there is no matching database row. If the class is mapped with a proxy, l o a d ( ) just returns an uninitialized proxy and does not actually hit the database until you invoke a method of the proxy. This is useful if you wish to create an association to an object without actually loading it from the database. It also allows multiple instances to be loaded as a batch if b a t c h s i z eis defined for the class mapping. If you are not certain that a matching row exists, you should use the g e t ( ) method which hits the database immediately and returns null if there is no matching row.
C a tc a t=( C a t )s e s s . g e t ( C a t . c l a s s ,i d ) ; i f( c a t = = n u l l ){ c a t=n e wC a t ( ) ; s e s s . s a v e ( c a t ,i d ) ; } r e t u r nc a t ;
You can even load an object using an SQL S E L E C T . . . F O R U P D A T E , using a L o c k M o d e . See the API documentation for more information.
C a tc a t=( C a t )s e s s . g e t ( C a t . c l a s s ,i d ,L o c k M o d e . U P G R A D E ) ;
Any associated instances or contained collections will not be selected F O RU P D A T E , unless you decide to specify l o c kor a l las a cascade style for the association. It is possible to re-load an object and all its collections at any time, using the r e f r e s h ( ) method. This is useful when database triggers are used to initialize some of the properties of the object.
s e s s . s a v e ( c a t ) ; s e s s . f l u s h ( ) ;/ / f o r c et h eS Q LI N S E R T s e s s . r e f r e s h ( c a t ) ;/ / r e r e a dt h es t a t e( a f t e rt h et r i g g e re x e c u t e s )
How much does Hibernate load from the database and how many SQL S E L E C T s will it use? This depends on the fetching strategy. This is explained in Section 20.1, Fetching strategies.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
124/215
12/30/13
11.4. Querying
If you do not know the identifiers of the objects you are looking for, you need a query. Hibernate supports an easy-to-use but powerful object oriented query language (HQL). For programmatic query creation, Hibernate supports a sophisticated Criteria and Example query feature (QBC and QBE). You can also express your query in the native SQL of your database, with optional support from Hibernate for result set conversion into objects.
A query is usually executed by invoking l i s t ( ) . The result of the query will be loaded completely into a collection in memory. Entity instances retrieve d by a query are in a persistent state. The u n i q u e R e s u l t ( ) method offers a shortcut if you know your query will only return a single object. Queries that make use of eager fetching of collections usually return duplicates of the root objects, but with their collections initialized. You can filter these duplicates through a S e t .
by the query will already be in the session or second-level cache. If they are not already cached, i t e r a t e ( )will be slower than l i s t ( )and might require many database hits for a simple query, usually 1 for the initial select which only returns identifiers, and n additional selects to initialize the actual instances.
/ /f e t c hi d s I t e r a t o ri t e r=s e s s . c r e a t e Q u e r y ( " f r o me g . Q u xqo r d e rb yq . l i k e l i n e s s " ) . i t e r a t e ( ) ; w h i l e(i t e r . h a s N e x t ( )){ Q u xq u x=( Q u x )i t e r . n e x t ( ) ; / /f e t c ht h eo b j e c t / /s o m e t h i n gw ec o u l d n te x p r e s si nt h eq u e r y i f(q u x . c a l c u l a t e C o m p l i c a t e d A l g o r i t h m ( )){ / /d e l e t et h ec u r r e n ti n s t a n c e i t e r . r e m o v e ( ) ; / /d o n tn e e dt op r o c e s st h er e s t b r e a k ; } }
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
125/215
12/30/13
11.4.1.5. Pagination
If you need to specify bounds upon your result set, that is, the maximum number of rows you want to retrieve and/or the first row you want to retrieve, you can use methods of the Q u e r yinterface:
Q u e r yq=s e s s . c r e a t e Q u e r y ( " f r o mD o m e s t i c C a tc a t " ) ; q . s e t F i r s t R e s u l t ( 2 0 ) ; q . s e t M a x R e s u l t s ( 1 0 ) ; L i s tc a t s=q . l i s t ( ) ;
Hibernate knows how to translate this limit query into the native SQL of your DBMS.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
126/215
12/30/13
c a t s . c l o s e ( )
Note
that
an
open
database
connection
and
cursor is
required
for this
functionality. Use
Using a mapping document can be configured using the < q u e r y >node. Remember to use a C D A T A section if your query contains characters that could be interpreted as markup.
Parameter binding and executing is done programatically as seen in Example 11.3, Parameter binding of a named query.
The actual program code is independent of the query language that is used. You can also define native SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files. Also note that a query declaration inside a < h i b e r n a t e m a p p i n g >element requires a global unique name for the query, while a query declaration inside a < c l a s s > element is made unique automatically by prepending the fully qualified name of the class. For example e g . C a t . B y N a m e A n d M a x i m u m W e i g h t .
The returned collection is considered a bag that is a copy of the given collection. The original collection is
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
127/215
12/30/13
Even an empty filter query is useful, e.g. to load a subset of elements in a large collection:
C o l l e c t i o nt e n K i t t e n s=s e s s i o n . c r e a t e F i l t e r ( m o t h e r . g e t K i t t e n s ( ) ," " ) . s e t F i r s t R e s u l t ( 0 ) . s e t M a x R e s u l t s ( 1 0 ) . l i s t ( ) ;
The C r i t e r i a and the associated E x a m p l e API are discussed in more detail in Chapter 17, Criteria Queries .
SQL queries can contain named and positional parameters, just like Hibernate queries. More information about native SQL queries in Hibernate can be found in Chapter 18, Native SQL.
Sometimes this programming model is inefficient, as it requires in the same session both an SQL S E L E C T to load an object and an SQL U P D A T E to persist its updated state. Hibernate offers an alternate approach by using detached instances.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
128/215
12/30/13
If the C a twith identifier c a t I d had already been loaded by s e c o n d S e s s i o n when the application tried to reattach it, an exception would have been thrown. Use u p d a t e ( ) if you are certain that the session does not contain an already persistent instance with the same identifier. Use m e r g e ( ) if you want to merge your modifications at any time without consideration of the state of the session. In other words, u p d a t e ( )is usually the first method you would call in a fresh session, ensuring that the reattachment of your detached instances is the first operation that is executed. The application should individually u p d a t e ( ) detached instances that are reachable from the given detached instance only if it wants their state to be updated. This can be automated using transitive persistence. See Section 11.11, Transitive persistence for more information. The l o c k ( ) method also allows an application to reassociate an object with a new session. However, the detached instance has to be unmodified.
/ / j u s tr e a s s o c i a t e : s e s s . l o c k ( f r i t z ,L o c k M o d e . N O N E ) ; / / d oav e r s i o nc h e c k ,t h e nr e a s s o c i a t e : s e s s . l o c k ( i z i ,L o c k M o d e . R E A D ) ; / / d oav e r s i o nc h e c k ,u s i n gS E L E C T. . .F O RU P D A T E ,t h e nr e a s s o c i a t e : s e s s . l o c k ( p k ,L o c k M o d e . U P G R A D E ) ;
Note that l o c k ( ) can be used with various L o c k M o d e s. See the API documentation and the chapter on transaction handling for more information. Reattachment is not the only usecase for l o c k ( ) . Other models for long units of work are discussed in Section 13.3, Optimistic concurrency control.
The usage and semantics of s a v e O r U p d a t e ( ) seems to be confusing for new users. Firstly, so long as you are not trying to use instances from one session in another new session, you should not need to use u p d a t e ( ) , s a v e O r U p d a t e ( ) , or m e r g e ( ) . Some whole applications will never use either of these methods. Usually u p d a t e ( )or s a v e O r U p d a t e ( )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 u p d a t e ( )in a second session
s a v e O r U p d a t e ( )does the following:
if the object is already persistent in this session, do nothing if another object associated with the session has the same identifier, throw an exception if the object has no identifier property, s a v e ( )it if the object's identifier has the value assigned to a newly instantiated object, s a v e ( )it if the object is versioned by a < v e r s i o n > or < t i m e s t a m p > , and the version property value is the same value assigned to a newly instantiated object, s a v e ( )it otherwise u p d a t e ( )the object and m e r g e ( )is very different:
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
129/215
12/30/13
hold a reference to a deleted object. It is best to think of d e l e t e ( ) as making a persistent instance, transient.
s e s s . d e l e t e ( c a t ) ;
You can delete objects in any order, without risk of foreign key constraint violations. It is still possible to violate a N O TN U L L constraint on a foreign key column by deleting objects in the wrong order, e.g. if you delete the parent, but forget to delete the children.
The R e p l i c a t i o n M o d e determines how r e p l i c a t e ( ) will deal with conflicts with existing rows in the database:
R e p l i c a t i o n M o d e . I G N O R E : ignores the object when there is an existing database row with the same
identifier
R e p l i c a t i o n M o d e . O V E R W R I T E : overwrites any existing database row with the same identifier R e p l i c a t i o n M o d e . E X C E P T I O N : throws an exception if there is an existing database row with the same
identifier
R e p l i c a t i o n M o d e . L A T E S T _ V E R S I O N : overwrites the row if its version number is earlier than the version
number of the object, or ignore the object otherwise Usecases for this feature include reconciling data entered into different database instances, upgrading system configuration information during product upgrades, rolling back changes made during non-ACID transactions and more.
in
the
same
order the
corresponding
objects
were
saved
using
2. all entity updates 3. all collection deletions 4. all collection element deletions, updates and insertions 5. all collection insertions 6. all entity deletions in the same order the corresponding objects were deleted using
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
130/215
12/30/13
S e s s i o n . d e l e t e ( )
An exception is that objects using n a t i v eID generation are inserted when they are saved. Except when you explicitly f l u s h ( ) , there are absolutely no guarantees about when the S e s s i o n executes the JDBC calls, only the order in which they are executed. However, Hibernate does guarantee that the Q u e r y . l i s t ( . . )will never return stale or incorrect data. It is possible to change the default behavior so that flush occurs less frequently. The F l u s h M o d e class defines three different modes: only flush at commit time when the Hibernate T r a n s a c t i o n API is used, flush automatically using the explained routine, or never flush unless f l u s h ( )is called explicitly. The last mode is useful for long running units of work, where a S e s s i o nis kept open and disconnected for a long time (see Section 13.3.2, Extended session and automatic versioning).
s e s s=s f . o p e n S e s s i o n ( ) ; T r a n s a c t i o nt x=s e s s . b e g i n T r a n s a c t i o n ( ) ; s e s s . s e t F l u s h M o d e ( F l u s h M o d e . C O M M I T ) ;/ /a l l o wq u e r i e st or e t u r ns t a l es t a t e C a ti z i=( C a t )s e s s . l o a d ( C a t . c l a s s ,i d ) ; i z i . s e t N a m e ( i z n i z i ) ; / /m i g h tr e t u r ns t a l ed a t a s e s s . f i n d ( " f r o mC a ta sc a tl e f to u t e rj o i nc a t . k i t t e n sk i t t e n " ) ; / /c h a n g et oi z ii sn o tf l u s h e d ! . . . t x . c o m m i t ( ) ;/ /f l u s ho c c u r s s e s s . c l o s e ( ) ;
During flush, an exception might occur (e.g. if a DML operation violates a constraint). Since handling exceptions involves some understanding of Hibernate's transactional behavior, we discuss it in Chapter 13, Transactions and Concurrency.
p e r s i s t ( ) ,m e r g e ( ) ,s a v e O r U p d a t e ( ) ,d e l e t e ( ) ,l o c k ( ) ,r e f r e s h ( ) ,e v i c t ( ) ,r e p l i c a t e ( ) - there is
corresponding
cascade
Respectively,
cascade
be cascaded along an association, you must indicate that in the mapping document. For example:
< o n e t o o n en a m e = " p e r s o n "c a s c a d e = " p e r s i s t " / >
You can even use c a s c a d e = " a l l " to specify that all operations should be cascaded along the association. The default c a s c a d e = " n o n e "specifies that no operations are to be cascaded. In case you are using annotatons you probably have noticed the c a s c a d e attribute taking an array of
C a s c a d e T y p e as a value. The cascade concept in JPA is very is similar to the transitive persistence and
cascading of operations as described above, but with slightly different semantics and cascading types:
C a s c a d e T y p e . P E R S I S T : cascades the persist (create) operation to associated entities persist() is
entity is managed
C a s c a d e T y p e . R E M O V E : cascades the remove operation to associated entities if delete() is called C a s c a d e T y p e . R E F R E S H :cascades the refresh operation to associated entities if refresh() is called C a s c a d e T y p e . D E T A C H :cascades the detach operation to associated entities if detach() is called C a s c a d e T y p e . A L L : all of the above
Note
CascadeType.ALL also covers Hibernate specific operations like save-
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
131/215
12/30/13
A special cascade style, d e l e t e o r p h a n , applies only to one-to-many associations, and indicates that the
d e l e t e ( ) operation should be applied to any child object that is removed from the association. Using
a @ O n e T o M a n y collection or an associated entity is dereferenced from a @ O n e T o O n e association, this associated entity can be marked for deletion if o r p h a n R e m o v a lis set to true.
Recommendations: It does not usually make sense to enable cascade on a many-to-one or many-to-many association. In fact the @ M a n y T o O n e and @ M a n y T o M a n y don't even offer a o r p h a n R e m o v a l attribute. Cascading is often useful for one-to-one and one-to-many associations. If the child object's lifespan is bounded by the lifespan of the parent object, make it a life cycle object by specifying c a s c a d e = " a l l , d e l e t e o r p h a n " (@ O n e T o M a n y ( c a s c a d e = C a s c a d e T y p e . A L L ,o r p h a n R e m o v a l = t r u e ) ). Otherwise, you might not need cascade at all. But if you think that you will often be working with the parent and children together in the same transaction, and you want to save yourself some typing, consider using c a s c a d e = " p e r s i s t , m e r g e , s a v e u p d a t e " . Mapping an association (either a single valued association, or a collection) with c a s c a d e = " a l l " marks the association as a parent/child style relationship where save/update/delete of the parent results in save/update/delete of the child or children. Furthermore, a mere reference to a child from a persistent parent will result in save/update of the child. This metaphor is incomplete, however. A child which becomes unreferenced by its parent is not automatically deleted, except in the case of a one-to-many association mapped with c a s c a d e = " d e l e t e o r p h a n " . The precise semantics of cascading operations for a parent/child relationship are as follows: If a parent is passed to p e r s i s t ( ) , all children are passed to p e r s i s t ( ) If a parent is passed to m e r g e ( ) , all children are passed to m e r g e ( ) If a parent is passed to s a v e ( ) , u p d a t e ( ) or s a v e O r U p d a t e ( ) , all children are passed to
s a v e O r U p d a t e ( )
If a parent is deleted, all children are passed to d e l e t e ( ) If a child is dereferenced by a persistent parent, nothing special happens - the application should explicitly delete the child if necessary - unless c a s c a d e = " d e l e t e o r p h a n " , in which case the "orphaned" child is deleted. Finally, note that cascading of operations can be applied to an object graph at call time or at flush time. All operations, if enabled, are cascaded to associated entities reachable when the operation is executed. However, s a v e u p d a t e and d e l e t e o r p h a n are transitive for all associated entities reachable during flush of the S e s s i o n .
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
132/215
12/30/13
12.2. Read-only affect on property type 12.2.1. Simple properties 12.2.2. Unidirectional associations 12.2.3. Bidirectional associations
Important
Hibernate's treatment of read-only entities may differ from what you may have encountered elsewhere. Incorrect usage may cause unexpected results.
When an entity is read-only: Hibernate does not dirty-check the entity's simple properties or single-ended associations; Hibernate will not update simple properties or updatable single-ended associations; Hibernate will not update the version of the read-only entity if only simple properties or single-ended updatable associations are changed; In some ways, Hibernate treats read-only entities the same as entities that are not read-only: Hibernate cascades operations to associations as defined in the entity mapping. Hibernate updates the version if the entity has a collection with changes that dirties the entity; A read-only entity can be deleted. Even if an entity is not read-only, its collection association can be affected if it contains a read-only entity. For details about the affect of read-only entities on different property and association types, see Section 12.2, Read-only affect on property type. For details about how to make entities read-only, see Section 12.1, Making persistent entities readonly Hibernate does some optimizing for read-only entities: It saves execution time by not dirty-checking simple properties or single-ended associations. It saves memory by deleting database snapshots.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
133/215
12/30/13
To change the default behavior so Hibernate loads entity instances of mutable classes into the session and automatically makes them read-only, call:
S e s s i o n . s e t D e f a u l t R e a d O n l y (t r u e) ;
To change the default back so entities loaded by Hibernate are not made read-only, call:
S e s s i o n . s e t D e f a u l t R e a d O n l y (f a l s e) ;
If Session.isDefaultReadOnly() returns true, entities loaded by the following are automatically made read-only: Session.load() Session.get() Session.merge() executing, scrolling, or iterating HQL queries and criteria; to override this setting for a particular HQL query or criteria see Section 12.1.3, Loading read-only entities from an HQL query/criteria Changing this default has no effect on: persistent entities already in the session when the default was changed persistent entities that are refreshed via Session.refresh(); a refreshed persistent entity will only be read-only if it was read-only before refreshing persistent entities added by the application Session.update() Session.saveOrUpdate() via Session.persist(), Session.save(), and
If Session.isDefaultReadOnly() returns false (the default) when an HQL query or criteria executes, then entities and proxies of mutable classes loaded by the query will not be read-only. You can override this behavior so that entities and proxies loaded by an HQL query or criteria are automatically made read-only. For an HQL query, call:
Q u e r y . s e t R e a d O n l y (t r u e) ;
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
134/215
12/30/13
Q u e r y . s e t R e a d O n l y (
must
be
called
before
Q u e r y . l i s t ( ) ,
Q u e r y . u n i q u e R e s u l t ( ) ,
Q u e r y . s c r o l l ( ) , or Q u e r y . i t e r a t e ( )
Entities and proxies that exist in the session before being returned by an HQL query or criteria are not affected. Uninitialized persistent collections returned by the query are not affected. Later, when the collection is initialized, entities loaded into the session will be read-only if Session.isDefaultReadOnly() returns true. Using Q u e r y . s e t R e a d O n l y ( t r u e ) or C r i t e r i a . s e t R e a d O n l y ( t r u e ) works well when a single HQL query or criteria loads all the entities and intializes all the proxies and collections that the application needs to be read-only. When it is not possible to load and initialize all necessary entities in a single query or criteria, you can temporarily change the session default to load entities as read-only before the query is executed. Then you can explicitly initialize proxies and collections before restoring the session default.
S e s s i o ns e s s i o n=f a c t o r y . o p e n S e s s i o n ( ) ; T r a n s a c t i o nt x=s e s s i o n . b e g i n T r a n s a c t i o n ( ) ; s e t D e f a u l t R e a d O n l y (t r u e) ; C o n t r a c tc o n t r a c t= (C o n t r a c t)s e s s i o n . c r e a t e Q u e r y ( " f r o mC o n t r a c tw h e r ec u s t o m e r N a m e=' S h e r m a n ' ") . u n i q u e R e s u l t ( ) ; H i b e r n a t e . i n i t i a l i z e (c o n t r a c t . g e t P l a n ( )) ; H i b e r n a t e . i n i t i a l i z e (c o n t r a c t . g e t V a r i a t i o n s ( )) ; H i b e r n a t e . i n i t i a l i z e (c o n t r a c t . g e t N o t e s ( )) ; s e t D e f a u l t R e a d O n l y (f a l s e) ; . . . t x . c o m m i t ( ) ; s e s s i o n . c l o s e ( ) ;
If Session.isDefaultReadOnly() returns true, then you can use Query.setReadOnly( false ) and Criteria.setReadOnly( false ) to override this session setting and load entities that are not read-only.
Important
When a read-only entity or proxy is changed so it is no longer read-only, Hibernate assumes that the current state of the read-only entity is consistent with its database representation. If this is not true, then any non-flushed changes made before or while the entity was read-only, will be ignored.
To throw away non-flushed changes and make the persistent entity consistent with its database representation, call:
s e s s i o n . r e f r e s h (e n t i t y) ;
To flush changes made before or while the entity was read-only and make the database representation consistent with the current state of the persistent entity:
/ /e v i c tt h er e a d o n l ye n t i t ys oi ti sd e t a c h e d s e s s i o n . e v i c t (e n t i t y) ; / /m a k et h ed e t a c h e de n t i t y( w i t ht h en o n f l u s h e dc h a n g e s )p e r s i s t e n t s e s s i o n . u p d a t e (e n t i t y) ; / /n o we n t i t yi sn ol o n g e rr e a d o n l ya n di t sc h a n g e sc a nb ef l u s h e d s . f l u s h ( ) ;
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
135/215
12/30/13
Table 12.1. Affect of read-only entity on property types Property/Association Type Simple (Section 12.2.1, Simple properties) Unidirectional one-to-one Unidirectional many-to-one no* Changes flushed to DB? no*
(Section 12.2.2.1, Unidirectional one-to-one and many- no* to-one) Unidirectional one-to-many Unidirectional many-to-many (Section 12.2.2.2, many-to-many) Unidirectional one-to-many and yes yes
Bidirectional one-to-one (Section 12.2.3.1, Bidirectional one-to-one) Bidirectional one-to-many/many-to-one inverse collection non-inverse collection only added/removed entities that are not read-only* only if the owning entity is not read-only*
(Section 12.2.3.2, Bidirectional one-to-many/many-to- yes one) Bidirectional many-to-many (Section 12.2.3.3, Bidirectional many-to-many) yes
* Behavior is different when the entity having the property/association is read-only, compared to when it is not read-only.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
136/215
12/30/13
only.
If you change a read-only entity's reference to a unidirectional single-ended association to null, or to refer to a different entity, that change will not be flushed to the database.
Note
If an entity is of an immutable class, then its references to unidirectional single-ended associations must be assigned when that entity is first created. Because the entity is automatically made read-only, these references can not be updated.
If automatic versioning is used, Hibernate will not increment the version due to local changes to unidirectional single-ended associations. In the following examples, Contract has a unidirectional many-to-one association with Plan. Contract cascades save and update operations to the association. The following shows that changing a read-only entity's many-to-one association reference to null has no effect on the entity's database representation.
/ /g e tac o n t r a c tw i t ha ne x i s t i n gp l a n ; / /m a k et h ec o n t r a c tr e a d o n l ya n ds e ti t sp l a nt on u l l t x=s e s s i o n . b e g i n T r a n s a c t i o n ( ) ; C o n t r a c tc o n t r a c t=(C o n t r a c t)s e s s i o n . g e t (C o n t r a c t . c l a s s ,c o n t r a c t I d) ; s e s s i o n . s e t R e a d O n l y (c o n t r a c t ,t r u e) ; c o n t r a c t . s e t P l a n (n u l l) ; t x . c o m m i t ( ) ; / /g e tt h es a m ec o n t r a c t t x=s e s s i o n . b e g i n T r a n s a c t i o n ( ) ; c o n t r a c t=(C o n t r a c t)s e s s i o n . g e t (C o n t r a c t . c l a s s ,c o n t r a c t I d) ; / /c o n t r a c t . g e t P l a n ( )s t i l lr e f e r st ot h eo r i g i n a lp l a n ; t x . c o m m i t ( ) ; s e s s i o n . c l o s e ( ) ;
The following shows that, even though an update to a read-only entity's many-to-one association has no affect on the entity's database representation, flush still cascades the save-update operation to the locally changed association.
/ /g e tac o n t r a c tw i t ha ne x i s t i n gp l a n ; / /m a k et h ec o n t r a c tr e a d o n l ya n dc h a n g et oan e wp l a n t x=s e s s i o n . b e g i n T r a n s a c t i o n ( ) ; C o n t r a c tc o n t r a c t=(C o n t r a c t)s e s s i o n . g e t (C o n t r a c t . c l a s s ,c o n t r a c t I d) ; s e s s i o n . s e t R e a d O n l y (c o n t r a c t ,t r u e) ; P l a nn e w P l a n=n e wP l a n (" n e wp l a n " c o n t r a c t . s e t P l a n (n e w P l a n ) ; t x . c o m m i t ( ) ; / /g e tt h es a m ec o n t r a c t t x=s e s s i o n . b e g i n T r a n s a c t i o n ( ) ; c o n t r a c t=(C o n t r a c t)s e s s i o n . g e t (C o n t r a c t . c l a s s ,c o n t r a c t I d) ; n e w P l a n=(C o n t r a c t)s e s s i o n . g e t (P l a n . c l a s s ,n e w P l a n . g e t I d ( )) ; / /c o n t r a c t . g e t P l a n ( )s t i l lr e f e r st ot h eo r i g i n a lp l a n ; / /n e w P l a ni sn o n n u l lb e c a u s ei tw a sp e r s i s t e dw h e n / /t h ep r e v i o u st r a n s a c t i o nw a sc o m m i t t e d ; t x . c o m m i t ( ) ; s e s s i o n . c l o s e ( ) ;
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
137/215
12/30/13
Note
If an entity is of an immutable class, and it owns a bidirectional one-to-one association, then its refere nce must be assigned when that entity is first created. Because the entity is automatically made read-only, these references cannot be updated.
When the owner is not read-only, Hibernate treats an association with a read-only entity the same as when the association is with an entity that is not read-only.
13.2. Database transaction demarcation 13.2.1. 13.2.2. 13.2.3. 13.2.4. Non-managed environment Using JTA Exception handling Transaction timeout
13.3. Optimistic concurrency control 13.3.1. Application version checking 13.3.2. Extended session and automatic versioning 13.3.3. Detached objects and automatic versioning 13.3.4. Customizing automatic versioning 13.4. Pessimistic locking 13.5. Connection release modes The most important point about Hibernate and concurrency control is that it is easy to understand. Hibernate directly uses JDBC connections and JTA resources without adding any additional locking
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
138/215
12/30/13
and this API are discussed later in this chapter. The discussion of concurrency control in Hibernate begins with the granularity of C o n f i g u r a t i o n ,
S e s s i o n F a c t o r y , and S e s s i o n , as well as database transactions and long conversations.
In order to reduce lock contention in the database, a database transaction has to be as short as possible. Long database transactions will prevent your application from scaling to a highly concurrent load. It is not recommended that you hold a database transaction open during user think time until the unit of work is complete. What is the scope of a unit of work? Can a single Hibernate S e s s i o n span several database transactions, or is this a one-to-one relationship of scopes? When should you open and close a S e s s i o n and how do you demarcate the database transaction boundaries? These questions are addressed in the following sections.
transaction. This has to be configured for either resource-local or JTA environments, see Section 2.2, Contextual sessions. You can extend the scope of a S e s s i o n and database transaction until the "view has been rendered". This is especially useful in servlet applications that utilize a separate rendering phase after the request has been processed. Extending the database transaction until view rendering, is achieved by
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
139/215
12/30/13
JVM Identity
f o o = = b a r
For objects attached to a particular S e s s i o n (i.e., in the scope of a S e s s i o n ), the two notions are equivalent and JVM identity for database identity is guaranteed by Hibernate. While the application might concurrently access the "same" (persistent identity) business object in two different sessions, the two instances will actually be "different" (JVM identity). Conflicts are resolved using an optimistic approach and automatic versioning at flush/commit time. This approach leaves Hibernate and the database to worry about concurrency. It also provides the best scalability, since guaranteeing identity in single-threaded units of work means that it does not need expensive locking or other means of synchronization. The application does not need to synchronize on any business object, as long as it maintains a single thread per S e s s i o n . Within a S e s s i o n the application can safely use = =to compare objects. However, an application that uses = =outside of a S e s s i o nmight produce unexpected results. This might occur even in some unexpected places. For example, if you put two detached instances into the same S e t , both might have the same database identity (i.e., they represent the same row). JVM identity,
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
140/215
12/30/13
synchronizing access to your Http session. Otherwise, a user that clicks reload fast enough can use the same S e s s i o nin two concurrently running threads. An exception thrown by Hibernate means you have to rollback your database transaction and close the S e s s i o n immediately (this is discussed in more detail later in the chapter). If your S e s s i o n is bound to the application, you have to stop the application. Rolling back the database transaction does not put your business objects back into the state they were at the start of the transaction. This means that the database state and the business objects will be out of sync. Usually this is not a problem, because exceptions are not recoverable and you will have to start over after rollback anyway. The S e s s i o ncaches every object that is in a persistent state (watched and checked for dirty state by Hibernate). If you keep it open for a long time or simply load too much data, it will grow endlessly until you get an OutOfMemoryException. One solution is to call c l e a r ( ) and e v i c t ( ) to manage the
S e s s i o ncache, but you should consider a Stored Procedure if you need mass data operations. Some
solutions are shown in Chapter 15, Batch processing. Keeping a S e s s i o n open for the duration of a user session also means a higher probability of stale data.
12/30/13
You do not have to f l u s h ( ) the S e s s i o n explicitly: the call to c o m m i t ( ) automatically triggers the synchronization depending on the Section 11.10, Flushing the Session for the session. A call to c l o s e ( ) marks the end of a session. The main implication of c l o s e ( ) is that the JDBC connection will be relinquished by the session. This Java code is portable and runs in both non-managed and JTA environments. As outlined earlier, a much more flexible solution is Hibernate's built-in "current session" context management:
/ /N o n m a n a g e de n v i r o n m e n ti d i o mw i t hg e t C u r r e n t S e s s i o n ( ) t r y{ f a c t o r y . g e t C u r r e n t S e s s i o n ( ) . b e g i n T r a n s a c t i o n ( ) ; / /d os o m ew o r k . . . f a c t o r y . g e t C u r r e n t S e s s i o n ( ) . g e t T r a n s a c t i o n ( ) . c o m m i t ( ) ; } c a t c h( R u n t i m e E x c e p t i o ne ){ f a c t o r y . g e t C u r r e n t S e s s i o n ( ) . g e t T r a n s a c t i o n ( ) . r o l l b a c k ( ) ; t h r o we ;/ /o rd i s p l a ye r r o rm e s s a g e }
You will not see these code snippets in a regular application; fatal (system) exceptions should always be caught at the "top". In other words, the code that executes Hibernate calls in the persistence layer, and the code that handles R u n t i m e E x c e p t i o n (and usually can only clean up and exit), are in different layers. The current context management by Hibernate can significantly simplify this design by accessing aS e s s i o n F a c t o r y . Exception handling is discussed later in this chapter. You should select o r g . h i b e r n a t e . t r a n s a c t i o n . J D B C T r a n s a c t i o n F a c t o r y , which is the default, and for the second example select " t h r e a d "as your h i b e r n a t e . c u r r e n t _ s e s s i o n _ c o n t e x t _ c l a s s .
If you want to use a transaction-bound S e s s i o n , that is, the g e t C u r r e n t S e s s i o n ( ) functionality for easy context propagation, use the JTA U s e r T r a n s a c t i o nAPI directly:
/ /B M Ti d i o mw i t hg e t C u r r e n t S e s s i o n ( ) t r y{ U s e r T r a n s a c t i o nt x=( U s e r T r a n s a c t i o n ) n e wI n i t i a l C o n t e x t ( ) . l o o k u p ( " j a v a : c o m p / U s e r T r a n s a c t i o n " ) ; t x . b e g i n ( ) ;
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
142/215
12/30/13
With CMT, transaction demarcation is completed in session bean deployment descriptors, not programmatically. The code is reduced to:
/ /C M Ti d i o m S e s s i o ns e s s=f a c t o r y . g e t C u r r e n t S e s s i o n ( ) ; / /d os o m ew o r k . . .
In a CMT/EJB, even rollback happens automatically. An unhandled R u n t i m e E x c e p t i o n thrown by a session bean method tells the container to set the global transaction to rollback. You do not need to use the Hibernate T r a n s a c t i o n API at all with BMT or CMT, and you get automatic propagation of the "current" Session bound to the transaction. When configuring Hibernate's if transaction you use Ensure factory, directly that choose (BMT), and your
o r g . h i b e r n a t e . t r a n s a c t i o n . J T A T r a n s a c t i o n F a c t o r y h i b e r n a t e . t r a n s a c t i o n . m a n a g e r _ l o o k u p _ c l a s s .
JTA
o r g . h i b e r n a t e . t r a n s a c t i o n . C M T T r a n s a c t i o n F a c t o r y in a CMT session bean. Remember to also set h i b e r n a t e . c u r r e n t _ s e s s i o n _ c o n t e x t _ c l a s sis either unset (backwards compatibility), or is set to " j t a " .
The g e t C u r r e n t S e s s i o n ( )operation has one downside in a JTA environment. There is one caveat to the use of a f t e r _ s t a t e m e n t connection release mode, which is then used by default. Due to a limitation of the JTA spec, it is not possible for Hibernate to automatically clean up any unclosed S c r o l l a b l e R e s u l t s or I t e r a t o r instances returned by s c r o l l ( ) or i t e r a t e ( ) . You must release the underlying database cursor by calling S c r o l l a b l e R e s u l t s . c l o s e ( ) or H i b e r n a t e . c l o s e ( I t e r a t o r ) explicitly from a f i n a l l y block. Most applications can easily avoid using s c r o l l ( )or i t e r a t e ( )from the JTA or CMT code.)
the S e s s i o n F a c t o r y . By default, the S Q L E x c e p t i o n C o n v e r t e r is defined by the configured dialect. However, it is also possible to plug in a custom implementation. See the javadocs for the S Q L E x c e p t i o n C o n v e r t e r F a c t o r yclass for details. The standard J D B C E x c e p t i o nsubtypes are:
J D B C C o n n e c t i o n E x c e p t i o n : indicates an error with the underlying JDBC communication. S Q L G r a m m a r E x c e p t i o n : indicates a grammar or syntax problem with the issued SQL. C o n s t r a i n t V i o l a t i o n E x c e p t i o n : indicates some form of integrity constraint violation. L o c k A c q u i s i t i o n E x c e p t i o n : indicates an error acquiring a lock level necessary to perform the
requested operation.
G e n e r i c J D B C E x c e p t i o n : a generic exception which did not fall into any of the other categories.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
143/215
12/30/13
The v e r s i o n property is mapped using < v e r s i o n > , and Hibernate will automatically increment it during flush if the entity is dirty. If you are operating in a low-data-concurrency environment, and do not require version checking, you can use this approach and skip the version check. In this case, last commit wins is the default strategy for long conversations. Be aware that this might confuse the users of the application, as they might experience lost updates without error messages or a chance to merge conflicting changes. Manual version checking is only feasible in trivial circumstances and not practical for most applications. Often not only single instances, but complete graphs of modified objects, have to be checked. Hibernate offers automatic version checking with either an extended S e s s i o n or detached instances as the design paradigm.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
144/215
12/30/13
to lock any data that you are updating. Usually you would set F l u s h M o d e . M A N U A L on an extended
S e s s i o n , so that only the last database transaction cycle is allowed to actually persist all modifications
made in this conversation. Only this last database transaction will include the f l u s h ( ) operation, and then c l o s e ( )the session to end the conversation. This pattern is problematic if the S e s s i o n is too big to be stored during user think time (for example, an
H t t p S e s s i o n should be kept as small as possible). As the S e s s i o n is also the first-level cache and
contains all loaded objects, we can probably use this strategy only for a few request/response cycles. Use a S e s s i o nonly for a single conversation as it will soon have stale data.
Note
Earlier versions of Hibernate required explicit disconnection and reconnection of a S e s s i o n . These methods are deprecated, as beginning and ending a transaction has the same effect.
Keep the disconnected S e s s i o n close to the persistence layer. Use an EJB stateful session bean to hold the S e s s i o n in a three-tier environment. Do not transfer it to the web layer, or even serialize it to a separate tier, to store it in the H t t p S e s s i o n . The extended session pattern, or session-per-conversation , is more difficult to implement with automatic current session context management. You need to supply your own implementation of the
C u r r e n t S e s s i o n C o n t e x tfor this. See the Hibernate Wiki for examples.
then
reattaches
them
using
Again, Hibernate will check instance versions during flush, throwing an exception if conflicting updates occurred. You can also call l o c k ( ) instead of u p d a t e ( ) , and use L o c k M o d e . R E A D (performing a version check and bypassing all caches) if you are sure that the object has not been modified.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
145/215
12/30/13
can
be
acquired
upon
explicit
user
request
using
S E L E C T. . .F O RU P D A T EN O W A I Tunder Oracle. L o c k M o d e . R E A D is acquired automatically when Hibernate reads data under Repeatable Read or
out in this lock mode. The "explicit user request" is expressed in one of the following ways: A call to S e s s i o n . l o a d ( ) , specifying a L o c k M o d e . A call to S e s s i o n . l o c k ( ) . A call to Q u e r y . s e t L o c k M o d e ( ) . If S e s s i o n . l o a d ( ) is called with U P G R A D E or U P G R A D E _ N O W A I T , and the requested object was not yet loaded by the session, the object is loaded using S E L E C T . . . F O R U P D A T E . If l o a d ( ) is called for an object that is already loaded with a less restrictive lock than the one requested, Hibernate calls l o c k ( ) for that object.
S e s s i o n . l o c k ( ) performs a version number check if the specified lock mode is R E A D , U P G R A D E or U P G R A D E _ N O W A I T . In the case of U P G R A D Eor U P G R A D E _ N O W A I T ,S E L E C T. . .F O RU P D A T Eis used.
If the requested lock mode is not supported by the database, Hibernate uses an appropriate alternate mode instead of throwing an exception. This ensures that applications are portable.
it first needs to perform some JDBC access and maintains that connection until the session is closed.
A F T E R _ T R A N S A C T I O N : releases connections after a o r g . h i b e r n a t e . T r a n s a c t i o nhas been completed. A F T E R _ S T A T E M E N T (also
statement execution. This aggressive releasing is skipped if that statement leaves open resources associated with the given session. Currently the only situation where this occurs is through the use of o r g . h i b e r n a t e . S c r o l l a b l e R e s u l t s . The configuration parameter h i b e r n a t e . c o n n e c t i o n . r e l e a s e _ m o d eis used to specify which release mode to use. The possible values are as follows:
a u t o
(the
default):
this
choice
delegates
to
the
release
mode
returned method.
by
the For
o r g . h i b e r n a t e . t r a n s a c t i o n . T r a n s a c t i o n F a c t o r y . g e t D e f a u l t R e l e a s e M o d e ( )
JTATransactionFactory, this returns ConnectionReleaseMode.AFTER_STATEMENT; for JDBCTransactionFactory, this returns ConnectionReleaseMode.AFTER_TRANSACTION. Do not change this default behavior as failures due to the value of this setting tend to indicate bugs and/or invalid assumptions in user code.
o n _ c l o s e : uses ConnectionReleaseMode.ON_CLOSE. This setting is left for backwards compatibility,
used in JTA environments. Also note that with ConnectionReleaseMode.AFTER_TRANSACTION, if a session is considered to be in auto-commit mode, connections will be released as if the release mode were AFTER_STATEMENT.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
146/215
12/30/13
configured
not, the release mode is reset to ConnectionReleaseMode.AFTER_TRANSACTION. This setting is only safe in environments where we can either re-acquire the same underlying JDBC connection each time you make a call into C o n n e c t i o n P r o v i d e r . g e t C o n n e c t i o n ( ) or in auto-commit environments where it does not matter if we re-establish the same connection.
14.1. Interceptors
The I n t e r c e p t o r interface provides callbacks from the session to the application, allowing the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. One possible use for this is to track auditing information. For example, the following I n t e r c e p t o r automatically sets the c r e a t e T i m e s t a m p when an A u d i t a b l e is created and updates the
l a s t U p d a t e T i m e s t a m pproperty when an A u d i t a b l eis updated.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
147/215
12/30/13
}
There are two kinds of inteceptors: S e s s i o n -scoped and S e s s i o n F a c t o r y -scoped. AS e s s i o n -scoped interceptor is specified when a session is opened.
S e s s i o ns e s s i o n=s f . w i t h O p t i o n s (n e wA u d i t I n t e r c e p t o r ( )) . o p e n S e s s i o n ( ) ;
interceptor will be applied to all sessions opened from that S e s s i o n F a c t o r y . S e s s i o n F a c t o r y -scoped interceptors must be thread safe. Ensure that you do not store session-specific states, since multiple sessions will use this interceptor potentially concurrently.
n e wC o n f i g u r a t i o n ( ) . s e t I n t e r c e p t o r (n e wA u d i t I n t e r c e p t o r ( )) ;
Note
See the Hibernate Dev eloper Guide for information on registering custom event listeners.
The listeners should be considered stateless; they are shared between requests, and should not save any state as instance variables. A custom listener implements 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-thebox as these are declared non-final for this purpose). Here is an example of a custom load event listener:
p u b l i cc l a s sM y L o a d L i s t e n e ri m p l e m e n t sL o a d E v e n t L i s t e n e r{ / /t h i si st h es i n g l em e t h o dd e f i n e db yt h eL o a d E v e n t L i s t e n e ri n t e r f a c e p u b l i cv o i do n L o a d ( L o a d E v e n te v e n t ,L o a d E v e n t L i s t e n e r . L o a d T y p el o a d T y p e ) t h r o w sH i b e r n a t e E x c e p t i o n{ i f(! M y S e c u r i t y . i s A u t h o r i z e d (e v e n t . g e t E n t i t y C l a s s N a m e ( ) ,e v e n t . g e t E n t i t y I d ( ))){ t h r o wM y S e c u r i t y E x c e p t i o n ( " U n a u t h o r i z e da c c e s s " ) ; } } }
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
148/215
12/30/13
You must also decide how to configure your JACC provider. One option is to tell Hibernate what permissions to bind to what roles and have it configure the JACC provider. This would be done in the h i b e r n a t e . c f g . x m lfile.
< g r a n tr o l e = " a d m i n "e n t i t y n a m e = " U s e r "a c t i o n s = " i n s e r t , u p d a t e , r e a d " / > < g r a n tr o l e = " s u "e n t i t y n a m e = " U s e r "a c t i o n s = " * " / >
This would fall over with an O u t O f M e m o r y E x c e p t i o n somewhere around the 50,000th row. That is because Hibernate caches all the newly inserted C u s t o m e r instances in the session-level cache. In this chapter we will show you how to avoid this problem. If you are undertaking batch processing you will need to enable the use of JDBC batching. This is absolutely essential if you want to achieve optimal performance. Set the JDBC batch size to a reasonable number (10-50, for example):
h i b e r n a t e . j d b c . b a t c h _ s i z e2 0
Hibernate disables insert batching at the JDBC level transparently if you use an i d e n t i t y identifier generator. You can also do this kind of work in a process where interaction with the second-level cache is completely disabled:
h i b e r n a t e . c a c h e . u s e _ s e c o n d _ l e v e l _ c a c h ef a l s e
However, this is not absolutely necessary, since we can explicitly set the C a c h e M o d e to disable interaction with the second-level cache.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
149/215
12/30/13
In this code example, the C u s t o m e rinstances returned by the query are immediately detached. They are never associated with any persistence context. The i n s e r t ( ) , u p d a t e ( ) and d e l e t e ( ) operations defined by the S t a t e l e s s S e s s i o n interface are considered to be direct database row-level operations. They result in the immediate execution of a SQL I N S E R T ,U P D A T E or D E L E T E respectively. They have different semantics to the s a v e ( ) , s a v e O r U p d a t e ( ) and d e l e t e ( )operations defined by the S e s s i o ninterface.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
150/215
12/30/13
SQL-style DML statement execution that is performed through the Hibernate Query Language (Chapter 16, HQL: The Hibernate Query Language). The pseudo-syntax for
U P D A T E
and
D E L E T E
statements
is:
(U P D A T E|D E L E T E)F R O M ?E n t i t y N a m e( W H E R Ew h e r e _ c o n d i t i o n s ) ? .
Some points to note: In the from-clause, the FROM keyword is optional There can only be a single entity named in the from-clause. It can, however, be aliased. If the entity name is aliased, then any property references must be qualified using that alias. If the entity name is not aliased, then it is illegal for any property references to be qualified. No Section 16.4, Forms of join syntax, either implicit or explicit, can be specified in a bulk HQL query. Sub-queries can be used in the where-clause, where the subqueries themselves may contain joins. The where-clause is also optional. As an example, to execute an HQL U P D A T E , use the Q u e r y . e x e c u t e U p d a t e ( ) method. The method is named for those familiar with JDBC's P r e p a r e d S t a t e m e n t . e x e c u t e U p d a t e ( ) :
S e s s i o ns e s s i o n=s e s s i o n F a c t o r y . o p e n S e s s i o n ( ) ; T r a n s a c t i o nt x=s e s s i o n . b e g i n T r a n s a c t i o n ( ) ; S t r i n gh q l U p d a t e=" u p d a t eC u s t o m e rcs e tc . n a m e=: n e w N a m ew h e r ec . n a m e=: o l d N a m e " ; / /o rS t r i n gh q l U p d a t e=" u p d a t eC u s t o m e rs e tn a m e=: n e w N a m ew h e r en a m e=: o l d N a m e " ; i n tu p d a t e d E n t i t i e s=s . c r e a t e Q u e r y (h q l U p d a t e) . s e t S t r i n g (" n e w N a m e " ,n e w N a m e) . s e t S t r i n g (" o l d N a m e " ,o l d N a m e) . e x e c u t e U p d a t e ( ) ; t x . c o m m i t ( ) ; s e s s i o n . c l o s e ( ) ;
In keeping with the EJB3 specification, HQL U P D A T E statements, by default, do not effect the Section 5.1.3.1, Version number or the Section 5.1.3.2, Timestamp property values for the affected entities. However, you can force Hibernate to reset the v e r s i o n or t i m e s t a m p property values through the use of a v e r s i o n e d u p d a t e . This is achieved by adding the V E R S I O N E D keyword after the U P D A T E keyword.
S e s s i o ns e s s i o n=s e s s i o n F a c t o r y . o p e n S e s s i o n ( ) ; T r a n s a c t i o nt x=s e s s i o n . b e g i n T r a n s a c t i o n ( ) ; S t r i n gh q l V e r s i o n e d U p d a t e=" u p d a t ev e r s i o n e dC u s t o m e rs e tn a m e=: n e w N a m ew h e r en a m e=: o l d N a m e " ; i n tu p d a t e d E n t i t i e s=s . c r e a t e Q u e r y (h q l U p d a t e) . s e t S t r i n g (" n e w N a m e " ,n e w N a m e) . s e t S t r i n g (" o l d N a m e " ,o l d N a m e) . e x e c u t e U p d a t e ( ) ; t x . c o m m i t ( ) ; s e s s i o n . c l o s e ( ) ;
The i n t value returned by the Q u e r y . e x e c u t e U p d a t e ( )method indicates the number of entities effected by the operation. This may or may not correlate to the number of rows effected in the database. An HQL bulk operation might result in multiple actual SQL statements being executed (for joined-subclass, for example). The returned number indicates the number of actual entities affected by the statement. Going back to the example of joined-subclass, a delete against one of the subclasses may actually result in deletes against not just the table to which that subclass is mapped, but also the "root" table and potentially joined-subclass tables further down the inheritance hierarchy. The pseudo-syntax for
I N S E R T
statements
is:
Only the INSERT INTO ... SELECT ... form is supported; not the INSERT INTO ... VALUES ... form. The properties_list is analogous to the c o l u m n s p e c i f i c a t i o n in the SQL I N S E R T statement. For entities involved in mapped inheritance, only properties directly defined on that given class-level can be used in the properties_list. Superclass properties are not allowed and subclass properties do not make sense. In other words, I N S E R Tstatements are inherently non-polymorphic. select_statement can be any valid HQL select query, with the caveat that the return types must match the types expected by the insert. Currently, this is checked during query compilation rather than allowing the check to relegate to the database. This might, however, cause problems between Hibernate T y p e s which are equivalent as opposed to equal. This might cause issues with mismatches between a property defined as a o r g . h i b e r n a t e . t y p e . D a t e T y p e and a property defined as a
o r g . h i b e r n a t e . t y p e . T i m e s t a m p T y p e , even though the database might not make a distinction or
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
151/215
12/30/13
The
most
notable
exception
here
is
selectable way to get its values. For properties mapped as either v e r s i o n or t i m e s t a m p , the insert statement gives you two options. You can either specify the property in the properties_list, in which case its value is taken from the corresponding select expressions, or omit it from the properties_list, in which case the s e e d v a l u e defined by the o r g . h i b e r n a t e . t y p e . V e r s i o n T y p eis used. The following is an example of an HQL I N S E R Tstatement execution:
S e s s i o ns e s s i o n=s e s s i o n F a c t o r y . o p e n S e s s i o n ( ) ; T r a n s a c t i o nt x=s e s s i o n . b e g i n T r a n s a c t i o n ( ) ; S t r i n gh q l I n s e r t=" i n s e r ti n t oD e l i n q u e n t A c c o u n t( i d ,n a m e )s e l e c tc . i d ,c . n a m ef r o mC u s t o m e rcw h e r e. . . " ; i n tc r e a t e d E n t i t i e s=s . c r e a t e Q u e r y (h q l I n s e r t) . e x e c u t e U p d a t e ( ) ; t x . c o m m i t ( ) ; s e s s i o n . c l o s e ( ) ;
16.18. Row value constructor syntax Hibernate uses a powerful query language (HQL) that is similar in appearance to SQL. Compared with SQL, however, HQL is fully object-oriented and understands notions like inheritance, polymorphism and association.
This manual uses lowercase HQL keywords. Some users find queries with uppercase keywords more readable, but this convention is unsuitable for queries embedded in Java code.
This returns all instances of the class e g . C a t . You do not usually need to qualify the class name, since
a u t o i m p o r tis the default. For example: f r o mC a t
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
152/215
12/30/13
This query assigns the alias c a t to C a t instances, so you can use that alias later in the query. The a s keyword is optional. You could also write:
f r o mC a tc a t
It is good practice to name query aliases using an initial lowercase as this is consistent with Java naming standards for local variables (e.g. d o m e s t i c C a t ).
You may supply extra join conditions using the HQL w i t hkeyword.
f r o mC a ta sc a t l e f tj o i nc a t . k i t t e n sa sk i t t e n w i t hk i t t e n . b o d y W e i g h t>1 0 . 0
A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections. See Section 20.1, Fetching strategies for more information.
f r o mC a ta sc a t i n n e rj o i nf e t c hc a t . m a t e l e f tj o i nf e t c hc a t . k i t t e n s
A fetch join does not usually need to assign an alias, because the associated objects should not be used in the w h e r e clause (or any other clause). The associated objects are also not returned directly in the query results. Instead, they may be accessed via the parent object. The only reason you might need an alias is if you are recursively join fetching a further collection:
f r o mC a ta sc a t i n n e rj o i nf e t c hc a t . m a t e l e f tj o i nf e t c hc a t . k i t t e n sc h i l d l e f tj o i nf e t c hc h i l d . k i t t e n s
The f e t c h construct cannot be used in queries called using i t e r a t e ( ) (though s c r o l l ( ) can be used).
F e t c hshould not be used together with s e t M a x R e s u l t s ( ) or s e t F i r s t R e s u l t ( ) , as these operations are
based on the result rows which usually contain duplicates for eager collection fetching, hence, the number of rows is not what you would expect. F e t c h should also not be used together with impromptu
w i t h condition. It is possible to create a cartesian product by join fetching more than one collection in a
query, so take care in this case. Join fetching multiple collection roles can produce unexpected results for bag mappings, so user discretion is advised when formulating queries in this case. Finally, note that
f u l lj o i nf e t c hand r i g h tj o i nf e t c hare not meaningful.
If you are using property-level lazy fetching (with bytecode instrumentation), it is possible to force Hibernate to fetch the lazy properties in the first query immediately using f e t c ha l lp r o p e r t i e s .
f r o mD o c u m e n tf e t c ha l lp r o p e r t i e so r d e rb yn a m e
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
153/215
12/30/13
Important
Please note that, starting in version 3.2.2, this has changed significantly. In previous versions, i dalways referred to the identifier property regardless of its actual name. A ramification of that decision was that non-identifier properties named i dcould never be referenced in Hibernate queries.
The query will select m a t e s of other C a t s. You can express this query more compactly as:
s e l e c tc a t . m a t ef r o mC a tc a t
Queries can return properties of any value type including properties of component type:
s e l e c tc a t . n a m ef r o mD o m e s t i c C a tc a t w h e r ec a t . n a m el i k e' f r i % ' s e l e c tc u s t . n a m e . f i r s t N a m ef r o mC u s t o m e ra sc u s t
Or as a L i s t :
s e l e c tn e wl i s t ( m o t h e r ,o f f s p r ,m a t e . n a m e ) f r o mD o m e s t i c C a ta sm o t h e r i n n e rj o i nm o t h e r . m a t ea sm a t e l e f to u t e rj o i nm o t h e r . k i t t e n sa so f f s p r
Or - assuming that the class F a m i l yhas an appropriate constructor - as an actual typesafe Java object:
s e l e c tn e wF a m i l y ( m o t h e r ,m a t e ,o f f s p r ) f r o mD o m e s t i c C a ta sm o t h e r j o i nm o t h e r . m a t ea sm a t e l e f tj o i nm o t h e r . k i t t e n sa so f f s p r
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
154/215
12/30/13
You can use arithmetic operators, concatenation, and recognized SQL functions in the select clause:
s e l e c tc a t . w e i g h t+s u m ( k i t t e n . w e i g h t ) f r o mC a tc a t j o i nc a t . k i t t e n sk i t t e n g r o u pb yc a t . i d ,c a t . w e i g h t s e l e c tf i r s t N a m e | | '' | | i n i t i a l | | '' | | u p p e r ( l a s t N a m e )f r o mP e r s o n
The d i s t i n c tand a l lkeywords can be used and have the same semantics as in SQL.
s e l e c td i s t i n c tc a t . n a m ef r o mC a tc a t s e l e c tc o u n t ( d i s t i n c tc a t . n a m e ) ,c o u n t ( c a t )f r o mC a tc a t
returns instances not only of C a t , but also of subclasses like D o m e s t i c C a t . Hibernate queries can name any Java class or interface in the f r o m clause. The query will return instances of all persistent classes that extend that class or implement the interface. The following query would return all persistent objects:
f r o mj a v a . l a n g . O b j e c to
These last two queries will require more than one SQL S E L E C T . This means that the o r d e r b y clause does not correctly order the whole result set. It also means you cannot call these queries using Q u e r y . s c r o l l ( ) .
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
155/215
12/30/13
returns all instances of F o owith an instance of b a rwith a d a t eproperty equal to the s t a r t D a t e property of the F o o . Compound path expressions make the w h e r e clause extremely powerful. Consider the following:
f r o mC a tc a tw h e r ec a t . m a t e . n a m ei sn o tn u l l
This query translates to an SQL query with a table (inner) join. For example:
f r o mF o of o o w h e r ef o o . b a r . b a z . c u s t o m e r . a d d r e s s . c i t yi sn o tn u l l
would result in a query that would require four table joins in SQL. The =operator can be used to compare not only properties, but also instances:
f r o mC a tc a t ,C a tr i v a lw h e r ec a t . m a t e=r i v a l . m a t e s e l e c tc a t ,m a t e f r o mC a tc a t ,C a tm a t e w h e r ec a t . m a t e=m a t e
The special property (lowercase) i d can be used to reference the unique identifier of an object. See Section 16.5, Referring to identifier property for more information.
f r o mC a ta sc a tw h e r ec a t . i d=1 2 3 f r o mC a ta sc a tw h e r ec a t . m a t e . i d=6 9
The second query is efficient and does not require a table join. Properties of composite identifiers can also be used. Consider the following example where P e r s o n has composite identifiers consisting of c o u n t r yand m e d i c a r e N u m b e r :
f r o mb a n k . P e r s o np e r s o n w h e r ep e r s o n . i d . c o u n t r y=' A U ' a n dp e r s o n . i d . m e d i c a r e N u m b e r=1 2 3 4 5 6 f r o mb a n k . A c c o u n ta c c o u n t w h e r ea c c o u n t . o w n e r . i d . c o u n t r y=' A U ' a n da c c o u n t . o w n e r . i d . m e d i c a r e N u m b e r=1 2 3 4 5 6
Once again, the second query does not require a table join. See Section 16.5, Referring to identifier property for more information regarding referencing identifier properties) The special property c l a s s accesses the discriminator value of an instance in the case of polymorphic persistence. A Java class name embedded in the where clause will be translated to its discriminator value.
f r o mC a tc a tw h e r ec a t . c l a s s=D o m e s t i c C a t
You can also use components or composite user types, or properties of said component types. See Section 16.17, Components for more information. An "any" type has the special properties i d and c l a s s that allows you to express a join in the following way (where A u d i t L o g . i t e mis a property mapped with < a n y > ):
f r o mA u d i t L o gl o g ,P a y m e n tp a y m e n t w h e r el o g . i t e m . c l a s s=' P a y m e n t 'a n dl o g . i t e m . i d=p a y m e n t . i d
The l o g . i t e m . c l a s s and p a y m e n t . c l a s s would refer to the values of completely different database columns in the above query.
16.10. Expressions
Expressions used in the w h e r eclause include the following: mathematical operators: + ,,* ,/ binary comparison operators: = ,> = ,< = ,< > ,! = ,l i k e logical operations a n d ,o r ,n o t Parentheses ( )that indicates grouping
i n ,n o ti n ,b e t w e e n ,i sn u l l ,i sn o tn u l l ,i se m p t y ,i sn o te m p t y ,m e m b e ro fand n o tm e m b e ro f
"Simple"
case,
c a s e
. . .
w h e n
. . .
t h e n
. . .
e l s e
. . .
e n d ,
and
"searched"
case,
c a s ew h e n. . .t h e n. . .e l s e. . .e n d
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
156/215
12/30/13
Any function
is the name
of a
the HQL i n d e x ( )function, that applies to aliases of a joined indexed collection HQL functions that take collection-valued path expressions:
s i z e ( ) ,m i n e l e m e n t ( ) ,m a x e l e m e n t ( ) , m i n i n d e x ( ) ,m a x i n d e x ( ) , along with the special e l e m e n t s ( )
and i n d i c e sfunctions that can be quantified using s o m e ,a l l ,e x i s t s ,a n y ,i n . Any database-supported SQL scalar function like s i g n ( ) ,t r u n c ( ) ,r t r i m ( ) , and s i n ( ) JDBC-style positional parameters ? named parameters : n a m e ,: s t a r t _ d a t e , and : x 1 SQL literals ' f o o ' ,6 9 ,6 . 6 6 E + 2 ,' 1 9 7 0 0 1 0 11 0 : 0 0 : 0 1 . 0 ' Java p u b l i cs t a t i cf i n a lconstants e g . C o l o r . T A B B Y
i nand b e t w e e ncan be used as follows: f r o mD o m e s t i c C a tc a tw h e r ec a t . n a m eb e t w e e n' A 'a n d' B ' f r o mD o m e s t i c C a tc a tw h e r ec a t . n a m ei n(' F o o ' ,' B a r ' ,' B a z ')
Similarly, i sn u l land i sn o tn u l lcan be used to test for null values. Booleans can be easily used in expressions by declaring HQL query substitutions in Hibernate configuration:
< p r o p e r t yn a m e = " h i b e r n a t e . q u e r y . s u b s t i t u t i o n s " > t r u e1 ,f a l s e0 < / p r o p e r t y >
This will replace the keywords t r u e and f a l s e with the literals 1 and 0 in the translated SQL from this HQL:
f r o mC a tc a tw h e r ec a t . a l i v e=t r u e
You can test the size of a collection with the special property s i z eor the special s i z e ( )function.
f r o mC a tc a tw h e r ec a t . k i t t e n s . s i z e>0 f r o mC a tc a tw h e r es i z e ( c a t . k i t t e n s )>0
For indexed collections, you can refer to the minimum and maximum indices using m i n i n d e x and m a x i n d e x functions. Similarly, you can refer to the minimum and maximum elements of a collection of basic type using the m i n e l e m e n tand m a x e l e m e n tfunctions. For example:
f r o mC a l e n d a rc a lw h e r em a x e l e m e n t ( c a l . h o l i d a y s )>c u r r e n t _ d a t e f r o mO r d e ro r d e rw h e r em a x i n d e x ( o r d e r . i t e m s )>1 0 0 f r o mO r d e ro r d e rw h e r em i n e l e m e n t ( o r d e r . i t e m s )>1 0 0 0 0
The SQL functions a n y ,s o m e ,a l l ,e x i s t s ,i nare supported when passed the element or index set of a collection (e l e m e n t sand i n d i c e sfunctions) or the result of a subquery (see below):
s e l e c tm o t h e rf r o mC a ta sm o t h e r ,C a ta sk i t w h e r ek i ti ne l e m e n t s ( f o o . k i t t e n s ) s e l e c tpf r o mN a m e L i s tl i s t ,P e r s o np w h e r ep . n a m e=s o m ee l e m e n t s ( l i s t . n a m e s ) f r o mC a tc a tw h e r ee x i s t se l e m e n t s ( c a t . k i t t e n s ) f r o mP l a y e rpw h e r e3>a l le l e m e n t s ( p . s c o r e s ) f r o mS h o ws h o ww h e r e' f i z a r d 'i ni n d i c e s ( s h o w . a c t s )
Note that these constructs - s i z e ,e l e m e n t s ,i n d i c e s ,m i n i n d e x ,m a x i n d e x ,m i n e l e m e n t ,m a x e l e m e n t - can only be used in the where clause in Hibernate. Elements of indexed collections (arrays, lists, and maps) can be referred to by index in a where clause only:
f r o mO r d e ro r d e rw h e r eo r d e r . i t e m s [ 0 ] . i d=1 2 3 4 s e l e c tp e r s o nf r o mP e r s o np e r s o n ,C a l e n d a rc a l e n d a r
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
157/215
12/30/13
HQL also provides the built-in i n d e x ( )function for elements of a one-to-many association or collection of values.
s e l e c ti t e m ,i n d e x ( i t e m )f r o mO r d e ro r d e r j o i no r d e r . i t e m si t e m w h e r ei n d e x ( i t e m )<5
Consider how much longer and less readable the following query would be in SQL:
s e l e c tc u s t f r o mP r o d u c tp r o d , S t o r es t o r e i n n e rj o i ns t o r e . c u s t o m e r sc u s t w h e r ep r o d . n a m e=' w i d g e t ' a n ds t o r e . l o c a t i o n . n a m ei n(' M e l b o u r n e ' ,' S y d n e y ') a n dp r o d=a l le l e m e n t s ( c u s t . c u r r e n t O r d e r . l i n e I t e m s )
The optional a s cor d e s cindicate ascending or descending order respectively. The optional n u l l sf i r s tor n u l l sl a s tindicate precedence of null values while sorting.
SQL functions and aggregate functions are allowed in the h a v i n g and o r d e r b y clauses if they are
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
158/215
12/30/13
Neither the g r o u pb y clause nor the o r d e rb y clause can contain arithmetic expressions. Hibernate also does not currently expand a grouped entity, so you cannot write g r o u pb yc a tif all properties of c a tare non-aggregated. You have to list all non-aggregated properties explicitly.
16.13. Subqueries
For databases that support subselects, Hibernate supports subqueries within queries. A subquery must be surrounded by parentheses (often by an SQL aggregate function call). Even correlated subqueries (subqueries that refer to an alias in the outer query) are allowed.
f r o mC a ta sf a t c a t w h e r ef a t c a t . w e i g h t>( s e l e c ta v g ( c a t . w e i g h t )f r o mD o m e s t i c C a tc a t ) f r o mD o m e s t i c C a ta sc a t w h e r ec a t . n a m e=s o m e( s e l e c tn a m e . n i c k N a m ef r o mN a m ea sn a m e ) f r o mC a ta sc a t w h e r en o te x i s t s( f r o mC a ta sm a t ew h e r em a t e . m a t e=c a t ) f r o mD o m e s t i c C a ta sc a t w h e r ec a t . n a m en o ti n( s e l e c tn a m e . n i c k N a m ef r o mN a m ea sn a m e ) s e l e c tc a t . i d ,( s e l e c tm a x ( k i t . w e i g h t )f r o mc a t . k i t t e nk i t ) f r o mC a ta sc a t
Note that HQL subqueries can occur only in the select or where clauses. Note that subqueries can also utilize r o w v a l u e c o n s t r u c t o r syntax. See Section 16.18, Row value constructor syntax for more information.
What a monster! Actually, in real life, I'm not very keen on subqueries, so my query was really more like this:
s e l e c to r d e r . i d ,s u m ( p r i c e . a m o u n t ) ,c o u n t ( i t e m ) f r o mO r d e ra so r d e r j o i no r d e r . l i n e I t e m sa si t e m j o i ni t e m . p r o d u c ta sp r o d u c t , C a t a l o ga sc a t a l o g j o i nc a t a l o g . p r i c e sa sp r i c e w h e r eo r d e r . p a i d=f a l s e
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
159/215
12/30/13
The next query counts the number of payments in each status, excluding all payments in the A W A I T I N G _ A P P R O V A L status where the most recent status change was made by the current user. It translates to an SQL query with two inner joins and a correlated subselect against the P A Y M E N T ,
P A Y M E N T _ S T A T U Sand P A Y M E N T _ S T A T U S _ C H A N G Etables. s e l e c tc o u n t ( p a y m e n t ) ,s t a t u s . n a m e f r o mP a y m e n ta sp a y m e n t j o i np a y m e n t . c u r r e n t S t a t u sa ss t a t u s j o i np a y m e n t . s t a t u s C h a n g e sa ss t a t u s C h a n g e w h e r ep a y m e n t . s t a t u s . n a m e< >P a y m e n t S t a t u s . A W A I T I N G _ A P P R O V A L o r( s t a t u s C h a n g e . t i m e S t a m p=( s e l e c tm a x ( c h a n g e . t i m e S t a m p ) f r o mP a y m e n t S t a t u s C h a n g ec h a n g e w h e r ec h a n g e . p a y m e n t=p a y m e n t ) a n ds t a t u s C h a n g e . u s e r< >: c u r r e n t U s e r ) g r o u pb ys t a t u s . n a m e ,s t a t u s . s o r t O r d e r o r d e rb ys t a t u s . s o r t O r d e r
If the s t a t u s C h a n g e scollection was mapped as a list, instead of a set, the query would have been much simpler to write.
s e l e c tc o u n t ( p a y m e n t ) ,s t a t u s . n a m e f r o mP a y m e n ta sp a y m e n t j o i np a y m e n t . c u r r e n t S t a t u sa ss t a t u s w h e r ep a y m e n t . s t a t u s . n a m e< >P a y m e n t S t a t u s . A W A I T I N G _ A P P R O V A L o rp a y m e n t . s t a t u s C h a n g e s [m a x I n d e x ( p a y m e n t . s t a t u s C h a n g e s )] . u s e r< >: c u r r e n t U s e r g r o u pb ys t a t u s . n a m e ,s t a t u s . s o r t O r d e r o r d e rb ys t a t u s . s o r t O r d e r
The next query uses the MS SQL Server i s N u l l ( ) function to return all the accounts and unpaid payments for the organization to which the current user belongs. It translates to an SQL query with three inner joins, an outer join and a subselect against the A C C O U N T , P A Y M E N T , P A Y M E N T _ S T A T U S ,
A C C O U N T _ T Y P E ,O R G A N I Z A T I O Nand O R G _ U S E Rtables. s e l e c ta c c o u n t ,p a y m e n t f r o mA c c o u n ta sa c c o u n t l e f to u t e rj o i na c c o u n t . p a y m e n t sa sp a y m e n t w h e r e: c u r r e n t U s e ri ne l e m e n t s ( a c c o u n t . h o l d e r . u s e r s ) a n dP a y m e n t S t a t u s . U N P A I D=i s N u l l ( p a y m e n t . c u r r e n t S t a t u s . n a m e ,P a y m e n t S t a t u s . U N P A I D ) o r d e rb ya c c o u n t . t y p e . s o r t O r d e r ,a c c o u n t . a c c o u n t N u m b e r ,p a y m e n t . d u e D a t e
For some databases, we would need to do away with the (correlated) subselect.
s e l e c ta c c o u n t ,p a y m e n t f r o mA c c o u n ta sa c c o u n t j o i na c c o u n t . h o l d e r . u s e r sa su s e r l e f to u t e rj o i na c c o u n t . p a y m e n t sa sp a y m e n t w h e r e: c u r r e n t U s e r=u s e r a n dP a y m e n t S t a t u s . U N P A I D=i s N u l l ( p a y m e n t . c u r r e n t S t a t u s . n a m e ,P a y m e n t S t a t u s . U N P A I D ) o r d e rb ya c c o u n t . t y p e . s o r t O r d e r ,a c c o u n t . a c c o u n t N u m b e r ,p a y m e n t . d u e D a t e
If your database supports subselects, you can place a condition upon selection size in the where clause of your query:
f r o mU s e ru s rw h e r es i z e ( u s r . m e s s a g e s )> =1
If your database does not support subselects, use the following query:
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
160/215
12/30/13
As this solution cannot return a U s e rwith zero messages because of the inner join, the following form is also useful:
s e l e c tu s r . i d ,u s r . n a m e f r o mU s e ra su s r l e f tj o i nu s r . m e s s a g e sa sm s g g r o u pb yu s r . i d ,u s r . n a m e h a v i n gc o u n t ( m s g )=0
16.17. Components
Components can be used similarly to the simple value types that are used in HQL queries. They can appear in the s e l e c tclause as follows:
s e l e c tp . n a m ef r o mP e r s o np s e l e c tp . n a m e . f i r s tf r o mP e r s o np
where the Person's name property is a component. Components can also be used in the w h e r eclause:
f r o mP e r s o npw h e r ep . n a m e=: n a m e f r o mP e r s o npw h e r ep . n a m e . f i r s t=: f i r s t N a m e
Another common use of components is in Section 16.18, Row value constructor syntax.
That is valid syntax although it is a little verbose. You can make this more concise by using
r o wv a l u ec o n s t r u c t o rsyntax: f r o mP e r s o npw h e r ep . n a m e = ( ' J o h n ' ,' J i n g l e h e i m e r S c h m i d t ' )
Using r o w v a l u e c o n s t r u c t o r syntax can also be beneficial when using subqueries that need to
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
161/215
12/30/13
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.
17.9. Projections, aggregation and grouping 17.10. Detached queries and subqueries 17.11. Queries by natural identifier Hibernate features an intuitive, extensible criteria query API.
There are a range of built-in criterion types (R e s t r i c t i o n s subclasses). One of the most useful allows you to specify SQL directly.
L i s tc a t s=s e s s . c r e a t e C r i t e r i a ( C a t . c l a s s ) . a d d (R e s t r i c t i o n s . s q l R e s t r i c t i o n ( " l o w e r ( { a l i a s } . n a m e )l i k el o w e r ( ? ) " ," F r i t z % " ,H i b e r n a t e . S T R I N G )) . l i s t ( ) ;
The { a l i a s }placeholder will be replaced by the row alias of the queried entity. You can also obtain a criterion from a P r o p e r t y instance. You can create a P r o p e r t y by calling
P r o p e r t y . f o r N a m e ( ) :
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
162/215
12/30/13
17.4. Associations
By navigating associations using c r e a t e C r i t e r i a ( )you can specify constraints upon related entities:
L i s tc a t s=s e s s . c r e a t e C r i t e r i a ( C a t . c l a s s ) . a d d (R e s t r i c t i o n s . l i k e ( " n a m e " ," F % " )) . c r e a t e C r i t e r i a ( " k i t t e n s " ) . a d d (R e s t r i c t i o n s . l i k e ( " n a m e " ," F % " )) . l i s t ( ) ;
The second c r e a t e C r i t e r i a ( ) returns a new instance of C r i t e r i a that refers to the elements of the
k i t t e n scollection.
(c r e a t e A l i a s ( )does not create a new instance of C r i t e r i a .) The kittens collections held by the C a t instances returned by the previous two queries are not prefiltered by the criteria. If you want to retrieve just the kittens that match the criteria, you must use a R e s u l t T r a n s f o r m e r .
L i s tc a t s=s e s s . c r e a t e C r i t e r i a ( C a t . c l a s s ) . c r e a t e C r i t e r i a ( " k i t t e n s " ," k t " ) . a d d (R e s t r i c t i o n s . e q ( " n a m e " ," F % " )) . s e t R e s u l t T r a n s f o r m e r ( C r i t e r i a . A L I A S _ T O _ E N T I T Y _ M A P ) . l i s t ( ) ; I t e r a t o ri t e r=c a t s . i t e r a t o r ( ) ; w h i l e(i t e r . h a s N e x t ( )){ M a pm a p=( M a p )i t e r . n e x t ( ) ; C a tc a t=( C a t )m a p . g e t ( C r i t e r i a . R O O T _ A L I A S ) ; C a tk i t t e n=( C a t )m a p . g e t ( " k t " ) ; }
Additionally you may manipulate the result set using a left outer join:
L i s tc a t s=s e s s i o n . c r e a t e C r i t e r i a (C a t . c l a s s) . c r e a t e A l i a s ( " m a t e " ," m t " ,C r i t e r i a . L E F T _ J O I N ,R e s t r i c t i o n s . l i k e ( " m t . n a m e " ," g o o d % " )) . a d d O r d e r ( O r d e r . a s c ( " m t . a g e " ) ) . l i s t ( ) ;
This will return all of the C a t s with a mate whose name starts with "good" ordered by their mate's age, and all cats who do not have a mate. This is useful when there is a need to order or limit in the database prior to returning complex/large result sets, and removes many instances where multiple queries would have to be performed and the results unioned by java in memory. Without this feature, first all of the cats without a mate would need to be loaded in one query. A second query would need to retreive the cats with mates who's name started with "good" sorted by the mates age. Thirdly, in memory; the lists would need to be joined manually.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
163/215
12/30/13
This query will fetch both m a t e and k i t t e n s by outer join. See Section 20.1, Fetching strategies for more information.
17.6. Components
To add a restriction against a property of an embedded component, the component property name should be prepended to the property name when creating the R e s t r i c t i o n . The criteria object should be created on the owning entity, and cannot be created on the component itself. For example, suppose the C a thas a component property f u l l N a m ewith sub-properties f i r s t N a m eand l a s t N a m e :
L i s tc a t s=s e s s i o n . c r e a t e C r i t e r i a ( C a t . c l a s s ) . a d d ( R e s t r i c t i o n s . e q ( " f u l l N a m e . l a s t N a m e " ," C a t t i n g t o n " ) ) . l i s t ( ) ;
Note: this does not apply when querying collections of components, for that see below Section 17.7, Collections
17.7. Collections
When using criteria against collections, there are two distinct cases. One is if the collection contains entities (eg. < o n e t o m a n y / > or < m a n y t o m a n y / > ) or components (< c o m p o s i t e e l e m e n t / > ), and the second is if the collection contains scalar values (< e l e m e n t / > ). In the first case, the syntax is as given above in the section Section 17.4, Associations where we restrict the k i t t e n s collection. Essentially we create a C r i t e r i a object against the collection property and restrict the entity or component properties using that instance. For queryng a collection of basic values, we still create the C r i t e r i aobject against the collection, but to reference the value, we use the special property "elements". For an indexed collection, we can also reference the index property using the special property "indices".
L i s tc a t s=s e s s i o n . c r e a t e C r i t e r i a ( C a t . c l a s s ) . c r e a t e C r i t e r i a ( " n i c k N a m e s " ) . a d d ( R e s t r i c t i o n s . e q ( " e l e m e n t s " ," B a d B o y " ) ) . l i s t ( ) ;
Version properties, identifiers and associations are ignored. By default, null valued properties are excluded. You can adjust how the E x a m p l eis applied.
E x a m p l ee x a m p l e=E x a m p l e . c r e a t e ( c a t ) . e x c l u d e Z e r o e s ( ) / / e x c l u d ez e r ov a l u e dp r o p e r t i e s . e x c l u d e P r o p e r t y ( " c o l o r " ) / / e x c l u d et h ep r o p e r t yn a m e d" c o l o r " . i g n o r e C a s e ( ) / / p e r f o r mc a s ei n s e n s i t i v es t r i n gc o m p a r i s o n s . e n a b l e L i k e ( ) ; / / u s el i k ef o rs t r i n gc o m p a r i s o n s L i s tr e s u l t s=s e s s i o n . c r e a t e C r i t e r i a ( C a t . c l a s s ) . a d d ( e x a m p l e ) . l i s t ( ) ;
You can even use examples to place criteria upon associated objects.
L i s tr e s u l t s=s e s s i o n . c r e a t e C r i t e r i a ( C a t . c l a s s ) . a d d (E x a m p l e . c r e a t e ( c a t )) . c r e a t e C r i t e r i a ( " m a t e " )
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
164/215
12/30/13
There is no explicit "group by" necessary in a criteria query. Certain projection types are defined to be grouping projections , which also appear in the SQL g r o u pb yclause. An alias can be assigned to a projection so that the projected value can be referred to in restrictions or orderings. Here are two different ways to do this:
L i s tr e s u l t s=s e s s i o n . c r e a t e C r i t e r i a ( C a t . c l a s s ) . s e t P r o j e c t i o n (P r o j e c t i o n s . a l i a s (P r o j e c t i o n s . g r o u p P r o p e r t y ( " c o l o r " ) ," c o l r ")) . a d d O r d e r (O r d e r . a s c ( " c o l r " )) . l i s t ( ) ; L i s tr e s u l t s=s e s s i o n . c r e a t e C r i t e r i a ( C a t . c l a s s ) . s e t P r o j e c t i o n (P r o j e c t i o n s . g r o u p P r o p e r t y ( " c o l o r " ) . a s ( " c o l r " )) . a d d O r d e r (O r d e r . a s c ( " c o l r " )) . l i s t ( ) ;
The a l i a s ( ) and a s ( ) methods simply wrap a projection instance in another, aliased, instance of
P r o j e c t i o n . As a shortcut, you can assign an alias when you add the projection to a projection list: L i s tr e s u l t s=s e s s i o n . c r e a t e C r i t e r i a ( C a t . c l a s s ) . s e t P r o j e c t i o n (P r o j e c t i o n s . p r o j e c t i o n L i s t ( ) . a d d (P r o j e c t i o n s . r o w C o u n t ( ) ," c a t C o u n t B y C o l o r ") . a d d (P r o j e c t i o n s . a v g ( " w e i g h t " ) ," a v g W e i g h t ") . a d d (P r o j e c t i o n s . m a x ( " w e i g h t " ) ," m a x W e i g h t ") . a d d (P r o j e c t i o n s . g r o u p P r o p e r t y ( " c o l o r " ) ," c o l o r ") ) . a d d O r d e r (O r d e r . d e s c ( " c a t C o u n t B y C o l o r " )) . a d d O r d e r (O r d e r . d e s c ( " a v g W e i g h t " )) . l i s t ( ) ; L i s tr e s u l t s=s e s s i o n . c r e a t e C r i t e r i a ( D o m e s t i c . c l a s s ," c a t " ) . c r e a t e A l i a s ( " k i t t e n s " ," k i t " ) . s e t P r o j e c t i o n (P r o j e c t i o n s . p r o j e c t i o n L i s t ( ) . a d d (P r o j e c t i o n s . p r o p e r t y ( " c a t . n a m e " ) ," c a t N a m e ") . a d d (P r o j e c t i o n s . p r o p e r t y ( " k i t . n a m e " ) ," k i t N a m e ") ) . a d d O r d e r (O r d e r . a s c ( " c a t N a m e " )) . a d d O r d e r (O r d e r . a s c ( " k i t N a m e " )) . l i s t ( ) ;
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
165/215
12/30/13
AD e t a c h e d C r i t e r i a can also be used to express a subquery. Criterion instances involving subqueries can be obtained via S u b q u e r i e sor P r o p e r t y .
D e t a c h e d C r i t e r i aa v g W e i g h t=D e t a c h e d C r i t e r i a . f o r C l a s s ( C a t . c l a s s ) . s e t P r o j e c t i o n (P r o p e r t y . f o r N a m e ( " w e i g h t " ) . a v g ( )) ; s e s s i o n . c r e a t e C r i t e r i a ( C a t . c l a s s ) . a d d (P r o p e r t y . f o r N a m e ( " w e i g h t " ) . g t ( a v g W e i g h t )) . l i s t ( ) ; D e t a c h e d C r i t e r i aw e i g h t s=D e t a c h e d C r i t e r i a . f o r C l a s s ( C a t . c l a s s ) . s e t P r o j e c t i o n (P r o p e r t y . f o r N a m e ( " w e i g h t " )) ; s e s s i o n . c r e a t e C r i t e r i a ( C a t . c l a s s ) . a d d (S u b q u e r i e s . g e A l l ( " w e i g h t " ,w e i g h t s )) . l i s t ( ) ;
This functionality is not intended for use with entities with mutable natural keys. Once you have enabled the Hibernate query cache, the R e s t r i c t i o n s . n a t u r a l I d ( ) allows you to make use of the more efficient cache algorithm.
s e s s i o n . c r e a t e C r i t e r i a ( U s e r . c l a s s ) . a d d (R e s t r i c t i o n s . n a t u r a l I d ( ) . s e t ( " n a m e " ," g a v i n " ) . s e t ( " o r g " ," h b " ) ) . s e t C a c h e a b l e ( t r u e ) . u n i q u e R e s u l t ( ) ;
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
166/215
12/30/13
18.1. Using a S Q L Q u e r y
Execution of native SQL queries is controlled via the S Q L Q u e r y interface, which is obtained by calling
S e s s i o n . c r e a t e S Q L Q u e r y ( ) . The following sections describe how to use this API for querying.
These will return a List of Object arrays (Object[]) with scalar values for each column in the CATS table. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values. To avoid the overhead of using R e s u l t S e t M e t a d a t a , or simply to be more explicit in what is returned, one can use a d d S c a l a r ( ) :
s e s s . c r e a t e S Q L Q u e r y ( " S E L E C T*F R O MC A T S " ) . a d d S c a l a r ( " I D " ,H i b e r n a t e . L O N G ) . a d d S c a l a r ( " N A M E " ,H i b e r n a t e . S T R I N G ) . a d d S c a l a r ( " B I R T H D A T E " ,H i b e r n a t e . D A T E )
This query specified: the SQL query string the columns and types to return This will return Object arrays, but now it will not use R e s u l t S e t M e t a d a t abut will instead explicitly get the ID, NAME and BIRTHDATE column as respectively a Long, String and a Short from the underlying resultset. This also means that only these three columns will be returned, even though the query is using *and could return more than the three listed columns. It is possible to leave out the type information for all or some of the scalars.
s e s s . c r e a t e S Q L Q u e r y ( " S E L E C T*F R O MC A T S " ) . a d d S c a l a r ( " I D " ,H i b e r n a t e . L O N G ) . a d d S c a l a r ( " N A M E " ) . a d d S c a l a r ( " B I R T H D A T E " )
This is essentially the same query as before, but now R e s u l t S e t M e t a D a t a is used to determine the type of NAME and BIRTHDATE, where as the type of ID is explicitly specified. How the java.sql.Types returned from ResultSetMetaData is mapped to Hibernate types is controlled by the Dialect. If a specific type is not mapped, or does not result in the expected type, it is possible to customize it via calls to r e g i s t e r H i b e r n a t e T y p ein the Dialect.
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, NAME and BIRTHDATE the above queries will both return a List where each element is a Cat entity. If the entity is mapped with a m a n y t o o n e to another entity it is required to also return this when
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
167/215
12/30/13
In this example, the returned C a t 's will have their d o g property fully initialized without any extra roundtrip to the database. Notice that you added an alias name ("cat") to be able to specify the target property path of the join. It is possible to do the same eager joining for collections, e.g. if the C a t had a one-to-many to D o ginstead.
s e s s . c r e a t e S Q L Q u e r y ( " S E L E C TI D ,N A M E ,B I R T H D A T E ,D _ I D ,D _ N A M E ,C A T _ I DF R O MC A T Sc ,D O G SdW H E R Ec . I D=d . C A T _ I D " ) . a d d E n t i t y ( " c a t " ,C a t . c l a s s ) . a d d J o i n ( " c a t . d o g s " ) ;
At this stage you are reaching the limits of what is possible with native queries, without starting to enhance the sql queries to make them usable in Hibernate. Problems can arise when returning multiple entities of the same type or when the default alias/column names are not enough.
The query was intended to return two Cat instances per row: a cat and its mother. The query will, however, fail because there is a conflict of names; the instances are mapped to the same column names. Also, on some databases the returned column aliases will most likely be on the form "c.ID", "c.NAME", etc. which are not equal to the columns specified in the mappings ("ID" and "NAME"). The following form is not vulnerable to column name duplication:
s e s s . c r e a t e S Q L Q u e r y ( " S E L E C T{ c a t . * } ,{ m . * } F R O MC A T Sc ,C A T SmW H E R Ec . M O T H E R _ I D=m . I D " ) . a d d E n t i t y ( " c a t " ,C a t . c l a s s ) . a d d E n t i t y ( " m o t h e r " ,C a t . c l a s s )
This query specified: the SQL query string, with placeholders for Hibernate to inject column aliases the entities returned by the query The {cat.*} and {mother.*} notation used above is a shorthand for "all properties". Alternatively, you can list the columns explicitly, but even in this case Hibernate injects the SQL column aliases for each property. The placeholder for a column alias is just the property name qualified by the table alias. In the following example, you retrieve Cats and their mothers from a different table (cat_log) to the one declared in the mapping metadata. You can even use the property aliases in the where clause.
S t r i n gs q l=" S E L E C TI Da s{ c . i d } ,N A M Ea s{ c . n a m e } ,"+ " B I R T H D A T Ea s{ c . b i r t h D a t e } ,M O T H E R _ I Da s{ c . m o t h e r } ,{ m o t h e r . * }"+ " F R O MC A T _ L O Gc ,C A T _ L O GmW H E R E{ c . m o t h e r }=c . I D " ; L i s tl o g g e d C a t s=s e s s . c r e a t e S Q L Q u e r y ( s q l ) . a d d E n t i t y ( " c a t " ,C a t . c l a s s ) . a d d E n t i t y ( " m o t h e r " ,C a t . c l a s s ) . l i s t ( )
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
168/215
12/30/13
Table 18.1. Alias injection names Description A simple property A composite property Discriminator of an entity Syntax
{ [ a l i a s n a m e ] . [ p r o p e r t y n a m e ] }
Example
A _ N A M Ea s{ i t e m . n a m e }
{ [ a l i a s n a m e ] . [ c o m p o n e n t n a m e ] . [ p r o p e r t y n a m e ] } C U R R E N C Ya s{ i t e m . a m o u n t . c u r r e n c y } ,V A L U Ea s{ i t e m . a m o u n t . v a l u e } { [ a l i a s n a m e ] . c l a s s } D I S Ca s{ i t e m . c l a s s }
All [ a l i a s n a m e ] . * } properties of { an entity A collection key The id of an collection The element of an collection
{ [ a l i a s n a m e ] . k e y } { [ a l i a s n a m e ] . i d }
{ i t e m . * }
O R G I Da s{ c o l l . k e y } E M P I Da s{ c o l l . i d }
{ [ a l i a s n a m e ] . e l e m e n t }
X I Da s{ c o l l . e l e m e n t }
property of the element { [ a l i a s n a m e ] . e l e m e n t . [ p r o p e r t y n a m e ] } in the collection All properties of [ a l i a s n a m e ] . e l e m e n t . * } the element { in the collection All properties of { [ a l i a s n a m e ] . * } the collection
N A M Ea s{ c o l l . e l e m e n t . n a m e }
{ c o l l . e l e m e n t . * }
{ c o l l . * }
This query specified: the SQL query string a result transformer The above query will return a list of C a t D T Owhich has been instantiated and injected the values of NAME and BIRTHNAME into its corresponding properties or fields.
18.1.7. Parameters
Native SQL queries support positional as well as named parameters:
Q u e r yq u e r y=s e s s . c r e a t e S Q L Q u e r y ( " S E L E C T*F R O MC A T SW H E R EN A M El i k e? " ) . a d d E n t i t y ( C a t . c l a s s ) ; L i s tp u s L i s t=q u e r y . s e t S t r i n g ( 0 ," P u s % " ) . l i s t ( ) ; q u e r y=s e s s . c r e a t e S Q L Q u e r y ( " S E L E C T*F R O MC A T SW H E R EN A M El i k e: n a m e " ) . a d d E n t i t y ( C a t . c l a s s ) ; L i s tp u s L i s t=q u e r y . s e t S t r i n g ( " n a m e " ," P u s % " ) . l i s t ( ) ;
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
169/215
12/30/13
Example 18.1. Named sql query using the <sql-query> maping element
< s q l q u e r yn a m e = " p e r s o n s " > < r e t u r na l i a s = " p e r s o n "c l a s s = " e g . P e r s o n " / > S E L E C Tp e r s o n . N A M EA S{ p e r s o n . n a m e } , p e r s o n . A G EA S{ p e r s o n . a g e } , p e r s o n . S E XA S{ p e r s o n . s e x } F R O MP E R S O Np e r s o n W H E R Ep e r s o n . N A M EL I K E: n a m e P a t t e r n < / s q l q u e r y >
The < r e t u r n j o i n > element is use to join associations and the < l o a d c o l l e c t i o n > element is used to define queries which initialize collections,
A named SQL query may return a scalar value. You must declare the column alias and Hibernate type using the < r e t u r n s c a l a r >element:
You can externalize the resultset mapping information in a < r e s u l t s e t > element which will allow you to either reuse them across several named queries or through the s e t R e s u l t S e t M a p p i n g ( )API.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
170/215
12/30/13
You can, alternatively, use the resultset mapping information in your hbm files directly in java code.
So far we have only looked at externalizing SQL queries using Hibernate mapping files. The same concept is also available with anntations and is called named native queries. You can use
@ N a m e d N a t i v e Q u e r y
(@ N a m e d N a t i v e Q u e r i e s )
in
conjunction
with
@ S q l R e s u l t S e t M a p p i n g
(@ S q l R e s u l t S e t M a p p i n g s ). Like @ N a m e d Q u e r y , @ N a m e d N a t i v e Q u e r y and @ S q l R e s u l t S e t M a p p i n g can be defined at class level, but their scope is global to the application. Lets look at a view examples. Example 18.7, Named SQL query using @ N a m e d N a t i v e Q u e r ytogether with @ S q l R e s u l t S e t M a p p i n g shows how a r e s u l t S e t M a p p i n g parameter is defined in @ N a m e d N a t i v e Q u e r y . It represents the name of a defined @ S q l R e s u l t S e t M a p p i n g . The resultset mapping declares the entities retrieved by this native query. Each field of the entity is bound to an SQL alias (or column name). All fields of the entity including the ones of subclasses and the foreign key columns of related entities have to be present in the SQL query. Field definitions are optional provided that they map to the same column name as the one declared on the class property. In the example 2 entities, N i g h t and A r e a , are returned and each property is declared and associated to a column name, actually the column name retrieved by the query. In Example 18.8, Implicit result set mapping the result set mapping is implicit. We only describe the entity class of the result set mapping. The property / column mappings is done using the entity mapping values. In this case the model property is bound to the model_txt column. Finally, if the association to a related entity involve a composite primary key, a @ F i e l d R e s u l t element should be used for each foreign key column. The @ F i e l d R e s u l tname is composed of the property name for the relationship, followed by a dot ("."), followed by the name or the field or property of the primary key. This can be seen in Example 18.9, Using dot notation in @FieldResult for specifying associations .
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
171/215
12/30/13
}
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
172/215
12/30/13
Tip
If you retrieve a single entity using the default mapping, you can specify the r e s u l t C l a s sattribute instead of r e s u l t S e t M a p p i n g :
@ N a m e d N a t i v e Q u e r y ( n a m e = " i m p l i c i t S a m p l e " ,q u e r y = " s e l e c t*f r o mS p a c e S h i p " ,r e s u l t C l a s s = S p a c e S h i p . c l a s s ) p u b l i cc l a s sS p a c e S h i p{
In some of your native queries, you'll have to return scalar values, for example when building report queries. You can map them in the @ S q l R e s u l t s e t M a p p i n g through @ C o l u m n R e s u l t . You actually can even mix, entities and scalar returns in the same native query (this is probably not that common though).
An other query hint specific to native queries has been introduced: o r g . h i b e r n a t e . c a l l a b l e which can be true or false depending on whether the query is a stored procedure or not.
In this example < r e t u r n p r o p e r t y >was used in combination with the { } -syntax for injection. This allows users to choose how they want to refer column and properties. If your mapping has a discriminator you must use < r e t u r n d i s c r i m i n a t o r > to specify the discriminator column.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
173/215
12/30/13
To use this query in Hibernate you need to map it via a named query.
< s q l q u e r yn a m e = " s e l e c t A l l E m p l o y e e s _ S P "c a l l a b l e = " t r u e " > < r e t u r na l i a s = " e m p "c l a s s = " E m p l o y m e n t " > < r e t u r n p r o p e r t yn a m e = " e m p l o y e e "c o l u m n = " E M P L O Y E E " / > < r e t u r n p r o p e r t yn a m e = " e m p l o y e r "c o l u m n = " E M P L O Y E R " / > < r e t u r n p r o p e r t yn a m e = " s t a r t D a t e "c o l u m n = " S T A R T D A T E " / > < r e t u r n p r o p e r t yn a m e = " e n d D a t e "c o l u m n = " E N D D A T E " / > < r e t u r n p r o p e r t yn a m e = " r e g i o n C o d e "c o l u m n = " R E G I O N C O D E " / > < r e t u r n p r o p e r t yn a m e = " i d "c o l u m n = " E I D " / > < r e t u r n p r o p e r t yn a m e = " s a l a r y " > < r e t u r n c o l u m nn a m e = " V A L U E " / > < r e t u r n c o l u m nn a m e = " C U R R E N C Y " / > < / r e t u r n p r o p e r t y > < / r e t u r n > {?=c a l ls e l e c t A l l E m p l o y m e n t s ( )} < / s q l q u e r y >
Stored procedures currently only return scalars and entities. < r e t u r n j o i n > and < l o a d c o l l e c t i o n > are not supported.
For Oracle the following rules apply: A function must return a result set. The first parameter of a procedure must be an O U T that returns a result set. This is done by using a S Y S _ R E F C U R S O Rtype in Oracle 9 or 10. In Oracle you need to define aR E FC U R S O Rtype. See Oracle literature for further information. For Sybase or MS SQL server the following rules apply: The procedure must return a result set. Note that since these servers can return multiple result sets and update counts, Hibernate will iterate the results and take the first result that is a result set as its return value. Everything else will be discarded. If you can enable S E TN O C O U N TO Nin your procedure it will probably be more efficient, but this is not a requirement.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
174/215
12/30/13
@ S Q L D e l e t e (s q l = " D E L E T EC H A O SW H E R Ei d=? " ) @ S Q L D e l e t e A l l (s q l = " D E L E T EC H A O S " ) @ L o a d e r ( n a m e d Q u e r y=" c h a o s " ) @ N a m e d N a t i v e Q u e r y ( n a m e = " c h a o s " ,q u e r y = " s e l e c ti d ,s i z e ,n a m e ,l o w e r (n i c k n a m e)a sn i c k n a m ef r o mC H A O Sw h e r ex m l : i d =? " ,r e s u l t C l a p u b l i cc l a s sC h a o s{ @ I d p r i v a t eL o n gi d ; p r i v a t eL o n gs i z e ; p r i v a t eS t r i n gn a m e ; p r i v a t eS t r i n gn i c k n a m e ;
and DELETE all statement. The same can be achieved using Hibernate mapping files and the
< s q l i n s e r t > , < s q l u p d a t e > and < s q l d e l e t e > nodes. This can be seen in Example 18.12, Custom
CRUD XML.
If you expect to call a store procedure, be sure to set the c a l l a b l e attribute to t r u e . In annotations as well as in xml. To check that the execution happens correctly, Hibernate allows you to define one of those three strategies: none: no check is performed: the store procedure is expected to fail upon issues count: use of rowcount to check that the update is successful param: like COUNT but using an output parameter rather that the standard mechanism To define the result check style, use the c h e c kparameter which is again available in annoations as well as in xml. You can use the exact same set of annotations respectively xml nodes to override the collection related statements -see Example 18.13, Overriding SQL statements for collections using annotations.
Tip
The parameter order is important and is defined by the order Hibernate handles properties. You can see the expected order by enabling debug logging for the o r g . h i b e r n a t e . p e r s i s t e r . e n t i t y level. With this level enabled Hibernate will print out the static SQL that is used to create, update, delete etc. entities. (To see the expected sequence, remember to not include your custom SQL through annotations or mapping files as that will override the Hibernate generated static sql)
Overriding
SQL
statements
for
secondary
tables
is
also
possible
using
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
175/215
12/30/13
The previous example also shows that you can give a comment to a given table (primary or secondary): This comment will be used for DDL generation.
Tip
The SQL is directly executed in your database, so you can use any dialect you like. This will, however, reduce the portability of your mapping if you use database specific SQL.
Last but not least, stored procedures are in most cases required to return the number of rows inserted, updated and deleted. Hibernate always registers the first statement parameter as a numeric output parameter for the CUD operations:
This is just a named query declaration, as discussed earlier. You can reference this named query in a class mapping:
< c l a s sn a m e = " P e r s o n " > < i dn a m e = " i d " > < g e n e r a t o rc l a s s = " i n c r e m e n t " / > < / i d > < p r o p e r t yn a m e = " n a m e "n o t n u l l = " t r u e " / > < l o a d e rq u e r y r e f = " p e r s o n " / > < / c l a s s >
This even works with stored procedures. You can even define a query for collection loading:
< s e tn a m e = " e m p l o y m e n t s "i n v e r s e = " t r u e " > < k e y / > < o n e t o m a n yc l a s s = " E m p l o y m e n t " / > < l o a d e rq u e r y r e f = " e m p l o y m e n t s " / > < / s e t > < s q l q u e r yn a m e = " e m p l o y m e n t s " > < l o a d c o l l e c t i o na l i a s = " e m p "r o l e = " P e r s o n . e m p l o y m e n t s " / > S E L E C T{ e m p . * } F R O ME M P L O Y M E N Te m p W H E R EE M P L O Y E R=: i d O R D E RB YS T A R T D A T EA S C ,E M P L O Y E EA S C < / s q l q u e r y >
You can also define an entity loader that loads a collection by join fetching:
< s q l q u e r yn a m e = " p e r s o n " > < r e t u r na l i a s = " p e r s "c l a s s = " P e r s o n " / > < r e t u r n j o i na l i a s = " e m p "p r o p e r t y = " p e r s . e m p l o y m e n t s " / > S E L E C TN A M EA S{ p e r s . * } ,{ e m p . * } F R O MP E R S O Np e r s
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
176/215
12/30/13
The annotation equivalent < l o a d e r > is the @Loader annotation as seen in Example 18.11, Custom CRUD via annotations.
or
parameter will allow you to adjust the behavior of the filter at runtime. Each parameter is defined by a @ P a r a m D e f which has a name and a type. You can also define a d e f a u l t C o n d i t i o n ( ) parameter for a given @ F i l t e r D e f to set the default condition to use when none are defined in each individual @ F i l t e r .
@ F i l t e r D e f (s) can be defined at the class or package level.
We now need to define the SQL filter clause applied to either the entity load or the collection load.
@ F i l t e r is used and placed either on the entity or the collection element. The connection between @ F i l t e r N a m eand @ F i l t e ris a matching name.
When the collection use an association table as a relational representation, you might want to apply the filter condition to the association table itself or to the target entity table. To apply the constraint on the target entity, use the regular @ F i l t e r annotation. However, if you want to target the association table, use the @ F i l t e r J o i n T a b l eannotation.
Using Hibernate mapping files for defining filters the situtation is very similar. The filters must first be defined and then attached to the appropriate mapping elements. To define a filter, use the
< f i l t e r d e f / >element within a < h i b e r n a t e m a p p i n g / >element:
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
177/215
12/30/13
This filter can then be attached to a class or collection (or, to both or multiples of each at the same time):
The
methods
on
S e s s i o n
are:
e n a b l e F i l t e r ( S t r i n g
f i l t e r N a m e ) ,
not enabled for a given session. Filters must be enabled through use of the S e s s i o n . e n a b l e F i l t e r ( ) method, which returns an instance of the F i l t e rinterface. If you used the simple filter defined above, it would look like this:
s e s s i o n . e n a b l e F i l t e r ( " m y F i l t e r " ) . s e t P a r a m e t e r ( " m y F i l t e r P a r a m " ," s o m e v a l u e " ) ;
Methods on the org.hibernate.Filter interface do allow the method-chaining common to much of Hibernate. The following is a full example, using temporal data with an effective record date pattern:
< f i l t e r d e fn a m e = " e f f e c t i v e D a t e " > < f i l t e r p a r a mn a m e = " a s O f D a t e "t y p e = " d a t e " / > < / f i l t e r d e f > < c l a s sn a m e = " E m p l o y e e ". . . > . . . < m a n y t o o n en a m e = " d e p a r t m e n t "c o l u m n = " d e p t _ i d "c l a s s = " D e p a r t m e n t " / > < p r o p e r t yn a m e = " e f f e c t i v e S t a r t D a t e "t y p e = " d a t e "c o l u m n = " e f f _ s t a r t _ d t " / > < p r o p e r t yn a m e = " e f f e c t i v e E n d D a t e "t y p e = " d a t e "c o l u m n = " e f f _ e n d _ d t " / > . . . < ! N o t et h a tt h i sa s s u m e sn o n t e r m i n a lr e c o r d sh a v ea ne f f _ e n d _ d ts e tt o am a xd bd a t ef o rs i m p l i c i t y s a k e > < f i l t e rn a m e = " e f f e c t i v e D a t e " c o n d i t i o n = " : a s O f D a t eB E T W E E Ne f f _ s t a r t _ d ta n de f f _ e n d _ d t " / > < / c l a s s > < c l a s sn a m e = " D e p a r t m e n t ". . . > . . . < s e tn a m e = " e m p l o y e e s "l a z y = " t r u e " > < k e yc o l u m n = " d e p t _ i d " / > < o n e t o m a n yc l a s s = " E m p l o y e e " / > < f i l t e rn a m e = " e f f e c t i v e D a t e " c o n d i t i o n = " : a s O f D a t eB E T W E E Ne f f _ s t a r t _ d ta n de f f _ e n d _ d t " / > < / s e t > < / c l a s s >
In order to ensure that you are provided with currently effective records, enable the filter on the session prior to retrieving employee data:
S e s s i o ns e s s i o n=. . . ; s e s s i o n . e n a b l e F i l t e r ( " e f f e c t i v e D a t e " ) . s e t P a r a m e t e r ( " a s O f D a t e " ,n e wD a t e ( ) ) ; L i s tr e s u l t s=s e s s i o n . c r e a t e Q u e r y ( " f r o mE m p l o y e ea sew h e r ee . s a l a r y>: t a r g e t S a l a r y " ) . s e t L o n g ( " t a r g e t S a l a r y " ,n e wL o n g ( 1 0 0 0 0 0 0 ) ) . l i s t ( ) ;
Even though a salary constraint was mentioned explicitly on the results in the above HQL, because of the enabled filter, the query will return only currently active employees who have a salary greater than one million dollars. If you want to use filters with outer joining, either through HQL or load fetching, be careful of the direction of the condition expression. It is safest to set this up for left outer joining. Place the parameter first followed by the column name(s) after the operator. After being defined, a filter might be attached to multiple entities and/or collections each with its own condition. This can be problematic when the conditions are the same each time. Using < f i l t e r d e f / > allows you to definine a default condition, either as an attribute or CDATA:
< f i l t e r d e fn a m e = " m y F i l t e r "c o n d i t i o n = " a b c>x y z " > . . . < / f i l t e r d e f > < f i l t e r d e fn a m e = " m y O t h e r F i l t e r " > a b c = x y z < / f i l t e r d e f >
This default condition will be used whenever the filter is attached to something without specifying a condition. This means you can give a specific condition as part of the attachment of the filter that overrides the default condition in that particular case.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
178/215
12/30/13
20.2. The Second Level Cache 20.2.1. Cache mappings 20.2.2. Strategy: read only 20.2.3. Strategy: read/write 20.2.4. Strategy: nonstrict read/write 20.2.5. Strategy: transactional 20.2.6. Cache-provider/concurrency-strategy compatibility 20.3. Managing the caches 20.4. The Query Cache 20.4.1. Enabling query caching 20.4.2. Query cache regions 20.5. Bytecode Enhancement 20.5.1. Implementing o r g . h i b e r n a t e . e n g i n e . s p i . M a n a g e d E n t i t yinterface 20.5.2. Runtime instrument 20.5.3. Buildtime instrument 20.6. Understanding Collection performance 20.6.1. Taxonomy 20.6.2. Lists, maps, idbags and sets are the most efficient collections to update 20.6.3. Bags and lists are the most efficient inverse collections 20.6.4. One shot delete 20.7. Monitoring performance 20.7.1. Monitoring a SessionFactory 20.7.2. Metrics
Select fetching: a second S E L E C T is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying l a z y = " f a l s e " , this second select will only be executed when you access the association. Subselect fetching: a second S E L E C T 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
l a z y = " f a l s e " , this second select will only be executed when you access the association.
Batch fetching: an optimization strategy for select fetching. Hibernate retrieves a batch of entity instances or collections in a single S E L E C Tby specifying a list of primary 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 collection. 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. It is suitable for large collections. Proxy fetching: a single-valued association is fetched when a method other than the identifier getter is invoked upon the associated object. "No-proxy" fetching: a single-valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy; the association is fetched even when only
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
179/215
12/30/13
Since the permissions collection was not initialized when the S e s s i o n was closed, the collection will not be able to load its state. Hibernate does not support lazy initialization for detached objects . This can be fixed by moving the code that reads from the collection to just before the transaction is committed. Alternatively, you can use a non-lazy collection or association, by specifying l a z y = " f a l s e " for the association mapping. However, it is intended that lazy initialization be used for almost all collections and associations. If you define too many non-lazy associations in your object model, Hibernate will fetch the entire database into memory in every transaction. On the other hand, you can use join fetching, which is non-lazy by nature, instead of select fetching in a particular transaction. We will now explain how to customize the fetching strategy. In Hibernate, the mechanisms for choosing a fetch strategy are identical for single-valued associations and collections.
The f e t c hstrategy defined in the mapping document affects: retrieval via g e t ( )or l o a d ( ) retrieval that happens implicitly when an association is navigated
C r i t e r i aqueries
HQL queries if s u b s e l e c tfetching is used Irrespective of the fetching strategy you use, the defined non-lazy graph is guaranteed to be loaded into memory. This might, however, result in several immediate selects being used to execute a particular HQL query. Usually, the mapping document is not used to customize fetching. Instead, we keep the default behavior, and override it for a particular transaction, using l e f tj o i nf e t c h in HQL. This tells Hibernate to fetch the association eagerly in the first select, using an outer join. In the C r i t e r i a query API, you would use s e t F e t c h M o d e ( F e t c h M o d e . J O I N ) . If you want to change the fetching strategy used by g e t ( )or l o a d ( ) , you can use a C r i t e r i a query. For example:
U s e ru s e r=( U s e r )s e s s i o n . c r e a t e C r i t e r i a ( U s e r . c l a s s ) . s e t F e t c h M o d e ( " p e r m i s s i o n s " ,F e t c h M o d e . J O I N ) . a d d (R e s t r i c t i o n s . i d E q ( u s e r I d )) . u n i q u e R e s u l t ( ) ;
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
180/215
12/30/13
Firstly, instances of C a t will never be castable to D o m e s t i c C a t , even if the underlying instance is an instance of D o m e s t i c C a t :
C a tc a t=( C a t )s e s s i o n . l o a d ( C a t . c l a s s ,i d ) ; / /i n s t a n t i a t eap r o x y( d o e sn o th i tt h ed b ) i f(c a t . i s D o m e s t i c C a t ( )){ / /h i tt h ed bt oi n i t i a l i z et h ep r o x y D o m e s t i c C a td c=( D o m e s t i c C a t )c a t ; / /E r r o r ! . . . . }
However, the situation is not quite as bad as it looks. Even though we now have two references to different proxy objects, the underlying instance will still be the same object:
c a t . s e t W e i g h t ( 1 1 . 0 ) ; / /h i tt h ed bt oi n i t i a l i z et h ep r o x y S y s t e m . o u t . p r i n t l n (d c . g e t W e i g h t ( )) ; / /1 1 . 0
Third, you cannot use a bytecode provider generated proxy for a f i n a l class or a class with any f i n a l methods. Finally, if your persistent object acquires any resources upon instantiation (e.g. in initializers or default constructor), then those resources will also be acquired by the proxy. The proxy class is an actual subclass of the persistent class. These problems are all due to fundamental limitations in Java's single inheritance model. To avoid these problems your persistent classes must each implement an interface that declares its business methods. You should specify these interfaces in the mapping file where C a t I m p l implements the interface C a t and
D o m e s t i c C a t I m p limplements the interface D o m e s t i c C a t . For example: < c l a s sn a m e = " C a t I m p l "p r o x y = " C a t " > . . . . . . < s u b c l a s sn a m e = " D o m e s t i c C a t I m p l "p r o x y = " D o m e s t i c C a t " > . . . . . < / s u b c l a s s > < / c l a s s >
Note
l i s t ( )does not usually return proxies.
Relationships are also lazily initialized. This means you must declare any properties to be of type C a t , not C a t I m p l . Certain operations do not require proxy initialization:
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
181/215
12/30/13
The identifier getter method Hibernate will detect persistent classes that override e q u a l s ( )or h a s h C o d e ( ) . By choosing l a z y = " n o p r o x y " instead of the default l a z y = " p r o x y " , you can avoid problems associated with typecasting. However, buildtime bytecode instrumentation is required, and all operations will result in immediate proxy initialization.
as
long
as
its
S e s s i o n
is
still
open.
Another option is to keep the S e s s i o n open until all required collections and proxies have been loaded. In some application architectures, particularly where the code that accesses data using Hibernate, and the code that uses it are in different application layers or different physical processes, it can be a problem to ensure that the S e s s i o n is open when a collection is initialized. There are two basic ways to deal with this issue: In a web-based application, a servlet filter can be used to close the S e s s i o n only at the end of a user request, once the rendering of the view is complete (the Open Session in View pattern). Of course, this places heavy demands on the correctness of the exception handling of your application infrastructure. It is vitally important that the S e s s i o n is closed and the transaction ended before returning to the user, even when an exception occurs during rendering of the view. See the Hibernate Wiki for examples of this "Open Session in View" pattern. In an application with a separate business tier, the business logic must "prepare" all collections that the web tier needs before returning. 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. Usually, the application calls H i b e r n a t e . i n i t i a l i z e ( ) 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 F E T C Hclause or a F e t c h M o d e . J O I Nin C r i t e r i a . This is usually easier if you adopt the Command pattern instead of a Session Facade. You can also attach a previously loaded object to a new S e s s i o n with m e r g e ( ) or l o c k ( ) before accessing uninitialized collections or other proxies. Hibernate does not, and certainly should not, do this automatically since it would introduce impromptu transaction semantics. Sometimes you do not want to initialize a large collection, but still need some information about it, like its size, for example, or a subset of the data. You can use a collection filter to get the size of a collection without initializing it:
(( I n t e g e r )s . c r e a t e F i l t e r (c o l l e c t i o n ," s e l e c tc o u n t ( * ) ") . l i s t ( ) . g e t ( 0 )) . i n t V a l u e ( )
The c r e a t e F i l t e r ( )method is also used to efficiently retrieve subsets of a collection without needing to initialize the whole collection:
s . c r e a t e F i l t e r (l a z y C o l l e c t i o n ," " ) . s e t F i r s t R e s u l t ( 0 ) . s e t M a x R e s u l t s ( 1 0 ) . l i s t ( ) ;
owners. You can tune this behavior by specifying a b a t c h s i z ein the mapping of P e r s o n :
< c l a s sn a m e = " P e r s o n "b a t c h s i z e = " 1 0 " > . . . < / c l a s s >
With this b a t c h s i z especified, Hibernate will now execute queries on demand when need to access the uninitialized proxy, as above, but the difference is that instead of querying the exactly proxy entity that
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
182/215
12/30/13
The
legacy
algorithm
where
we
keep
set
of
pre-built
o r g . h i b e r n a t e . i n t e r n a l . u t i l . c o l l e c t i o n s . A r r a y H e l p e r # g e t B a t c h S i z e s .
using the next-smaller pre-built batch size from the number of existing batchable identifiers. In the above example, with a batch-size setting of 25 the pre-built batch sizes would be [25, 12, 10, 9, 8, 7, .., 1]. And since there are 25 persons' owner to be initialized, then only one query will be executed using these 25 owners' identifier. But in another case, suppose there are only 24 persons, there will be 3 queries (12, 10, 2) will be executed to go through all person's owner, and the query will looks like :
s e l e c t*f r o mo w n e rw h e r ei di n( ? ,? ,? ,? ,? ,? ,? ,? ,? ,? ,? ,? ) s e l e c t*f r o mo w n e rw h e r ei di n( ? ,? ,? ,? ,? ,? ,? ,? ,? ,? ) s e l e c t*f r o mo w n e rw h e r ei di n( ? ,? )
P A D D E D
This is kind of similar with the legacy algorithm, it uses the pre-build batch sizes based on same
o r g . h i b e r n a t e . i n t e r n a l . u t i l . c o l l e c t i o n s . A r r a y H e l p e r # g e t B a t c h S i z e s . The difference is that here
hibernate will use the next-bigger batch size and pads the extra identifier placeholders. So, using the same example above, initializing 25 persons the query would be same as above, only 1 query will be executed to batch query all the owners. However, the attempt to batch load 24 owners would result just a single batch of size 25, the identifiers to load would be "padded" (aka, repeated) to make up the difference.
D Y N A M I C
Dynamically builds its SQL based on the actual number of available ids. Does still limit to the batchsize defined on the entity. You can also enable batch fetching of collections. For example, if each P e r s o n has a lazy collection of
C a t s, and 10 persons are currently loaded in the S e s s i o n , iterating through all persons will generate 10 S E L E C T s, one for every call to g e t C a t s ( ) . If you enable batch fetching for the c a t s collection in the
For example, with a b a t c h s i z e of 3 and using l e g a c y batch style, Hibernate will load 3, 3, 3, 1 collections in four S E L E C T s. Again, the value of the attribute depends on the expected number of uninitialized collections in a particular S e s s i o n . Batch fetching of collections is particularly useful if you have a nested tree of items, i.e. the typical bill-ofmaterials pattern. However, a nested set or a materialized path might be a better option for read-mostly trees.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
183/215
12/30/13
Example 20.2. Specifying a fetch profile using < f e t c h p r o f i l e >outside < c l a s s >node
< h i b e r n a t e m a p p i n g > < c l a s sn a m e = " C u s t o m e r " > . . . < s e tn a m e = " o r d e r s "i n v e r s e = " t r u e " > < k e yc o l u m n = " c u s t _ i d " / > < o n e t o m a n yc l a s s = " O r d e r " / > < / s e t > < / c l a s s > < c l a s sn a m e = " O r d e r " > . . . < / c l a s s > < f e t c h p r o f i l en a m e = " c u s t o m e r w i t h o r d e r s " > < f e t c he n t i t y = " C u s t o m e r "a s s o c i a t i o n = " o r d e r s "s t y l e = " j o i n " / > < / f e t c h p r o f i l e > < / h i b e r n a t e m a p p i n g >
Example 20.3. Specifying a fetch profile using < f e t c h p r o f i l e >inside < c l a s s >node
< h i b e r n a t e m a p p i n g > < c l a s sn a m e = " C u s t o m e r " > . . . < s e tn a m e = " o r d e r s "i n v e r s e = " t r u e " > < k e yc o l u m n = " c u s t _ i d " / > < o n e t o m a n yc l a s s = " O r d e r " / > < / s e t > < f e t c h p r o f i l en a m e = " c u s t o m e r w i t h o r d e r s " > < f e t c ha s s o c i a t i o n = " o r d e r s "s t y l e = " j o i n " / > < / f e t c h p r o f i l e > < / c l a s s > < c l a s sn a m e = " O r d e r " > . . . < / c l a s s > < / h i b e r n a t e m a p p i n g >
Now normally when you get a reference to a particular customer, that customer's set of orders will be lazy meaning we will not yet have loaded those orders from the database. Normally this is a good thing. Now lets say that you have a certain use case where it is more efficient to load the customer and their orders together. One way certainly is to use "dynamic fetching" strategies via an HQL or criteria queries. But another option is to use a fetch profile to achieve that. The following code will load both the customer andtheir orders:
Note
@ F e t c h P r o f i l e definitions are global and it does not matter on which class
you place them. You can place the @ F e t c h P r o f i l e annotation either onto a class or package (package-info.java). In order to define multiple fetch profiles for the same class or package @ F e t c h P r o f i l e scan be used.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
184/215
12/30/13
HHH-3414 for details.
Lazy property loading requires buildtime bytecode instrumentation. If your persistent classes are not enhanced, Hibernate will ignore lazy property settings and return to immediate fetching. For bytecode instrumentation, use the following Ant task:
< t a r g e tn a m e = " i n s t r u m e n t "d e p e n d s = " c o m p i l e " > < t a s k d e fn a m e = " i n s t r u m e n t "c l a s s n a m e = " o r g . h i b e r n a t e . t o o l . i n s t r u m e n t . I n s t r u m e n t T a s k " > < c l a s s p a t hp a t h = " $ { j a r . p a t h } " / > < c l a s s p a t hp a t h = " $ { c l a s s e s . d i r } " / > < c l a s s p a t hr e f x m l : i d = " l i b . c l a s s . p a t h " / > < / t a s k d e f > < i n s t r u m e n tv e r b o s e = " t r u e " > < f i l e s e td i r = " $ { t e s t c l a s s e s . d i r } / o r g / h i b e r n a t e / a u c t i o n / m o d e l " > < i n c l u d en a m e = " * . c l a s s " / > < / f i l e s e t > < / i n s t r u m e n t > < / t a r g e t >
A different way of avoiding unnecessary column reads, at least for read-only transactions, is to use the projection features of HQL or Criteria queries. This avoids the need for buildtime bytecode processing and is certainly a preferred solution. You can force the usual eager fetching of properties using f e t c ha l lp r o p e r t i e sin HQL.
using
the
property
open-source cache providers that are listed in Table 20.1, Cache Providers. You can also implement your own and plug it in as outlined above. Note that versions prior to Hibernate 3.2 use EhCache as the default cache provider.
Provider class
Type
o r g . h i b e r n a t e . t e s t i n g . c a c h e . C a c h i n g R e g i o n F a c t o r y
memory
yes
memory, EHCache
o r g . h i b e r n a t e . c a c h e . e h c a c h e . E h C a c h e R e g i o n F a c t o r y
yes
yes
Infinispan
o r g . h i b e r n a t e . c a c h e . i n f i n i s p a n . I n f i n i s p a n R e g i o n F a c t o r y multicast),
yes (replication
yes (clock
transactional
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
185/215
12/30/13
this the
by setting
the
s h a r e d c a c h e m o d e element
in in
your your
or
j a v a x . p e r s i s t e n c e . s h a r e d C a c h e . m o d e
property
as cacheable.
D I S A B L E _ S E L E C T I V E : entities are cached unless explicitly marked as not cacheable. A L L : all entities are always cached even if marked as non cacheable. N O N E : no entity are cached even if marked as cacheable. This option can make sense to disable
second-level cache altogether. The cache concurrency strategy used by default can be set globaly via the
h i b e r n a t e . c a c h e . d e f a u l t _ c a c h e _ c o n c u r r e n c y _ s t r a t e g y configuration
property are:
r e a d o n l y r e a d w r i t e n o n s t r i c t r e a d w r i t e t r a n s a c t i o n a l
Note
It is recommended to define the cache concurrency strategy per entity rather than using a global one. Use the @ o r g . h i b e r n a t e . a n n o t a t i o n s . C a c h e annotation for that.
Hibernate also let's you cache the content of a collection or the identifiers if the collection contains other entities. Use the @ C a c h eannotation on the collection property.
@ o r g . h i b e r n a t e . a n n o t a t i o n s . C a c h e
annotations with its attributes. It allows you to define the caching strategy and region of a given second level cache.
usage: the given cache concurrency strategy (NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL) region (optional): the cache region (default to the fqcn of the class or the fq role name of the collection)
i n c l u d e(optional): all to include all properties, non-lazy to only include non lazy properties
(default all).
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
186/215
12/30/13
Alternatively
to
< c a c h e > ,
you
can
use
in
h i b e r n a t e . c f g . x m l .
The following table shows which providers are compatible with which concurrency strategies.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
187/215
12/30/13
Cache
Example 20.9. Explcitly evicting a cached instance from the first level cache using S e s s i o n . e v i c t ( )
S c r o l l a b l e R e s u l tc a t s=s e s s . c r e a t e Q u e r y ( " f r o mC a ta sc a t " ) . s c r o l l ( ) ;/ / ah u g er e s u l ts e t w h i l e(c a t s . n e x t ( )){ C a tc a t=( C a t )c a t s . g e t ( 0 ) ; d o S o m e t h i n g W i t h A C a t ( c a t ) ; s e s s . e v i c t ( c a t ) ; }
The S e s s i o n also provides a c o n t a i n s ( ) method to determine if an instance belongs to the session cache. To evict all objects from the session cache, call S e s s i o n . c l e a r ( ) For the second-level cache, there are methods defined on S e s s i o n F a c t o r y for evicting the cached state of an instance, entire class, collection instance or entire collection role.
Example
20.10.
Second-level
cache
eviction
via
S e s s i o n F a c t o t y . e v i c t ( )
and
The C a c h e M o d econtrols how a particular session interacts with the second-level cache:
C a c h e M o d e . N O R M A L : will read items from and write items to the second-level cache C a c h e M o d e . G E T : will read items from the second-level cache. Do not write to the second-level cache
cache. Bypass the effect of h i b e r n a t e . c a c h e . u s e _ m i n i m a l _ p u t s 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, use the S t a t i s t i c sAPI:
Example 20.11. Browsing the second-level cache entries via the S t a t i s t i c sAPI
M a pc a c h e E n t r i e s=s e s s i o n F a c t o r y . g e t S t a t i s t i c s ( ) . g e t S e c o n d L e v e l C a c h e S t a t i s t i c s ( r e g i o n N a m e ) . g e t E n t r i e s ( ) ;
You will need to enable statistics and, optionally, force Hibernate to keep the cache entries in a more readable format:
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
188/215
12/30/13
to queryable tables. These are used to validate the results as they are served from the query cache.
Important
If you configure your underlying cache implementation to use expiry or timeouts is very important that the cache timeout of the underlying cache region for the UpdateTimestampsCache be set to a higher value than the timeouts of any of the query caches. In fact, we recommend that the the UpdateTimestampsCache region not be configured for expiry at all. Note, in particular, that an LRU cache expiry policy is never appropriate.
As mentioned above, most queries do not benefit from caching or their results. So by default, individual queries are not cached even after enabling query caching. To enable results caching for a particular query, call o r g . h i b e r n a t e . Q u e r y . s e t C a c h e a b l e ( t r u e ) . This call allows the query to look for existing cache results or add its results to the cache when it is executed.
Note
The query cache does not cache the state of the actual entities in the cache; it caches only identifier values and results of value type. For this reaso, the query cache should always be used in conjunction with the second-level cache for those entities expected to be cached as part of a query result cache (just as with collection caching).
If you want to force the query cache to refresh one of its regions (disregard any cached results it finds there) you can use o r g . h i b e r n a t e . Q u e r y . s e t C a c h e M o d e ( C a c h e M o d e . R E F R E S H ) . In conjunction with the region you have defined for the given query, Hibernate will selectively force the results cached in that particular region to be refreshed. This is particularly useful in cases where underlying data may have been updated via a separate process and is a far more efficient alternative to bulk eviction of the region via o r g . h i b e r n a t e . S e s s i o n F a c t o r y . e v i c t Q u e r i e s ( ) .
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
189/215
12/30/13
There are three ways to get benefits from this new improvement:
20.6.1. 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. To fully understand the relational structure and performance characteristics, we must also consider the structure of the primary key that is used by Hibernate to update or delete collection rows. This suggests the following classification: indexed collections sets bags All indexed collections (maps, lists, and arrays) have a primary key consisting of the < k e y > and < i n d e x > columns. In this case, collection updates are extremely efficient. The primary key can be efficiently indexed and a particular row can be efficiently located when Hibernate tries to update or delete it.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
190/215
12/30/13
case. Bags are the worst case since they permit duplicate element values and, as they have no index column, no primary key can be defined. Hibernate has no way of distinguishing between duplicate rows. Hibernate resolves this problem by completely removing in a single D E L E T E and recreating the collection whenever it changes. This can be inefficient. For a one-to-many association, the "primary key" may not be the physical primary key of the database table. Even in this case, the above classification is still useful. It reflects how Hibernate "locates" individual rows of the collection.
20.6.2. Lists, maps, idbags and sets are the most efficient collections to update
From the discussion above, it should be clear that indexed collections and sets allow the most efficient operation in terms of adding, removing and updating elements. There is, arguably, one more advantage that indexed collections have over sets for many-to-many associations or collections of values. Because of the structure of a S e t , Hibernate does not U P D A T E a row when an element is "changed". Changes to a S e talways work via I N S E R Tand D E L E T E of individual rows. Once again, this consideration does not apply to one-to-many associations. After observing that arrays cannot be lazy, you can conclude that lists, maps and idbags are the most performant (non-inverse) collection types, with sets not far behind. You can expect sets to be the most common kind of collection in Hibernate applications. This is because the "set" semantics are most natural in the relational model. However, in well-designed Hibernate domain models, most collections are in fact one-to-many associations with i n v e r s e = " t r u e " . For these associations, the update is handled by the many-to-one end of the association, and so considerations of collection update performance simply do not apply.
20.6.3. Bags and lists are the most efficient inverse collections
There is a particular case, however, in which bags, and also lists, are much more performant than sets. For a collection with i n v e r s e = " t r u e " , the standard bidirectional one-to-many relationship idiom, for example, we can add elements to a bag or list without needing to initialize (fetch) the bag elements. This is because, unlike a s e t ,C o l l e c t i o n . a d d ( ) or C o l l e c t i o n . a d d A l l ( ) must always return true for a bag or L i s t . This can make the following common code much faster:
P a r e n tp=( P a r e n t )s e s s . l o a d ( P a r e n t . c l a s s ,i d ) ; C h i l dc=n e wC h i l d ( ) ; c . s e t P a r e n t ( p ) ; p . g e t C h i l d r e n ( ) . a d d ( c ) ; / / n on e e dt of e t c ht h ec o l l e c t i o n ! s e s s . f l u s h ( ) ;
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
191/215
12/30/13
metrics
in
two
ways.
Your
first
option
is
to
call
Hibernate can also use JMX to publish metrics if you enable the S t a t i s t i c s S e r v i c e MBean. You can enable a single MBean for all your S e s s i o n F a c t o r y or one per factory. See the following code for minimalistic configuration examples:
/ /M B e a ns e r v i c er e g i s t r a t i o nf o ras p e c i f i cS e s s i o n F a c t o r y H a s h t a b l et b=n e wH a s h t a b l e ( ) ; t b . p u t ( " t y p e " ," s t a t i s t i c s " ) ; t b . p u t ( " s e s s i o n F a c t o r y " ," m y F i n a n c i a l A p p " ) ; O b j e c t N a m eo n=n e wO b j e c t N a m e ( " h i b e r n a t e " ,t b ) ;/ /M B e a no b j e c tn a m e S t a t i s t i c s S e r v i c es t a t s=n e wS t a t i s t i c s S e r v i c e ( ) ;/ /M B e a ni m p l e m e n t a t i o n s t a t s . s e t S e s s i o n F a c t o r y ( s e s s i o n F a c t o r y ) ;/ /B i n dt h es t a t st oaS e s s i o n F a c t o r y s e r v e r . r e g i s t e r M B e a n ( s t a t s ,o n ) ;/ /R e g i s t e rt h eM b e a no nt h es e r v e r / /M B e a ns e r v i c er e g i s t r a t i o nf o ra l lS e s s i o n F a c t o r y ' s H a s h t a b l et b=n e wH a s h t a b l e ( ) ; t b . p u t ( " t y p e " ," s t a t i s t i c s " ) ; t b . p u t ( " s e s s i o n F a c t o r y " ," a l l " ) ; O b j e c t N a m eo n=n e wO b j e c t N a m e ( " h i b e r n a t e " ,t b ) ;/ /M B e a no b j e c tn a m e S t a t i s t i c s S e r v i c es t a t s=n e wS t a t i s t i c s S e r v i c e ( ) ;/ /M B e a ni m p l e m e n t a t i o n s e r v e r . r e g i s t e r M B e a n ( s t a t s ,o n ) ;/ /R e g i s t e rt h eM B e a no nt h es e r v e r
You can activate and deactivate the monitoring for a S e s s i o n F a c t o r y : at configuration time, set h i b e r n a t e . g e n e r a t e _ s t a t i s t i c sto f a l s e at runtime:
s f . g e t S t a t i s t i c s ( ) . s e t S t a t i s t i c s E n a b l e d ( t r u e )
or
h i b e r n a t e S t a t s B e a n . s e t S t a t i s t i c s E n a b l e d ( t r u e )
Statistics can be reset programmatically using the c l e a r ( ) method. A summary can be sent to a logger (info level) using the l o g S u m m a r y ( )method.
20.7.2. Metrics
Hibernate provides a number of metrics, from basic information to more specialized information that is only relevant in certain scenarios. All available counters are described in the S t a t i s t i c sinterface API, in three categories: Metrics related to the general S e s s i o n usage, such as number of open sessions, retrieved JDBC connections, etc. Metrics related to the entities, collections, queries, and caches as a whole (aka global metrics). Detailed metrics related to a particular entity, collection, query or cache region. For example, you can check the cache hit, miss, and put ratio of entities, collections and queries, and the average time a query needs. Be aware that the number of milliseconds is subject to approximation in Java. Hibernate is tied to the JVM precision and on some platforms this might only be accurate to 10 seconds. Simple getters are used to access the global metrics (i.e. not tied to a particular entity, collection, cache region, etc.). You can access the metrics of a particular entity, collection or cache region through its name, and through its HQL or SQL representation for queries. Please refer to the S t a t i s t i c s ,
E n t i t y S t a t i s t i c s , C o l l e c t i o n S t a t i s t i c s , S e c o n d L e v e l C a c h e S t a t i s t i c s ,
and
Q u e r y S t a t i s t i c s API
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
192/215
12/30/13
You can work on all entities, collections, queries and region caches, by retrieving the list of names of entities, collections, queries and region caches using the following methods:
g e t Q u e r i e s ( ) , g e t E n t i t y N a m e s ( ) ,g e t C o l l e c t i o n R o l e N a m e s ( ) , and g e t S e c o n d L e v e l C a c h e R e g i o n N a m e s ( ) .
Please refer to the Hibernate Tools package documentation for more information. However, the Hibernate main package comes bundled with an integrated tool : SchemaExport aka
h b m 2 d d l .It can even be used from "inside" Hibernate.
Some tags also accept a n o t n u l l attribute for generating a N O TN U L L constraint on table columns, and au n i q u eattribute for generating U N I Q U Econstraint on table columns.
< m a n y t o o n en a m e = " b a r "c o l u m n = " b a r I d "n o t n u l l = " t r u e " / > < e l e m e n tc o l u m n = " s e r i a l N u m b e r "t y p e = " l o n g "n o t n u l l = " t r u e "u n i q u e = " t r u e " / >
Au n i q u e k e y attribute can be used to group columns in a single, unique key constraint. The attribute overrides the name of any generated unique key constraint.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
193/215
12/30/13
An i n d e x attribute specifies the name of an index that will be created using the mapped column or columns. Multiple columns can be grouped into the same index by simply specifying the same index name.
< p r o p e r t yn a m e = " l a s t N a m e "i n d e x = " C u s t N a m e " / > < p r o p e r t yn a m e = " f i r s t N a m e "i n d e x = " C u s t N a m e " / >
Af o r e i g n k e yattribute can be used to override the name of any generated foreign key constraint.
< m a n y t o o n en a m e = " b a r "c o l u m n = " b a r I d "f o r e i g n k e y = " F K F o o B a r " / >
Many mapping elements also accept a child < c o l u m n > element. This is particularly useful for mapping multi-column types:
< p r o p e r t yn a m e = " n a m e "t y p e = " m y . c u s t o m t y p e s . N a m e " / > < c o l u m nn a m e = " l a s t "n o t n u l l = " t r u e "i n d e x = " b a r _ i d x "l e n g t h = " 3 0 " / > < c o l u m nn a m e = " f i r s t "n o t n u l l = " t r u e "i n d e x = " b a r _ i d x "l e n g t h = " 2 0 " / > < c o l u m nn a m e = " i n i t i a l " / > < / p r o p e r t y >
The d e f a u l t attribute allows you to 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.
< p r o p e r t yn a m e = " c r e d i t s "t y p e = " i n t e g e r "i n s e r t = " f a l s e " > < c o l u m nn a m e = " c r e d i t s "d e f a u l t = " 1 0 " / > < / p r o p e r t y > < v e r s i o nn a m e = " v e r s i o n "t y p e = " i n t e g e r "i n s e r t = " f a l s e " > < c o l u m nn a m e = " v e r s i o n "d e f a u l t = " 0 " / > < / p r o p e r t y >
The s q l t y p e attribute allows the user to override the default mapping of a Hibernate type to SQL datatype.
< p r o p e r t yn a m e = " b a l a n c e "t y p e = " f l o a t " > < c o l u m nn a m e = " b a l a n c e "s q l t y p e = " d e c i m a l ( 1 3 , 3 ) " / > < / p r o p e r t y >
Interpretation column length column decimal precision column decimal scale specifies that the column should be non-nullable specifies that the column should have a unique constraint specifies the name of a (multi-column) index specifies the name of a multi-column unique constraint specifies the name of the foreign key constraint generated for an association, for a < o n e t o o n e > , < m a n y t o o n e > , < k e y > , or
< m a n y t o m a n y > mapping element. Note that i n v e r s e = " t r u e " sides
f o r e i g n k e y f o r e i g n _ k e y _ n a m e
overrides the default column type (attribute of < c o l u m n > element only) specify a default value for the column create an SQL check constraint on either column or table
The < c o m m e n t >element allows you to specify comments for the generated schema.
< c l a s sn a m e = " C u s t o m e r "t a b l e = " C u r C u s t " > < c o m m e n t > C u r r e n tc u s t o m e r so n l y < / c o m m e n t > . . . < / c l a s s > < p r o p e r t yn a m e = " b a l a n c e " > < c o l u m nn a m e = " b a l " > < c o m m e n t > B a l a n c ei nU S D < / c o m m e n t > < / c o l u m n > < / p r o p e r t y >
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
194/215
12/30/13
supported.
Description do not output the script to stdout only drop the tables only create the tables do not export to the database output the ddl script to a file select a N a m i n g S t r a t e g y read Hibernate configuration from an XML file read database properties from a file format the generated SQL nicely in the script set an end of line delimiter for the script
21.1.3. Properties
Database properties can be specified: as system properties with D <property> in h i b e r n a t e . p r o p e r t i e s in a named properties file with p r o p e r t i e s The needed properties are:
Description jdbc driver class jdbc url database user user password dialect
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
195/215
12/30/13
Description do not output the script to stdout do not export the script to the database select a N a m i n g S t r a t e g y read database properties from a file specify a . c f g . x m lfile
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
196/215
12/30/13
< / t a r g e t >
22.1.2. Configuration
By default, no configuration is necessary. The D e f a u l t group is validated on entity insert and update and the database model is updated accordingly based on the D e f a u l tgroup as well. You can customize the Bean Validation integration by setting the validation mode. Use the j a v a x . p e r s i s t e n c e . v a l i d a t i o n . m o d e property and set it up for example in your p e r s i s t e n c e . x m l file or your h i b e r n a t e . c f g . x m lfile. Several options are possible:
a u t o (default): enable integration between Bean Validation and Hibernate (callback and ddl
raised if no Bean Validation provider is present in the classpath. This value is not defined by the Java Persistence spec and is specific to Hibernate.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
197/215
12/30/13
Note
You can use both c a l l b a c k and d d l together by setting the property to
c a l l b a c k ,d l l
< p e r s i s t e n c e. . . > < p e r s i s t e n c e u n i t. . . > . . . < p r o p e r t i e s > < p r o p e r t yn a m e = " j a v a x . p e r s i s t e n c e . v a l i d a t i o n . m o d e " v a l u e = " c a l l b a c k ,d d l " / > < / p r o p e r t i e s > < / p e r s i s t e n c e u n i t > < / p e r s i s t e n c e >
This is equivalent to a u t o except that if no Bean Validation provider is present, an exception is raised.
If you want to validate different groups during insertion, update and deletion, use:
j a v a x . p e r s i s t e n c e . v a l i d a t i o n . g r o u p . p r e p e r s i s t : groups validated when an entity is about to be
persisted (default to D e f a u l t )
j a v a x . p e r s i s t e n c e . v a l i d a t i o n . g r o u p . p r e u p d a t e : groups validated when an entity is about to be
updated (default to D e f a u l t )
j a v a x . p e r s i s t e n c e . v a l i d a t i o n . g r o u p . p r e r e m o v e : groups validated when an entity is about to be
schema (default to D e f a u l t ) Each property accepts the fully qualified class names of the groups validated separated by a comma (,)
< p e r s i s t e n c e. . . > < p e r s i s t e n c e u n i t. . . > . . . < p r o p e r t i e s > < p r o p e r t yn a m e = " j a v a x . p e r s i s t e n c e . v a l i d a t i o n . g r o u p . p r e u p d a t e " v a l u e = " j a v a x . v a l i d a t i o n . g r o u p . D e f a u l t ,c o m . a c m e . g r o u p . S t r i c t " / > < p r o p e r t yn a m e = " j a v a x . p e r s i s t e n c e . v a l i d a t i o n . g r o u p . p r e r e m o v e " v a l u e = " c o m . a c m e . g r o u p . O n D e l e t e " / > < p r o p e r t yn a m e = " o r g . h i b e r n a t e . v a l i d a t o r . g r o u p . d d l " v a l u e = " c o m . a c m e . g r o u p . D D L " / > < / p r o p e r t i e s > < / p e r s i s t e n c e u n i t > < / p e r s i s t e n c e >
Note
You can set these properties in h i b e r n a t e . c f g . x m l , h i b e r n a t e . p r o p e r t i e s or programmatically.
This exception is wrapped in a R o l l b a c k E x c e p t i o n when the violation happens at commit time. Otherwise the C o n s t r a i n t V i o l a t i o n E x c e p t i o n is returned (for example when calling f l u s h ( ) . Note that generally, catchable violations are validated at a higher level (for example in Seam / JSF 2 via the JSF Bean Validation integration or in your business layer by explicitly calling Bean Validation). An application code will rarely be looking for a C o n s t r a i n t V i o l a t i o n E x c e p t i o n raised by Hibernate. This exception should be treated as fatal and the persistence context should be discarded (E n t i t y M a n a g e r or
S e s s i o n ).
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
198/215
12/30/13
with @ D i g i t s:) ) These constraints can be declared directly on the entity properties or indirectly by using constraint composition. For more information check the Hibernate Validator reference http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html/ documentation at
22.2.1. Description
Full text search engines like Apache Lucene are a very powerful technology to bring free text/efficient queries to applications. If suffers several mismatches when dealing with a object domain model (keeping the index up to date, mismatch between the index structure and the domain model, querying mismatch...) Hibernate Search indexes your domain model thanks to a few annotations, takes care of the database / index synchronization and brings you back regular managed objects from free text queries. Hibernate Search is using Apache Lucene under the covers.
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. We will explain how to use a bidirectional one-to-many association with cascades to model a parent/child relationship efficiently and elegantly.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
199/215
12/30/13
Hibernate would issue two SQL statements: an I N S E R Tto create the record for c an U P D A T Eto create the link from pto c This is not only inefficient, but also violates any N O TN U L Lconstraint on the p a r e n t _ i dcolumn. You can fix the nullability constraint violation by specifying n o t n u l l = " t r u e "in the collection mapping:
< s e tn a m e = " c h i l d r e n " > < k e yc o l u m n = " p a r e n t _ i d "n o t n u l l = " t r u e " / > < o n e t o m a n yc l a s s = " C h i l d " / > < / s e t >
However, this is not the recommended solution. The underlying cause of this behavior is that the link (the foreign key p a r e n t _ i d ) from p to c is not considered part of the state of the C h i l dobject and is therefore not created in the I N S E R T . The solution is to make the link part of the C h i l dmapping.
< m a n y t o o n en a m e = " p a r e n t "c o l u m n = " p a r e n t _ i d "n o t n u l l = " t r u e " / >
You also need to add the p a r e n tproperty to the C h i l dclass. Now that the C h i l dentity is managing the state of the link, we tell the collection not to update the link. We use the i n v e r s eattribute to do this:
< s e tn a m e = " c h i l d r e n "i n v e r s e = " t r u e " > < k e yc o l u m n = " p a r e n t _ i d " / > < o n e t o m a n yc l a s s = " C h i l d " / > < / s e t >
Only one SQL I N S E R Twould now be issued. You could also create an a d d C h i l d ( )method of P a r e n t .
p u b l i cv o i da d d C h i l d ( C h i l dc ){ c . s e t P a r e n t ( t h i s ) ; c h i l d r e n . a d d ( c ) ; }
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
200/215
12/30/13
< / s e t >
Similarly, we do not need to iterate over the children when saving or deleting a P a r e n t . The following removes pand all its children from the database.
P a r e n tp=( P a r e n t )s e s s i o n . l o a d ( P a r e n t . c l a s s ,p i d ) ; s e s s i o n . d e l e t e ( p ) ; s e s s i o n . f l u s h ( ) ;
will not remove c from the database. In this case, it will only remove the link to pand cause a N O TN U L L constraint violation. You need to explicitly d e l e t e ( )the C h i l d .
P a r e n tp=( P a r e n t )s e s s i o n . l o a d ( P a r e n t . c l a s s ,p i d ) ; C h i l dc=( C h i l d )p . g e t C h i l d r e n ( ) . i t e r a t o r ( ) . n e x t ( ) ; p . g e t C h i l d r e n ( ) . r e m o v e ( c ) ; s e s s i o n . d e l e t e ( c ) ; s e s s i o n . f l u s h ( ) ;
In our case, a C h i l d cannot exist without its parent. So if we remove a C h i l d from the collection, we do want it to be deleted. To do this, we must use c a s c a d e = " a l l d e l e t e o r p h a n " .
< s e tn a m e = " c h i l d r e n "i n v e r s e = " t r u e "c a s c a d e = " a l l d e l e t e o r p h a n " > < k e yc o l u m n = " p a r e n t _ i d " / > < o n e t o m a n yc l a s s = " C h i l d " / > < / s e t >
Even though the collection mapping specifies i n v e r s e = " t r u e " , cascades are still processed by iterating the collection elements. If you need an object be saved, deleted or updated by cascade, you must add it to the collection. It is not enough to simply call s e t P a r e n t ( ) .
This may be suitable for the case of a generated identifier, but what about assigned identifiers and composite identifiers? This is more difficult, since Hibernate cannot 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. In this case, Hibernate will either use the timestamp or version property, or will actually query the second-level cache or, worst case, the database, to see if the row exists.
23.5. Conclusion
The sections we have just covered can be a bit confusing. However, in practice, it all works out nicely. Most Hibernate applications use the parent/child pattern in many places. We mentioned an alternative in the first paragraph. None of the above issues exist in the case of < c o m p o s i t e e l e m e n t > mappings, which have exactly the semantics of a parent/child relationship. Unfortunately, there are two big limitations with composite element classes: composite elements cannot own collections and they should not be the child of any entity other than the unique parent.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
201/215
12/30/13
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
202/215
12/30/13
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
203/215
12/30/13
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
204/215
12/30/13
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
205/215
12/30/13
25.1. Employer/Employee
The following model of the relationship between E m p l o y e r and E m p l o y e e uses an entity class (E m p l o y m e n t ) to represent the association. You can do this when there might be more than one period of employment for the same two parties. Components are used to model monetary values and employee names.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
206/215
12/30/13
25.2. Author/Work
Consider the following model of the relationships between W o r k ,A u t h o rand P e r s o n . In the example, the relationship between W o r k and A u t h o r is represented as a many-to-many association and the relationship between A u t h o r and P e r s o n is represented as one-to-one association. Another possibility would be to have A u t h o rextend P e r s o n .
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
207/215
12/30/13
There are four tables in this mapping: w o r k s ,a u t h o r s and p e r s o n s hold work, author and person data respectively. a u t h o r _ w o r k is an association table linking authors to works. Here is the table schema, as generated by S c h e m a E x p o r t :
c r e a t et a b l ew o r k s( i dB I G I N Tn o tn u l lg e n e r a t e db yd e f a u l ta si d e n t i t y , t e m p oF L O A T , g e n r eV A R C H A R ( 2 5 5 ) , t e x tI N T E G E R , t i t l eV A R C H A R ( 2 5 5 ) , t y p eC H A R ( 1 )n o tn u l l , p r i m a r yk e y( i d ) ) c r e a t et a b l ea u t h o r _ w o r k( a u t h o r _ i dB I G I N Tn o tn u l l , w o r k _ i dB I G I N Tn o tn u l l , p r i m a r yk e y( w o r k _ i d ,a u t h o r _ i d ) ) c r e a t et a b l ea u t h o r s( i dB I G I N Tn o tn u l lg e n e r a t e db yd e f a u l ta si d e n t i t y , a l i a sV A R C H A R ( 2 5 5 ) , p r i m a r yk e y( i d ) ) c r e a t et a b l ep e r s o n s( i dB I G I N Tn o tn u l lg e n e r a t e db yd e f a u l ta si d e n t i t y , n a m eV A R C H A R ( 2 5 5 ) , p r i m a r yk e y( i d ) ) a l t e rt a b l ea u t h o r s a d dc o n s t r a i n ta u t h o r s F K 0f o r e i g nk e y( i d )r e f e r e n c e sp e r s o n s a l t e rt a b l ea u t h o r _ w o r k a d dc o n s t r a i n ta u t h o r _ w o r k F K 0f o r e i g nk e y( a u t h o r _ i d )r e f e r e n c e sa u t h o r s a l t e rt a b l ea u t h o r _ w o r k a d dc o n s t r a i n ta u t h o r _ w o r k F K 1f o r e i g nk e y( w o r k _ i d )r e f e r e n c e sw o r k s
25.3. Customer/Order/Product
In this section we consider a model of the relationships between C u s t o m e r , O r d e r , L i n e I t e m and
P r o d u c t . There is a one-to-many association between C u s t o m e r and O r d e r , but how can you represent O r d e r/ L i n e I t e m/ P r o d u c t ? In the example, L i n e I t e m is mapped as an association class representing
the many-to-many association between O r d e r and P r o d u c t . In Hibernate this is called a composite element.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
208/215
12/30/13
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
209/215
12/30/13
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
210/215
12/30/13
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
211/215
12/30/13
Place each class mapping in its own file: Do not use a single monolithic mapping document. Map c o m . e g . F o o in the file c o m / e g / F o o . h b m . x m l . This makes sense, particularly in a team environment. Load mappings as resources: Deploy the mappings along with the classes they map. Consider externalizing query strings: This is recommended if your queries call non-ANSI-standard SQL functions. Externalizing the query strings to mapping files will make the application more portable. Use bind variables. As in JDBC, always replace non-constant values by "?". Do not use string manipulation to bind a non-constant value in a query. You should also consider using named parameters in queries.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
212/215
12/30/13
map This
it as a approach
implementing implementing
transformations to/from a Hibernate type. Use hand-coded JDBC in bottlenecks: In performance-critical areas of the system, some kinds of operations might benefit from direct JDBC. Do not assume, however, that JDBC is necessarily faster. Please wait until you know something is a bottleneck. If you need to use direct JDBC, you can open a Hibernate S e s s i o n , wrap your JDBC operation as a o r g . h i b e r n a t e . j d b c . W o r k object and using that JDBC connection. This way you can still use the same transaction strategy and underlying connection provider. Understand S e s s i o nflushing: Sometimes the Session synchronizes its persistent state with the database. Performance will be affected if this process occurs too often. You can sometimes minimize unnecessary flushing by disabling automatic flushing, or even by changing the order of queries and other operations within a particular transaction. In a three tiered architecture, consider using detached objects: When using a servlet/session bean architecture, you can pass persistent objects loaded in the session bean to and from the servlet/JSP layer. Use a new session to service each request. Use
S e s s i o n . m e r g e ( )or S e s s i o n . s a v e O r U p d a t e ( )to synchronize objects with the database.
In a two tiered architecture, consider using long persistence contexts: Database Transactions have to be as short as possible for best scalability. However, it is often necessary to implement long running application transactions , a single unit-of-work from the point of view of a user. An application transaction might span several client request/response cycles. It is common to use detached objects to implement application transactions. An appropriate alternative in a two tiered architecture, is to maintain a single open persistence contact session for the whole life cycle of the application transaction. Then simply disconnect from the JDBC connection at the end of each request and reconnect at the beginning of the subsequent request. Never share a single session across more than one application transaction or you will be working with stale data. Do not treat exceptions as recoverable: This is more of a necessary practice than a "best" practice. When an exception occurs, roll back the T r a n s a c t i o n and close the S e s s i o n . If you do not do this, Hibernate cannot guarantee that inmemory state accurately represents the persistent state. For example, do not use S e s s i o n . l o a d ( ) to determine if an instance with the given identifier exists on the database; use S e s s i o n . g e t ( ) or a query instead. Prefer lazy fetching for associations: Use eager fetching sparingly. Use proxies and lazy collections for most associations to classes that are not likely to be completely held in the second-level cache. For associations to cached classes, where there is an a extremely high probability of a cache hit, explicitly disable eager fetching using
l a z y = " f a l s e " . When join fetching is appropriate to a particular use case, use a query with a l e f tj o i nf e t c h .
Use the open session in v iew pattern, or a disciplined assem bly phase to avoid problems with unfetched data: Hibernate frees the developer from writing tedious Data Transfer Objects (DTO). In a traditional EJB architecture, DTOs serve dual purposes: first, they work around the problem that entity beans are not serializable; second, 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. Hibernate eliminates the first purpose. Unless you are prepared to hold the persistence context (the session) open across the view rendering process, 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. This is not a limitation of Hibernate. It is a fundamental requirement of safe transactional data access. Consider abstracting your business logic from Hibernate: Hide Hibernate data-access code behind an interface. Combine the DAO and Thread Local Session patterns. You can even have some classes persisted by handcoded JDBC associated to Hibernate via a U s e r T y p e . This advice is, however, intended for "sufficiently large" applications. It is not appropriate for an application with five tables. Do not use exotic association mappings: Practical test cases for real many-to-many associations are rare. Most of the time you need additional information stored in the "link table". In this case, it is much better to use two one-tomany associations to an intermediate link class. In fact, most associations are one-to-many and many-to-one. For this reason, you should proceed cautiously when using any other association style. Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
213/215
12/30/13
27.2. Dialect
The first line of portability for Hibernate is the dialect, which is a specialization of the
o r g . h i b e r n a t e . d i a l e c t . D i a l e c t contract. A dialect encapsulates all the differences in how Hibernate
must communicate with a particular database to accomplish some task like getting a sequence value or structuring a SELECT query. Hibernate bundles a wide range of dialects for many of the most popular databases. If you find that your particular database is not among them, it is not terribly difficult to write your own.
The basic contract here is that if the resolver 'understands' the given database metadata then it returns the corresponding Dialect; if not it returns null and the process continues to the next resolver. The signature also identifies o r g . h i b e r n a t e . e x c e p t i o n . J D B C C o n n e c t i o n E x c e p t i o n as possibly being thrown. A JDBCConnectionException here is interpreted to imply a "non transient" (aka non-recoverable) connection problem and is used to indicate an immediate stop to resolution attempts. All other exceptions result in a warning and continuing on to the next resolver. The cool part about these resolvers is that users can also register their own custom resolvers which will be processed ahead of the built-in Hibernate ones. This might be useful in a number of different situations: it allows easy integration for auto-detection of dialects beyond those shipped with HIbernate itself; it allows you to specify to use a custom dialect when a particular database is recognized; etc. To register one or more resolvers, simply specify them (seperated by commas, tabs or spaces) using the 'hibernate.dialect_resolvers' configuration setting (see the D I A L E C T _ R E S O L V E R S constant on
o r g . h i b e r n a t e . c f g . E n v i r o n m e n t ).
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
214/215
12/30/13
Note
Hibernate was changed slightly once the implication of this was better understood so that the insert is delayed in cases where that is feasible.
The underlying issue is that the actual semanctics of the application itself changes in these cases. Starting with version 3.2.3, Hibernate comes with a set of enhanced identifier generators targetting portability in a much different way.
Note
There are specifically 2 bundled enhancedgenerators:
o r g . h i b e r n a t e . i d . e n h a n c e d . S e q u e n c e S t y l e G e n e r a t o r o r g . h i b e r n a t e . i d . e n h a n c e d . T a b l e G e n e r a t o r
The idea behind these generators is to port the actual semantics of the identifer value generation to the different databases. For example, the o r g . h i b e r n a t e . i d . e n h a n c e d . S e q u e n c e S t y l e G e n e r a t o r mimics the behavior of a sequence on databases which do not support sequences by using a table.
SQL functions can be referenced in many ways by users. However, not all databases support the same set of functions. Hibernate, provides a means of mapping a logical function name to a delegate which knows how to render that particular function, perhaps even using a totally different physical function call.
Important
Technically this function registration is
o r g . h i b e r n a t e . d i a l e c t . f u n c t i o n . S Q L F u n c t i o n R e g i s t r y
intended to allow users to provide custom function definitions without having to provide a custom dialect. This specific behavior is not fully completed as of yet. It is sort of implemented such that users can programatically register functions with the o r g . h i b e r n a t e . c f g . C o n f i g u r a t i o n and those functions will be recognized for HQL.
References
[PoEAA] Patterns of Enterprise Application Architecture. 0-321-12742-0. Martin Fowler. Copyright 2003 Pearson Education, Inc.. Addison-Wesley Publishing Company. [JPwH] Java Persistence with Hibernate. Second Edition of Hibernate in Action. 1-932394-88-5. http://www.manning.com/bauer2 . Christian Bauer and Gavin King. Copyright 2007 Manning Publications Co.. Manning Publications Co..
docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e741
215/215