From hibernate-commits at lists.jboss.org Thu Jan 29 14:56:07 2009 Content-Type: multipart/mixed; boundary="===============2081375298519546727==" MIME-Version: 1.0 From: hibernate-commits at lists.jboss.org To: hibernate-commits at lists.jboss.org Subject: [hibernate-commits] Hibernate SVN: r15830 - core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/content. Date: Thu, 29 Jan 2009 14:56:07 -0500 Message-ID: --===============2081375298519546727== Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Author: steve.ebersole(a)jboss.com Date: 2009-01-29 14:56:06 -0500 (Thu, 29 Jan 2009) New Revision: 15830 Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/architecture.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/association_mapping.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/basic_mapping.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/batch.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/best_practices.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/collection_mapping.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/component_mapping.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/configuration.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/events.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/example_mappings.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/example_parentchild.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/example_weblog.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/filters.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/inheritance_mapping.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/performance.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/persistent_classes.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/preface.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/query_criteria.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/query_hql.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/query_sql.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/session_api.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/toolset_guide.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/transactions.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/tutorial.xml core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/con= tent/xml.xml Log: HHH-3742 : doc corrections Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/architecture.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/architecture.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/architecture.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -33,7 +33,7 @@ Overview = - A (very) high-level view of the Hibernate architecture: + The diagram below provides a high-level view of the Hibernate = architecture: = @@ -45,15 +45,21 @@ = + = + - This diagram shows Hibernate using the database and configurat= ion data to - provide persistence services (and persistent objects) to the a= pplication. + We do not have the scope in this document to provide a more de= tailed view of all the runtime architectures available; = + Hibernate is flexible and supports several different approache= s. We will, however, + show the two extremes: "minimal" architecture and "comprehensi= ve" architecture. = + + + + This next diagram illustrates how Hibernate utilizes database = and configuration data to + provide persistence services, and persistent objects, to the a= pplication. = - - We would like to show a more detailed view of the runtime arch= itecture. - Unfortunately, Hibernate is flexible and supports several appr= oaches. We will - show the two extremes. The "lite" architecture has the applica= tion + + The "minimal" architecture has the application provide its own JDBC connections and manage its own transactio= ns. This approach uses a minimal subset of Hibernate's APIs: @@ -67,9 +73,11 @@ = - - The "full cream" architecture abstracts the application away f= rom the - underlying JDBC/JTA APIs and lets Hibernate take care of the d= etails. + = + + + The "comprehensive" architecture abstracts the application awa= y from the + underlying JDBC/JTA APIs and allows Hibernate to manage the de= tails. = @@ -82,18 +90,18 @@ = - Heres some definitions of the objects in the diagrams: + Here are some definitions of the objects depicted in the diagr= ams: = SessionFactory (org.hibernate.SessionFa= ctory) - A threadsafe (immutable) cache of compiled map= pings for a single database. + A threadsafe, immutable cache of compiled mapp= ings for a single database. A factory for Session and a= client of - ConnectionProvider. Might h= old an optional (second-level) - cache of data that is reusable between transac= tions, at a - process- or cluster-level. + ConnectionProvider, SessionFactory can hold an optional (second-level) + cache of data that is reusable between transac= tions at a + process, or cluster, level. @@ -102,9 +110,9 @@ A single-threaded, short-lived object represen= ting a conversation between - the application and the persistent store. Wrap= s a JDBC connection. Factory - for Transaction. Holds a ma= ndatory (first-level) cache - of persistent objects, used when navigating th= e object graph or looking up + the application and the persistent store. It w= raps a JDBC connection and is a factory + for Transaction. S= ession holds a mandatory first-level cache + of persistent objects that are used when navig= ating the object graph or looking up objects by identifier. @@ -114,10 +122,9 @@ Short-lived, single threaded objects containin= g persistent state and business - function. These might be ordinary JavaBeans/PO= JOs, the only special thing about - them is that they are currently associated wit= h (exactly one) - Session. As soon as the Session is closed, - they will be detached and free to use in any a= pplication layer (e.g. directly + function. These can be ordinary JavaBeans/POJO= s. They are associated with exactly one + Session. Once the = Session is closed, + they will be detached and free to use in any a= pplication layer (for example, directly as data transfer objects to and from presentat= ion). @@ -128,7 +135,7 @@ Instances of persistent classes that are not c= urrently associated with a Session. They may have been= instantiated by - the application and not (yet) persisted or the= y may have been instantiated by a + the application and not yet persisted, or they= may have been instantiated by a closed Session. @@ -138,11 +145,11 @@ (Optional) A single-threaded, short-lived obje= ct used by the application to - specify atomic units of work. Abstracts applic= ation from underlying JDBC, + specify atomic units of work. It abstracts the= application from the underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases.= However, transaction demarcation, either using the underlying API or Tr= ansaction, is never - optional! + optional. @@ -150,9 +157,9 @@ ConnectionProvider (org.hibernate.conne= ction.ConnectionProvider) - (Optional) A factory for (and pool of) JDBC co= nnections. Abstracts application from + (Optional) A factory for, and pool of, JDBC co= nnections. It abstracts the application from underlying Datasource or DriverManager. - Not exposed to application, but can be extende= d/implemented by the developer. + It is not exposed to application, but it can b= e extended and/or implemented by the developer. @@ -160,8 +167,8 @@ TransactionFactory (org.hibernate.Trans= actionFactory) - (Optional) A factory for Transaction<= /literal> instances. Not exposed to the - application, but can be extended/implemented b= y the developer. + (Optional) A factory for Transaction<= /literal> instances. It is not exposed to the + application, but it can be extended and/or imp= lemented by the developer. @@ -169,7 +176,7 @@ Extension Interfaces - Hibernate offers many optional extension inter= faces you can implement to customize + Hibernate offers a range of optional extension= interfaces you can implement to customize the behavior of your persistence layer. See th= e API documentation for details. @@ -178,18 +185,18 @@ = - Given a "lite" architecture, the application bypasses the + Given a "minimal" architecture, the application bypasses the Transaction/TransactionFactory and/or - ConnectionProvider APIs to talk to JTA or J= DBC directly. + ConnectionProvider APIs to communicate with= JTA or JDBC directly. = Instance states - An instance of a persistent classes may be in one of three dif= ferent states, - which are defined with respect to a persistence cont= ext. - The Hibernate Session object is the persist= ence context: + An instance of a persistent class can be in one of three diffe= rent states. These states are + defined in relation to a persistence context. + The Hibernate Session object is the persist= ence context. The three different states are as follows: = @@ -197,9 +204,9 @@ transient - The instance is not, and has never been associated= with - any persistence context. It has no persistent iden= tity - (primary key value). + The instance is not associated with + any persistence context. It has no persistent iden= tity or + primary key value. @@ -209,11 +216,11 @@ The instance is currently associated with a persis= tence = context. It has a persistent identity (primary key= value) - and, perhaps, a corresponding row in the database.= For a + and can have a corresponding row in the database. = For a particular persistence context, Hibernate = guarantees that persistent id= entity - is equivalent to Java identity (in-memory location= of the - object). + is equivalent to Java identity in relation to the = in-memory location of the + object. @@ -224,9 +231,9 @@ The instance was once associated with a persistence context, but that context was closed, or the insta= nce was serialized to another process. It has a persis= tent = - identity and, perhaps, a corresponding row in the = database. - For detached instances, Hibernate makes no guarant= ees = - about the relationship between persistent identity= and + identity and can have a corresponding row in the d= atabase. + For detached instances, Hibernate does not guarant= ee = + the relationship between persistent identity and Java identity. @@ -238,36 +245,36 @@ JMX Integration = - JMX is the J2EE standard for management of Java components. Hi= bernate may be managed via - a JMX standard service. We provide an MBean implementation in = the distribution, + JMX is the J2EE standard for the management of Java components= . Hibernate can be managed via + a JMX standard service. AN MBean implementation is provided in= the distribution: org.hibernate.jmx.HibernateService. = - For an example how to deploy Hibernate as a JMX service on the= JBoss Application Server, - please see the JBoss User Guide. On JBoss AS, you also get the= se benefits if you deploy + For an example of how to deploy Hibernate as a JMX service on = the JBoss Application Server, + please see the JBoss User Guide. JBoss AS also provides these = benefits if you deploy using JMX: = - Session Management: The Hibernate= Session's life cycle - can be automatically bound to the scope of a JTA trans= action. This means you no - longer have to manually open and close the Se= ssion, this - becomes the job of a JBoss EJB interceptor. You also d= on't have to worry about - transaction demarcation in your code anymore (unless y= ou'd like to write a portable - persistence layer of course, use the optional Hibernat= e Transaction + Session Management: the Hibernate= Session's life cycle + can be automatically bound to the scope of a JTA trans= action. This means that you no + longer have to manually open and close the Se= ssion; this + becomes the job of a JBoss EJB interceptor. You also d= o not have to worry about + transaction demarcation in your code (if you would lik= e to write a portable + persistence layer use the optional Hibernate = Transaction API for this). You call the HibernateContext<= /literal> to access a Session. - HAR deployment: Usually you deplo= y the Hibernate JMX service using a JBoss - service deployment descriptor (in an EAR and/or SAR fi= le), it supports all the usual + HAR deployment: the Hibernate JMX= service is deployed using a JBoss + service deployment descriptor in an EAR and/or SAR fil= e, as it supports all the usual configuration options of a Hibernate SessionF= actory. However, you still - have to name all your mapping files in the deployment = descriptor. If you decide to use + need to name all your mapping files in the deployment = descriptor. If you use the optional HAR deployment, JBoss will automatically = detect all mapping files in your HAR file. @@ -279,45 +286,45 @@ = - Another feature available as a JMX service are runtime Hiberna= te statistics. See - . + Another feature available as a JMX service is runtime Hibernat= e statistics. See + for more= information. = JCA Support - Hibernate may also be configured as a JCA connector. Please se= e the website for more - details. Please note that Hibernate JCA support is still consi= dered experimental. + Hibernate can also be configured as a JCA connector. Please se= e the website for more + information. Please note, however, that at this stage Hibernat= e JCA support is under development. = - Contextual Sessions + Contextual sessions - Most applications using Hibernate need some form of "contextua= l" sessions, where a given + Most applications using Hibernate need some form of "contextua= l" session, where a given session is in effect throughout the scope of a given context. = However, across applications - the definition of what constitutes a context is typically diff= erent; and different contexts + the definition of what constitutes a context is typically diff= erent; different contexts define different scopes to the notion of current. Applications= using Hibernate prior to version 3.0 tended to utilize either home-grown Th= readLocal-based contextual sessions, helper classes such as Hibernate= Util, or utilized - third-party frameworks (such as Spring or Pico) which provided= proxy/interception-based contextual sessions. + third-party frameworks, such as Spring or Pico, which provided= proxy/interception-based contextual sessions. Starting with version 3.0.1, Hibernate added the Sess= ionFactory.getCurrentSession() - method. Initially, this assumed usage of JTA transactions, where the + method. Initially, this assumed usage of JTA transactions, where the JTA transaction defined both the scope and = context of a current session. - The Hibernate team maintains that, given the maturity of the n= umerous stand-alone - JTA TransactionManager implementations out = there, most (if not all) - applications should be using JTA transactio= n management whether or not + Given the maturity of the numerous stand-alone + JTA TransactionManager implementations, mos= t, if not all, + applications should be using JTA transactio= n management, whether or not they are deployed into a J2EE container. B= ased on that, the - JTA-based contextual sessions is all you sh= ould ever need to use. + JTA-based contextual sessions are all you n= eed to use. However, as of version 3.1, the processing behind SessionFactory.getCurrentSession() is now p= luggable. To that - end, a new extension interface (org.hibernate.context= .CurrentSessionContext) - and a new configuration parameter (hibernate.current_= session_context_class) + end, a new extension interface, org.hibernate.context= .CurrentSessionContext, + and a new configuration parameter, hibernate.current_= session_context_class, have been added to allow pluggability of the scope and context= of defining current sessions. @@ -325,13 +332,13 @@ interface for a detailed discussion of its contract. It defin= es a single method, currentSession(), by which the implementati= on is responsible for tracking the current contextual session. Out-of-the-box, Hibe= rnate comes with three - implementations of this interface. + implementations of this interface: = - org.hibernate.context.JTASessionContext - current sessions + org.hibernate.context.JTASessionContext: current sessions are tracked and scoped by a JTA tra= nsaction. The processing here is exactly the same as in the older JTA-only appr= oach. See the Javadocs for details. @@ -339,41 +346,41 @@ - org.hibernate.context.ThreadLocalSessionConte= xt - current - sessions are tracked by thread of execution. Again, se= e the Javadocs for details. + org.hibernate.context.ThreadLocalSessionConte= xt:current + sessions are tracked by thread of execution. See the J= avadocs for details. - org.hibernate.context.ManagedSessionContext - current + org.hibernate.context.ManagedSessionContext: current sessions are tracked by thread of execution. However, = you are responsible to bind and unbind a Session instance = with static methods - on this class, it does never open, flush, or close a <= literal>Session. + on this class: it does not open, flush, or close a Session. = The first two implementations provide a "one session - one dat= abase transaction" programming - model, also known and used as session-per-request. The beginning + model. This is also also known and used as session-p= er-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 w= ithout JTA, you are advised to use the Hibernate Transaction API to hide t= he underlying transaction system - from your code. If you use JTA, use the JTA interfaces to dema= rcate transactions. If you + from your code. If you use JTA, you can utilize the JTA interf= aces to demarcate transactions. If you execute in an EJB container that supports CMT, transaction bou= ndaries are defined declaratively - and you don't need any transaction or session demarcation oper= ations in your code. + and you do not need any transaction or session demarcation ope= rations in your code. Refer to for more information= and code examples. = The hibernate.current_session_context_class= configuration parameter defines which org.hibernate.context.CurrentSessionCon= text implementation - should be used. Note that for backwards compatibility, if thi= s config param is not set + should be used. For backwards compatibility, if this configur= ation parameter is not set but a org.hibernate.transaction.TransactionManagerLoo= kup is configured, Hibernate will use the org.hibernate.context.JTASessi= onContext. Typically, the value of this parameter would just name the imp= lementation class to - use; for the three out-of-the-box implementations, however, th= ere are three corresponding - short names, "jta", "thread", and "managed". + use. For the three out-of-the-box implementations, however, th= ere are three corresponding + short names: "jta", "thread", and "managed". = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/association_mapping.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/association_mapping.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/association_mapping.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -33,22 +33,22 @@ Introduction = - Association mappings are the often most difficult thing to get= right. In - this section we'll go through the canonical cases one by one, = starting - with unidirectional mappings, and then considering the bidirec= tional cases. - We'll use Person and Address in all + Association mappings are often the most difficult thing to imp= lement correctly. In + this section we examine some canonical cases one by one, start= ing + with unidirectional mappings and then bidirectional cases. + We will use Person and Address in all the examples. = - We'll classify associations by whether or not they map to an inte= rvening - join table, and by multiplicity. + Associations will be classified by multiplicity and whether or no= t they map to an intervening + join table. = - Nullable foreign keys are not considered good practice in traditi= onal data - modelling, so all our examples use not null foreign keys. This is= not a - requirement of Hibernate, and the mappings will all work if you d= rop the + Nullable foreign keys are not considered to be good practice in t= raditional 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. = @@ -58,7 +58,7 @@ Unidirectional associations = - many to one + Many-to-one = A unidirectional many-to-one association = is the most = @@ -87,7 +87,7 @@ = - one to one + One-to-one = A unidirectional one-to-one association on a foreign= key @@ -116,8 +116,8 @@ = A unidirectional one-to-one association on a primary= key - usually uses a special id generator. (Notice that we've revers= ed the direction - of the association in this example.) + usually uses a special id generator In this example, however, = we have reversed the direction + of the association: = @@ -142,11 +142,11 @@ = - one to many + One-to-many = A unidirectional one-to-many association on a foreig= n key = - is a very unusual case, and is not really recommended. + is an unusual case, and is not recommended. = @@ -171,7 +171,7 @@ ]]> = - We think it's better to use a join table for this kind of asso= ciation. + You should instead use a join table for this kind of association. = @@ -182,12 +182,12 @@ Unidirectional associations with join tables = - one to many + One-to-many = A unidirectional one-to-many association on a join t= able = - is much preferred. Notice that by specifying unique= =3D"true", - we have changed the multiplicity from many-to-many to one-to-m= any. + is the preferred option. Specifying unique=3D"true", + changes the multiplicity from many-to-many to one-to-many. = @@ -216,11 +216,11 @@ = - many to one + Many-to-one = A unidirectional many-to-one association on a join t= able = - is quite common when the association is optional. + is common when the association is optional. For example: = @@ -250,11 +250,11 @@ = - one to one + One-to-one = - A unidirectional one-to-one association on a join ta= ble = - is extremely unusual, but possible. + A unidirectional one-to-one association on a join ta= ble is possible, = + but extremely unusual. = @@ -286,10 +286,10 @@ = - many to many + Many-to-many = - Finally, we have a unidirectional many-to-many assoc= iation. + Finally, here is an example of a unidirectional many= -to-many association. = @@ -322,12 +322,12 @@ Bidirectional associations = - one to many / many to one + one-to-many / many-to-one = A bidirectional many-to-one association i= s the - most common kind of association. (This is the standard parent/= child - relationship.) + most common kind of association. The following example illustr= ates the standard parent/child + relationship. = @@ -355,11 +355,11 @@ ]]> = - If you use a List (or other indexed collect= ion) you need - to set the key column of the foreign key to= not null, - and let Hibernate manage the association from the collections = side to maintain the index - of each element (making the other side virtually inverse by se= tting - update=3D"false" and insert=3D"fal= se"): + If you use a List, or other indexed collect= ion, + set the key column of the foreign key to not null. + Hibernate will manage the association from the collections sid= e to maintain the index + of each element, making the other side virtually inverse by se= tting + update=3D"false" and insert=3D"fal= se": = @@ -383,9 +383,10 @@ ]]> = - It is important that you define not-null=3D"true"= on the - <key> element of the collection m= apping if the - underlying foreign key column is NOT NULL. Don't only + If the underlying foreign key column is NOT NULL<= /literal>, it = + is important that you define not-null=3D"true" on the + <key> element of the collection m= apping. + Do not only declare not-null=3D"true" on a possible= nested <column> element, but on the <key> element. @@ -394,11 +395,11 @@ = - one to one + One-to-one = A bidirectional one-to-one association on a foreign = key - is quite common. + is common: = @@ -425,7 +426,7 @@ = A bidirectional one-to-one association on a primary = key - uses the special id generator. + uses the special id generator: = @@ -457,11 +458,11 @@ Bidirectional associations with join tables = - one to many / many to one + one-to-many / many-to-one = - A bidirectional one-to-many association on a join ta= ble. - Note that the inverse=3D"true" can go on ei= ther end of the + The following is an example of a bidirectional one-t= o-many association on a join table. + The inverse=3D"true" can go on either end o= f the association, on the collection, or on the join. = @@ -503,8 +504,8 @@ one to one = - A bidirectional one-to-one association on a join tab= le = - is extremely unusual, but possible. + A bidirectional one-to-one association on a join tab= le is possible, + but extremely unusual. = @@ -546,10 +547,10 @@ = - many to many + Many-to-many = - Finally, we have a bidirectional many-to-many associ= ation. + Here is an example of a bidirectional many-to-many a= ssociation. = @@ -589,11 +590,11 @@ = More complex association joins are extremely rare. = - Hibernate makes it possible to handle more complex situations = using + Hibernate handles more complex situations by using SQL fragments embedded in the mapping document. For example, i= f a table with historical account information data defines = accountNumber, effectiveEndDate = - and effectiveStartDatecolumns, mapped as fo= llows: + and effectiveStartDatecolumns, it would be = mapped as follows: = @@ -606,8 +607,8 @@ ]]>= = - Then we can map an association to the current instance = - (the one with null effectiveEndDate) using: + You can then map an association to the current instance, = + the one with null effectiveEndDate, by usin= g: = Employee and Organization is maintained in an Employment table full of historical e= mployment data. - Then an association to the employee's most recent employer - (the one with the most recent startDate) mi= ght be mapped this way: + An association to the employee's most recent employer, + the one with the most recent startDate, cou= ld be mapped in the following way: = @@ -639,7 +640,7 @@ ]]> = - You can get quite creative with this functionality, but it is = usually more practical = + This functionality allows a degree of creativity and flexibili= ty, but it is more practical = to handle these kinds of cases using HQL or a criteria query. = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/basic_mapping.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/basic_mapping.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/basic_mapping.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -35,17 +35,17 @@ Object/relational mappings are usually defined in an XML docum= ent. The mapping document is designed to be readable and hand-editable. The map= ping language is Java-centric, meaning that mappings are constructed around per= sistent class - declarations, not table declarations. + declarations and not table declarations. = - Note that, even though many Hibernate users choose to write th= e XML by hand, - a number of tools exist to generate the mapping document, incl= uding XDoclet, + Please note that even though many Hibernate users choose to wr= ite the XML by hand, + a number of tools exist to generate the mapping document. Thes= e include XDoclet, Middlegen and AndroMDA. = - Lets kick off with an example mapping: + Here is an example mapping: = @@ -114,11 +114,11 @@ ]]> = - We will now discuss the content of the mapping document. We w= ill only describe the + We will now discuss the content of the mapping document. We w= ill only describe, however, the document elements and attributes that are used by Hibernate a= t runtime. The mapping document also contains some extra optional attributes and ele= ments that affect the - database schemas exported by the schema export tool. (For exa= mple the - not-null attribute.) + database schemas exported by the schema export tool (for exam= ple, the + not-null attribute). = = @@ -127,44 +127,44 @@ Doctype = - All XML mappings should declare the doctype shown. The act= ual DTD may be found + All XML mappings should declare the doctype shown. The act= ual DTD can be found at the URL above, in the directory hibernate-x.x.= x/src/org/hibernate - or in hibernate3.jar. Hibern= ate will always look for + , or in hibernate3.jar. Hiber= nate will always look for the DTD in its classpath first. If you experience lookups = of the DTD using an - Internet connection, check your DTD declaration against th= e contents of your - claspath. + Internet connection, check the DTD declaration against the= contents of your + classpath. = EntityResolver - As mentioned previously, Hibernate will first attempt = to resolve DTDs in its classpath. The - manner in which it does this is by registering a custo= m org.xml.sax.EntityResolver + Hibernate will first attempt to resolve DTDs in its cl= asspath. + It does this is by registering a custom org.x= ml.sax.EntityResolver implementation with the SAXReader it uses to read in t= he xml files. This custom - EntityResolver recognizes two diffe= rent systemId namespaces. + EntityResolver recognizes two diffe= rent systemId namespaces: a hibernate namespace is re= cognized whenever the - resolver encounteres a systemId starting with - http://hibernate.sourceforge.net/; the resolver - attempts to resolve these entities via the cla= sslaoder which loaded + resolver encounters a systemId starting with + http://hibernate.sourceforge.net/. The resolver + attempts to resolve these entities via the cla= ssloader which loaded the Hibernate classes. a user namespace is recogni= zed whenever the - resolver encounteres a systemId using a classpath:// - URL protocol; the resolver will attempt to res= olve these entities + resolver encounters a systemId using a classpath:// + URL protocol. The resolver will attempt to res= olve these entities via (1) the current thread context classloader= and (2) the classloader which loaded the Hibernate classes. - An example of utilizing user namespacing: + The following is an example of utilizing user namespac= ing: = - hibernate-mapping + Hibernate-mapping = This element has several optional attributes. The schema and catalog attributes specify that tables = referred to in this mapping - belong to the named schema and/or catalog. If specified, t= ablenames will be qualified - by the given schema and catalog names. If missing, tablena= mes will be unqualified. + belong to the named schema and/or catalog. If they are spe= cified, tablenames will be qualified + by the given schema and catalog names. If they are missing= , tablenames will be unqualified. The default-cascade attribute specifies= what cascade style - should be assumed for properties and collections which do = not specify a - cascade attribute. The auto-im= port attribute lets us - use unqualified class names in the query language, by defa= ult. + should be assumed for properties and collections that do n= ot specify a + cascade attribute. By default, the auto-import attribute allows you + to use unqualified class names in the query language. = @@ -224,44 +224,44 @@ - schema (optional): The nam= e of a database schema. + schema (optional): the nam= e of a database schema. - catalog (optional): The na= me of a database catalog. + catalog (optional): the na= me of a database catalog. default-cascade (optional = - defaults to none): - A default cascade style. + a default cascade style. default-access (optional -= defaults to property): - The strategy Hibernate should use for accessi= ng all properties. Can be a custom + the strategy Hibernate should use for accessi= ng all properties. It can be a custom implementation of PropertyAccessor. default-lazy (optional - d= efaults to true): - The default value for unspecifed laz= y attributes of class and + the default value for unspecified la= zy attributes of class and collection mappings. auto-import (optional - de= faults to true): - Specifies whether we can use unqualified clas= s names (of classes in this mapping) + specifies whether we can use unqualified clas= s names of classes in this mapping in the query language. - package (optional): Specif= ies a package prefix to assume for + package (optional): specif= ies a package prefix to use for unqualified class names in the mapping docume= nt. @@ -269,17 +269,17 @@ = - If you have two persistent classes with the same (unquali= fied) name, you should set - auto-import=3D"false". Hibernate will = throw an exception if you attempt + If you have two persistent classes with the same unqualif= ied name, you should set + auto-import=3D"false". An exception wi= ll result if you attempt to assign two classes to the same "imported" name. = - Note that the hibernate-mapping elemen= t allows you to nest + The hibernate-mapping element allows y= ou to nest several persistent <class> mappi= ngs, 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 map= ping file and name - it after the persistent superclass, e.g. Cat.hbm= .xml, + It is, however, good practice (and expected by some tools= ) to map only a single + persistent class, or a single class hierarchy, in one map= ping file and name + it after the persistent superclass. For example, Cat.hbm.xml, Dog.hbm.xml, or if using inheritance, Animal.hbm.xml. @@ -287,10 +287,10 @@ = - class + Class = - You may declare a persistent class using the clas= s element: + You can declare a persistent class using the clas= s element. For example: = @@ -344,112 +344,112 @@ - name (optional): The fully = qualified Java class name of the - persistent class (or interface). If this attri= bute is missing, it is assumed + name (optional): the fully = qualified Java class name of the + persistent class or interface. If this attribu= te is missing, it is assumed that the mapping is for a non-POJO entity. - table (optional - defaults = to the unqualified class name): The + table (optional - defaults = to the unqualified class name): the name of its database table. - discriminator-value (option= al - defaults to the class name): A value - that distiguishes individual subclasses, used = for polymorphic behaviour. Acceptable + discriminator-value (option= al - defaults to the class name): a value + that distinguishes individual subclasses that = is used for polymorphic behavior. Acceptable values include null and not null. - mutable (optional, defaults= to true): Specifies + mutable (optional - default= s to true): specifies that instances of the class are (not) mutable. - schema (optional): Override= the schema name specified by + schema (optional): override= s the schema name specified by the root <hibernate-mapping> element. - catalog (optional): Overrid= e the catalog name specified by + catalog (optional): overrid= es the catalog name specified by the root <hibernate-mapping> element. - proxy (optional): Specifies= an interface to use for lazy - initializing proxies. You may specify the name= of the class itself. + proxy (optional): specifies= an interface to use for lazy + initializing proxies. You can specify the name= of the class itself. - dynamic-update (optional, d= efaults to false): - Specifies that UPDATE SQL s= hould be generated at runtime and - contain only those columns whose values have c= hanged. + dynamic-update (optional - = defaults to false): + specifies that UPDATE SQL s= hould be generated at runtime and + can contain only those columns whose values ha= ve changed. - dynamic-insert (optional, d= efaults to false): - Specifies that INSERT SQL s= hould be generated at runtime and + dynamic-insert (optional - = defaults to false): + specifies that INSERT SQL s= hould be generated at runtime and contain only the columns whose values are not = null. - select-before-update (optio= nal, defaults to false): - Specifies that Hibernate should neve= r perform an SQL UPDATE - unless it is certain that an object is actuall= y modified. In certain cases (actually, only - when a transient object has been associated wi= th a new session using update()), - this means that Hibernate will perform an extr= a SQL SELECT to determine + select-before-update (optio= nal - defaults to false): + specifies that Hibernate should neve= r perform an SQL UPDATE + unless it is certain that an object is actuall= y modified. Only + when a transient object has been associated wi= th a new session using update(), + will Hibernate perform an extra SQL S= ELECT to determine if an UPDATE is actually re= quired. - polymorphism (optional, def= aults to implicit): - Determines whether implicit or explicit query = polymorphism is used. + polymorphism (optional - de= faults to implicit): + determines whether implicit or explicit query = polymorphism is used. - where (optional) specify an= arbitrary SQL WHERE - condition to be used when retrieving objects o= f this class + where (optional): specifies= an arbitrary SQL WHERE + condition to be used when retrieving objects o= f this class. - persister (optional): Speci= fies a custom ClassPersister. + persister (optional): speci= fies a custom ClassPersister. - batch-size (optional, defau= lts to 1) specify a "batch size" + batch-size (optional - defa= ults to 1): specifies a "batch size" for fetching instances of this class by identi= fier. - optimistic-lock (optional, = defaults to version): - Determines the optimistic locking strategy. + optimistic-lock (optional -= defaults to version): + determines the optimistic locking strategy. - lazy (optional): Lazy fetch= ing may be completely disabled by setting + lazy (optional): lazy fetch= ing can be disabled by setting lazy=3D"false". - entity-name (optional, defa= ults to the class name): Hibernate3 - allows a class to be mapped multiple times (to= different tables, potentially), - and allows entity mappings that are represente= d by Maps or XML at the Java level. + entity-name (optional - def= aults to the class name): Hibernate3 + allows a class to be mapped multiple times, po= tentially to different tables. + It also allows entity mappings that are repres= ented by Maps or XML at the Java level. In these cases, you should provide an explicit= arbitrary name for the entity. See and for more information. @@ -457,28 +457,27 @@ - check (optional): A SQL exp= ression used to generate a multi-row + check (optional): an SQL ex= pression used to generate a multi-row check constraint for auto= matic schema generation. - rowid (optional): Hibernate= can use so called ROWIDs on databases - which support. E.g. on Oracle, Hibernate can u= se the rowid extra - column for fast updates if you set this option= to rowid. A ROWID + rowid (optional): Hibernate= can use ROWIDs on databases. On Oracle, for example, Hibernate can use the= rowid extra + column for fast updates once this option has b= een set to rowid. A ROWID is an implementation detail and represents the= physical location of a stored tuple. - subselect (optional): Maps = an immutable and read-only entity - to a database subselect. Useful if you want to= have a view instead of a base table, - but don't. See below for more information. + subselect (optional): maps = an immutable and read-only entity + to a database subselect. This is useful if you= want to have a view instead of a base table. + See below for more information. - abstract (optional): Used t= o mark abstract superclasses in + abstract (optional): is use= d to mark abstract superclasses in <union-subclass> hier= archies. @@ -486,57 +485,57 @@ = - It is perfectly acceptable for the named persistent class = to be an interface. You would then + It is acceptable for the named persistent class to be an i= nterface. You can declare implementing classes of that interface using the <= literal><subclass> - element. You may persist any static i= nner class. You should specify the - class name using the standard form ie. eg.Foo$Bar= . + element. You can persist any static i= nner class. Specify the + class name using the standard form i.e. e.g.Foo$B= ar. = - Immutable classes, mutable=3D"false", m= ay not be updated or deleted by the + Immutable classes, mutable=3D"false", c= annot be updated or deleted by the application. This allows Hibernate to make some minor perf= ormance optimizations. = The optional proxy attribute enables la= zy initialization of persistent - instances of the class. Hibernate will initially return CG= LIB proxies which implement - the named interface. The actual persistent object will be = loaded when a method of the + instances of the class. Hibernate will initially return CG= LIB proxies that implement + the named interface. The persistent object will load when = a method of the proxy is invoked. See "Initializing collections and proxie= s" below. = Implicit polymorphism means that in= stances of the class will be returned - by a query that names any superclass or implemented interf= ace or the class and that instances + by a query that names any superclass or implemented interf= ace or class, and that instances of any subclass of the class will be returned by a query t= hat names the class itself. Explicit polymorphism means that clas= s instances will be returned only - by queries that explicitly name that class and that querie= s that name the class will return + by queries that explicitly name that class. Queries that n= ame the class will return only instances of subclasses mapped inside this &= lt;class> declaration as a <subclass> or <j= oined-subclass>. For - most purposes the default, polymorphism=3D"implic= it", is appropriate. + most purposes, the default polymorphism=3D"implic= it" is appropriate. Explicit polymorphism is useful when two different classes= are mapped to the same table - (this allows a "lightweight" class that contains a subset = of the table columns). + This allows a "lightweight" class that contains a subset o= f the table columns. = The persister attribute lets you custom= ize the persistence strategy used for - the class. You may, for example, specify your own subclass= of - org.hibernate.persister.EntityPersister= or you might even provide a + the class. You can, for example, specify your own subclass= of + org.hibernate.persister.EntityPersister= , or you can even provide a completely new implementation of the interface - org.hibernate.persister.ClassPersister = that implements persistence via, - for example, stored procedure calls, serialization to flat= files or LDAP. See - org.hibernate.test.CustomPersister for = a simple example (of "persistence" - to a Hashtable). + org.hibernate.persister.ClassPersister = that implements, for example, persistence via + stored procedure calls, serialization to flat files or LDA= P. See + org.hibernate.test.CustomPersister for = a simple example of "persistence" + to a Hashtable. = - Note that the dynamic-update and dynamic-insert - settings are not inherited by subclasses and so may also b= e specified on the + The dynamic-update and dynamic= -insert + settings are not inherited by subclasses, so they can also= be specified on the <subclass> or <joined= -subclass> elements. - These settings may increase performance in some cases, but= might actually decrease - performance in others. Use judiciously. + Although these settings can increase performance in some c= ases, they can actually decrease + performance in others. = - Use of select-before-update will usuall= y decrease performance. It is very + Use of select-before-update will usuall= y decrease performance. It is useful to prevent a database update trigger being called u= nnecessarily if you reattach a graph of detached instances to a Session. @@ -548,37 +547,37 @@ - version check the version/times= tamp columns + version: check the version/time= stamp columns - all check all columns + all: check all columns - dirty check the changed columns= , allowing some concurrent updates + dirty: check the changed column= s, allowing some concurrent updates - none do not use optimistic lock= ing + none: do not use optimistic loc= king - We very strongly recommend that you u= se version/timestamp - columns for optimistic locking with Hibernate. This is the= optimal strategy with - respect to performance and is the only strategy that corre= ctly handles modifications - made to detached instances (ie. when Session.merg= e() is used). + It is strongly recommended that you u= se version/timestamp + columns for optimistic locking with Hibernate. + This strategy optimizes performance and correctly handles modifications + made to detached instances (i.e. when Session.mer= ge() is used). = - There is no difference between a view and a base table for= a Hibernate mapping, as - expected this is transparent at the database level (note t= hat some DBMS don't support - views properly, especially with updates). Sometimes you wa= nt to use a view, but can't - create one in the database (ie. with a legacy schema). In = this case, you can map an + There is no difference between a view and a base table for= a Hibernate mapping. = + This is transparent at the database level, although some D= BMS do not support + views properly, especially with updates. Sometimes you wan= t to use a view, but you cannot + create one in the database (i.e. with a legacy schema). In= this case, you can map an immutable and read-only entity to a given SQL subselect ex= pression: = @@ -597,8 +596,8 @@ = Declare the tables to synchronize this entity with, ensuri= ng that auto-flush happens - correctly, and that queries against the derived entity do = not return stale data. - The <subselect> is available as b= oth as an attribute and + correctly and that queries against the derived entity do n= ot return stale data. + The <subselect> is available both= as an attribute and a nested mapping element. = @@ -635,31 +634,31 @@ - name (optional): The name o= f the identifier property. + name (optional): the name o= f the identifier property. - type (optional): A name tha= t indicates the Hibernate type. + type (optional): a name tha= t indicates the Hibernate type. - column (optional - defaults= to the property name): The + column (optional - defaults= to the property name): the name of the primary key column. unsaved-value (optional - d= efaults to a "sensible" value): - An identifier property value that indicates th= at an instance is newly instantiated + an identifier property value that indicates an= instance is newly instantiated (unsaved), distinguishing it from detached ins= tances that were saved or loaded in a previous session. - access (optional - defaults= to property): The + access (optional - defaults= to property): the strategy Hibernate should use for accessing th= e property value. @@ -676,8 +675,8 @@ = - There is an alternative <composite-id> declaration to allow access to - legacy data with composite keys. We strongly discourage it= s use for anything else. + There is an alternative <composite-id> declaration that allows access to + legacy data with composite keys. Its use is strongly disco= uraged for anything else. = @@ -699,9 +698,9 @@ = All generators implement the interface org.hi= bernate.id.IdentifierGenerator. - This is a very simple interface; some applications may= choose to provide their own specialized - implementations. However, Hibernate provides a range o= f built-in implementations. There are shortcut - names for the built-in generators: + This is a very simple interface. Some applications can= choose to provide their own specialized + implementations, however, Hibernate provides a range o= f built-in implementations. The shortcut + names for the built-in generators are as follows: = @@ -761,9 +760,9 @@ uuid - uses a 128-bit UUID algorithm to generate = identifiers of type string, + uses a 128-bit UUID algorithm to generate = identifiers of type string that are unique within a network (the IP address is= used). The UUID is encoded - as a string of hexadecimal digits of lengt= h 32. + as a string of 32 hexadecimal digits in le= ngth. @@ -779,7 +778,7 @@ native - picks identity, sequence or + selects identity, sequence or hilo depending upon the= capabilities of the underlying database. @@ -789,7 +788,7 @@ assigned - lets the application to assign an identifi= er to the object before + lets the application assign an identifier = to the object before save() is called. This = is the default strategy if no <generator>= element is specified. @@ -799,7 +798,7 @@ select - retrieves a primary key assigned by a data= base trigger by selecting + retrieves a primary key, assigned by a dat= abase trigger, by selecting the row by some unique key and retrieving = the primary key value. @@ -808,7 +807,7 @@ foreign - uses the identifier of another associated = object. Usually used in conjunction + uses the identifier of another associated = object. It is usually used in conjunction with a <one-to-one> primary key association. @@ -817,12 +816,12 @@ sequence-identity - a specialized sequence generation strategy= which utilizes a + a specialized sequence generation strategy= that utilizes a database sequence for the actual value gen= eration, but combines - this with JDBC3 getGeneratedKeys to actual= ly return the generated - identifier value as part of the insert sta= tement execution. This - strategy is only known to be supported on = Oracle 10g drivers - targetted for JDK 1.4. Note comments on t= hese insert statements + this with JDBC3 getGeneratedKeys to return= the generated + identifier value as part of the insert sta= tement execution. This + strategy is only supported on Oracle 10g d= rivers + targeted for JDK 1.4. Comments on these in= sert statements are disabled due to a bug in the Oracle dr= ivers. @@ -836,9 +835,9 @@ Hi/lo algorithm The hilo and seqhilo generators provide two alternate - implementations of the hi/lo algorithm, a favorite app= roach to identifier generation. The + implementations of the hi/lo algorithm. The first implementation requires a "special" database tab= le to hold the next available "hi" value. - The second uses an Oracle-style sequence (where suppor= ted). + Where supported, the second uses an Oracle-style seque= nce. = @@ -857,9 +856,9 @@ ]]> = - Unfortunately, you can't use hilo w= hen supplying your own - Connection to Hibernate. When Hiber= nate is using an application - server datasource to obtain connections enlisted with = JTA, you must properly configure + Unfortunately, you cannot use hilo = when supplying your own + Connection to Hibernate. When Hiber= nate uses an application + server datasource to obtain connections enlisted with = JTA, you must configure the hibernate.transaction.manager_lookup_clas= s. @@ -867,21 +866,21 @@ UUID algorithm - The UUID contains: IP address, startup time of the JVM= (accurate to a quarter - second), system time and a counter value (unique withi= n the JVM). It's not + 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 fro= m Java code, so this is - the best we can do without using JNI. + the best option without using JNI. = Identity columns and sequences - For databases which support identity columns (DB2, MyS= QL, Sybase, MS SQL), you - may use identity key generation. Fo= r databases that support - sequences (DB2, Oracle, PostgreSQL, Interbase, McKoi, = SAP DB) you may use - sequence style key generation. Both= these strategies require - two SQL queries to insert a new object. + For databases that support identity columns (DB2, MySQ= L, Sybase, MS SQL), you + can use identity key generation. Fo= r databases that support + sequences (DB2, Oracle, PostgreSQL, Interbase, McKoi, = SAP DB) you can use + sequence style key generation. Both= of these strategies require + two SQL queries to insert a new object. For example: = @@ -895,27 +894,26 @@ ]]> = - For cross-platform development, the native strategy will + For cross-platform development, the native strategy will, depending on the capabilities of the underlying data= base, = choose from the identity, = sequence and - hilo strategies, dependant upon the= capabilities of the - underlying database. + hilo strategies. = Assigned identifiers - If you want the application to assign identifiers (as = opposed to having - Hibernate generate them), you may use the ass= igned generator. - This special generator will use the identifier value a= lready assigned to the - object's identifier property. This generator is used w= hen the primary key + If you want the application to assign identifiers, as = opposed to having + Hibernate generate them, you can use the assi= gned generator. + This special generator uses the identifier value alrea= dy assigned to the + object's identifier property. The generator is used wh= en the primary key is a natural key instead of a surrogate key. This is t= he default behavior - if you do no specify a <generator> element. + if you do not specify a <generator> element. = - Choosing the assigned generator mak= es Hibernate use - unsaved-value=3D"undefined", forcin= g Hibernate to go to + The assigned generator makes Hibern= ate use + unsaved-value=3D"undefined". This f= orces 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 Interceptor.isUnsaved(). @@ -925,7 +923,7 @@ Primary keys assigned by triggers - For legacy schemas only (Hibernate does not generate D= DL with triggers). + Hibernate does not generate DDL with triggers. It is f= or legacy schemas only. = @@ -936,8 +934,8 @@ = In the above example, there is a unique valued propert= y named - socialSecurityNumber defined by the= class, as a - natural key, and a surrogate key named person= _id + socialSecurityNumber. It is defined= by the class, as a + natural key and a surrogate key named person_= id, whose value is generated by a trigger. = @@ -946,127 +944,127 @@ = - Enhanced identifier generators + Enhanced identifier generatorscomposite = Starting with release 3.2.3, there are 2 new generators wh= ich represent a re-thinking of 2 different aspects of identifier generation. The first aspect is dat= abase portability; the second is optimization - (not having to query the database for every request for a = new identifier value). These two new - generators are intended to take the place of some of the n= amed generators described above (starting - in 3.3.x); however, they are included in the current relea= ses and can be referenced by FQN. + Optimization means that you do not have to query the datab= ase for every request for a new identifier value. These two new + generators are intended to take the place of some of the n= amed generators described above, starting + in 3.3.x. However, they are included in the current releas= es and can be referenced by FQN. = The first of these new generators is org.hibernat= e.id.enhanced.SequenceStyleGenerator - which is intended firstly as a replacement for the sequence generator and secondly as - a better portability generator than native (because native - (generally) chooses between identity an= d sequence which have - largely different semantics which can cause subtle isssues= in applications eyeing portability). - org.hibernate.id.enhanced.SequenceStyleGenerator<= /literal> however achieves portability in - a different manner. It chooses between using a table or a= sequence in the database to store its - incrementing values depending on the capabilities of the d= ialect being used. The difference between this + which is intended, firstly, as a replacement for the sequence generator and, secondly, as + a better portability generator than native. This is because native + generally chooses between identity and = sequence which have + largely different semantics that can cause subtle issues i= n applications eyeing portability. + org.hibernate.id.enhanced.SequenceStyleGenerator<= /literal>, however, achieves portability in + a different manner. It chooses between a table or a seque= nce in the database to store its + incrementing values, depending on the capabilities of the = dialect being used. The difference between this and native is that table-based and sequ= ence-based storage have the same exact - semantic (in fact sequences are exactly what Hibernate tri= es to emmulate with its table-based - generators). This generator has a number of configuration= parameters: + semantic. In fact, sequences are exactly what Hibernate tr= ies to emulate with its table-based + generators. This generator has a number of configuration = parameters: sequence_name (optional, de= faults to hibernate_sequence): - The name of the sequence (or table) to be used. + the name of the sequence or table to be used. - initial_value (optional, de= faults to 1): The initial + initial_value (optional, de= faults to 1): the initial value to be retrieved from the sequence/table.= In sequence creation terms, this is analogous - to the clause typical named "STARTS WITH". + to the clause typically named "STARTS WITH". - increment_size (optional, d= efaults to 1): The value by + increment_size (optional - = defaults to 1): the value by which subsequent calls to the sequence/table s= hould differ. In sequence creation terms, this - is analogous to the clause typical named "INCR= EMENT BY". + is analogous to the clause typically named "IN= CREMENT BY". - force_table_use (optional, = defaults to false): Should + force_table_use (optional -= defaults to false): should we force the use of a table as the backing str= ucture even though the dialect might support sequence? - value_column (optional, def= aults to next_val): Only - relevant for table structures! The name of th= e column on the table which is used to + value_column (optional - de= faults to next_val): only + relevant for table structures, it is the name = of the column on the table which is used to hold the value. - optimizer (optional, defaul= ts to none): + optimizer (optional - defau= lts to none): See - The second of these new generators is org.hiberna= te.id.enhanced.TableGenerator which - is intended firstly as a replacement for the tabl= e generator (although it actually - functions much more like org.hibernate.id.Multipl= eHiLoPerTableGenerator) and secondly - as a re-implementation of org.hibernate.id.Multip= leHiLoPerTableGenerator utilizing the - notion of pluggable optimiziers. Essentially this generat= or defines a table capable of holding + The second of these new generators is org.hiberna= te.id.enhanced.TableGenerator, which + is intended, firstly, as a replacement for the ta= ble generator, even though it actually + functions much more like org.hibernate.id.Multipl= eHiLoPerTableGenerator, and secondly, + as a re-implementation of org.hibernate.id.Multip= leHiLoPerTableGenerator that utilizes the + notion of pluggable optimizers. Essentially this generato= r defines a table capable of holding a number of different increment values simultaneously by u= sing multiple distinctly keyed rows. This generator has a number of configuration parameters: - table_name (optional, defau= lts to hibernate_sequences): - The name of the table to be used. + table_name (optional - defa= ults to hibernate_sequences): + the name of the table to be used. - value_column_name (optional= , defaults to next_val): - The name of the column on the table which is u= sed to hold the value. + value_column_name (optional= - defaults to next_val): + the name of the column on the table that is us= ed to hold the value. - segment_column_name (option= al, defaults to sequence_name): - The name of the column on the table which is u= sed to hold the "segement key". This is the - value which distinctly identifies which increm= ent value to use. + segment_column_name (option= al - defaults to sequence_name): + the name of the column on the table that is us= ed to hold the "segment key". This is the + value which identifies which increment value t= o use. - segment_value (optional, de= faults to default): + segment_value (optional - d= efaults to default): The "segment key" value for the segment from w= hich we want to pull increment values for this generator. - segment_value_length (optio= nal, defaults to 255): + segment_value_length (optio= nal - defaults to 255): Used for schema generation; the column size to= create this segment key column. - initial_value (optional, de= faults to 1): + initial_value (optional - d= efaults to 1): The initial value to be retrieved from the tab= le. - increment_size (optional, d= efaults to 1): + increment_size (optional - = defaults to 1): The value by which subsequent calls to the tab= le should differ. - optimizer (optional, defaul= ts to ): + optimizer (optional - defau= lts to ): See @@ -1077,34 +1075,34 @@ Identifier generator optimization - For identifier generators which store values in the databa= se, it is inefficient for them to hit the - database on each and every call to generate a new identifi= er value. Instead, you'd ideally want to + For identifier generators that store values in the databas= e, it is inefficient for them to hit the + database on each and every call to generate a new identifi= er 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 - ( suppo= rt this notion. + ( suppo= rt this operation. - none (generally this is the= default if no optimizer was specified): This - says to not perform any optimizations, and hit= the database each and every request. + none (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. hilo: applies a hi/lo algor= ithm around the database retrieved values. The values from the database for this optimizer ar= e expected to be sequential. The values - retrieved from the database structure for this= optimizer indicates the "group number"; the + retrieved from the database structure for this= optimizer indicates the "group number". The increment_size is multiplie= d by that value in memory to define a group "hi value". - pooled: like was discussed = for hilo, this optimizers + pooled: as with the case of= hilo, 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 t= he database structure rather than a sequential - value in combination with an in-memory groupin= g algorithm. increment_size - here refers to the values coming from the data= base. + value in combination with an in-memory groupin= g algorithm. Here, increment_size + refers to the values coming from the database. @@ -1127,7 +1125,7 @@ ]]> = - For a table with a composite key, you may map multiple pro= perties of the class + A table with a composite key can be mapped with multiple p= roperties of the class as identifier properties. The <composite-id>= ; element accepts <key-property> property m= appings and <key-many-to-one> mappings as chi= ld elements. @@ -1139,13 +1137,13 @@ ]]> = - Your persistent class must override <= literal>equals() + The persistent class must override equals() and hashCode() to implement composite i= dentifier equality. It must - also implements Serializable. + also implement Serializable. = - Unfortunately, this approach to composite identifiers mean= s that a persistent object + Unfortunately, this approach means that a persistent object is its own identifier. There is no convenient "handle" oth= er than the object itself. You must instantiate an instance of the persistent class i= tself and populate its identifier properties before you can load() the persistent state @@ -1168,9 +1166,9 @@ In this example, both the composite identifier class, MedicareId, and the entity class itself have properties named medicareNumber and dependent. The identifier class mus= t override - equals() and hashCode() and implement. - Serializable. The disadvantage of this = approach is quite - obvious—code duplication. + equals() and hashCode() and implement + Serializable. The main disadvantage of = this approach is + code duplication. = @@ -1180,7 +1178,7 @@ - mapped (optional, defaults to <= literal>false): + mapped (optional - defaults to = false): indicates that a mapped composite identifier is us= ed, and that the contained property mappings refer to both the entity class a= nd the composite identifier class. @@ -1188,14 +1186,14 @@ - class (optional, but required f= or a mapped composite identifier): - The class used as a composite identifier. + class (optional - but required = for a mapped composite identifier): + the class used as a composite identifier. = - We will describe a third, even more convenient approach wh= ere the composite identifier + We will describe a third, even more convenient approach, w= here the composite identifier is implemented as a component class in . The attributes described below apply only to this alternative = approach: @@ -1203,39 +1201,39 @@ - name (optional, required for th= is approach): A property of - component type that holds the composite identifier= (see chapter 9). + name (optional - required for t= his approach): a property of + component type that holds the composite identifier= . Please see chapter 9 for more information. access (optional - defaults to = property): - The strategy Hibernate should use for accessing th= e property value. + the strategy Hibernate uses for accessing the prop= erty value. class (optional - defaults to t= he property type determined by - reflection): The component class used as a composi= te identifier (see next section). + reflection): the component class used as a composi= te identifier. Please see the next section for more information. = - This third approach, an identifier component is the one we recommend + The third approach, an identifier component, is recommended for almost all applications. = = - discriminator + Discriminator = The <discriminator> element is re= quired for polymorphic persistence - using the table-per-class-hierarchy mapping strategy and d= eclares a discriminator column of the + using the table-per-class-hierarchy mapping strategy. It d= eclares a discriminator column of the table. The discriminator column contains marker values tha= t tell the persistence layer what - subclass to instantiate for a particular row. A restricted= set of types may be used: + subclass to instantiate for a particular row. A restricted= set of types can be used: string, character, <= literal>integer, byte, short, boolean, yes_no, true_false. @@ -1259,35 +1257,35 @@ - column (optional - defaults= to class) the + column (optional - defaults= to class): the name of the discriminator column. - type (optional - defaults t= o string) a + type (optional - defaults t= o string): a name that indicates the Hibernate type - force (optional - defaults = to false) - "force" Hibernate to specify allowed discrimin= ator values even when retrieving + force (optional - defaults = to false): + "forces" Hibernate to specify the allowed disc= riminator values, even when retrieving all instances of the root class. - insert (optional - defaults= to true) + insert (optional - defaults= to true): set this to false if your d= iscriminator column is also part - of a mapped composite identifier. (Tells Hiber= nate to not include the column - in SQL INSERTs.) + of a mapped composite identifier. It tells Hib= ernate not to include the column + in SQL INSERTs. - formula (optional) an arbit= rary SQL expression that is - executed when a type has to be evaluated. Allo= ws content-based discrimination. + formula (optional): an arbi= trary SQL expression that is + executed when a type has to be evaluated. It a= llows content-based discrimination. @@ -1300,14 +1298,14 @@ = - The force attribute is (only) useful if= the table contains rows with + The force attribute is only useful if t= he table contains rows with "extra" discriminator values that are not mapped to a pers= istent class. This will not usually be the case. = - Using the formula attribute you can dec= lare an arbitrary SQL expression - that will be used to evaluate the type of a row: + The formula attribute allows you to dec= lare an arbitrary SQL expression + that will be used to evaluate the type of a row. For examp= le: = = - version (optional) + Version (optional) = The <version> element is optional= and indicates that the table contains versioned data. This is particularly us= eful if you plan to - use long transactions (see below). + use long transactions. See below for = more information: = @@ -1348,48 +1346,48 @@ - column (optional - defaults= to the property name): The name + column (optional - defaults= to the property name): the name of the column holding the version number. - name: The name of a propert= y of the persistent class. + name: the name of a propert= y of the persistent class. type (optional - defaults t= o integer): - The type of the version number. + the type of the version number. - access (optional - defaults= to property): The - strategy Hibernate should use for accessing th= e property value. + access (optional - defaults= to property): the + strategy Hibernate uses to access the property= value. unsaved-value (optional - d= efaults to undefined): - A version property value that indicates that a= n instance is newly instantiated + a version property value that indicates that a= n instance is newly instantiated (unsaved), distinguishing it from detached ins= tances that were saved or loaded - in a previous session. (undefined specifies that the identifier - property value should be used.) + in a previous session. Undefined specifies that the identifier + property value should be used. generated (optional - defau= lts to never): - Specifies that this version property value is = actually generated by the database. - See the discussion of generated properties. + specifies that this version property value is = generated by the database. + See the discussion of generated properties for more information. insert (optional - defaults= to true): - Specifies whether the version column should be= included in SQL insert statements. - May be set to false if and = only if the database column + specifies whether the version column should be= included in SQL insert statements. + It can be set to false if t= he database column is defined with a default value of 0<= /literal>. @@ -1397,26 +1395,26 @@ = - Version numbers may be of Hibernate type long, integer, + Version numbers can be of Hibernate type long, integer, short, timestamp or = calendar. = - A version or timestamp property should never be null for a= detached instance, so - Hibernate will detect any instance with a null version or = timestamp as transient, - no matter what other unsaved-value stra= tegies are specified. + A version or timestamp property should never be null for a= detached instance. = + Hibernate will detect any instance with a null version or timestamp as t= ransient, + irrespective of what other unsaved-value strategies are specified. Declaring a nullable version or timestamp proper= ty is an easy way to avoid - any problems with transitive reattachment in Hibernate, es= pecially useful for people - using assigned identifiers or composite keys! + problems with transitive reattachment in Hibernate. It is = especially useful for people + using assigned identifiers or composite keys. = - timestamp (optional) + Timestamp (optional) = The optional <timestamp> element = indicates that the table contains - timestamped data. This is intended as an alternative to ve= rsioning. Timestamps are by nature + timestamped data. This provides an alternative to versioni= ng. Timestamps are a less safe implementation of optimistic locking. However,= sometimes the application might use the timestamps in other ways. @@ -1442,68 +1440,73 @@ - column (optional - defaults= to the property name): The name + column (optional - defaults= to the property name): the name of a column holding the timestamp. - name: The name of a JavaBea= ns style property of + name: the name of a JavaBea= ns style property of Java type Date or = Timestamp of the persistent class. - access (optional - defaults= to property): The - strategy Hibernate should use for accessing th= e property value. + access (optional - defaults= to property): the + strategy Hibernate uses for accessing the prop= erty value. unsaved-value (optional - d= efaults to null): - A version property value that indicates that a= n instance is newly instantiated + a version property value that indicates that a= n instance is newly instantiated (unsaved), distinguishing it from detached ins= tances that were saved or loaded - in a previous session. (undefined specifies that the identifier - property value should be used.) + in a previous session. Undefined specifies that the identifier + property value should be used. source (optional - defaults= to vm): - From where should Hibernate retrieve the times= tamp value? From the database, + Where should Hibernate retrieve the timestamp = value from? From the database, or from the current JVM? Database-based times= tamps incur an overhead because - Hibernate must hit the database in order to de= termine the "next value", - but will be safer for use in clustered environ= ments. Note also, that not - all Dialects are known to s= upport retrieving of the - database's current timestamp, while others mig= ht be unsafe for usage - in locking due to lack of precision (Oracle 8 = for example). + Hibernate must hit the database in order to de= termine the "next value". + It is safer to use in clustered environments. = Not + all Dialects are known to s= upport 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). generated (optional - defau= lts to never): - Specifies that this timestamp property value i= s actually generated by the database. - See the discussion of generated properties. + specifies that this timestamp property value i= s actually generated by the database. + See the discussion of generated properties for more information. = - - Note that <timestamp> is equivale= nt to + = + + Note + + <Timestamp> is equivalent to <version type=3D"timestamp">. And <timestamp source=3D"db"> is equ= ivalent to <version type=3D"dbtimestamp"> - + + = + = = = - property + Property = - The <property> element declares a= persistent, JavaBean style + The <property> element declares a= persistent JavaBean style property of the class. = @@ -1554,7 +1557,7 @@ column (optional - defaults= to the property name): the name - of the mapped database table column. This may = also be specified by nested + of the mapped database table column. This can = also be specified by nested <column> element(s). @@ -1565,11 +1568,11 @@ - update, insert (optional - = defaults to true) : + update, insert (optional - = defaults to true): specifies that the mapped columns should be in= cluded in SQL UPDATE and/or INSERT statements. S= etting both to false allows a pure "derived" property whose value i= s initialized from some other - property that maps to the same colum(s) or by = a trigger or other application. + property that maps to the same column(s), or b= y a trigger or other application. @@ -1581,43 +1584,43 @@ - access (optional - defaults= to property): The - strategy Hibernate should use for accessing th= e property value. + access (optional - defaults= to property): the + strategy Hibernate uses for accessing the prop= erty value. - lazy (optional - defaults t= o false): Specifies + lazy (optional - defaults t= o false): specifies that this property should be fetched lazily wh= en the instance variable is first - accessed (requires build-time bytecode instrum= entation). + accessed. It requires build-time bytecode inst= rumentation. - unique (optional): Enable t= he DDL generation of a unique + unique (optional): enables = the DDL generation of a unique constraint for the columns. Also, allow this t= o be the target of a property-ref. - not-null (optional): Enable= the DDL generation of a nullability + not-null (optional): enable= s the DDL generation of a nullability constraint for the columns. optimistic-lock (optional -= defaults to true): - Specifies that updates to this property do or = do not require acquisition of the - optimistic lock. In other words, determines if= a version increment should occur when + 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. generated (optional - defau= lts to never): - Specifies that this property value is actually= generated by the database. - See the discussion of generated properties. + specifies that this property value is actually= generated by the database. + See the discussion of generated properties for more information. @@ -1630,14 +1633,14 @@ - The name of a Hibernate basic type (eg. i= nteger, string, character, - date, timestamp, float, binary, serializable, obje= ct, blob). + The name of a Hibernate basic type: integ= er, string, character, + date, timestamp, float, binary, serializable, obje= ct, blob etc. - The name of a Java class with a default basic type= (eg. int, float, - char, java.lang.String, java.util.Date, java.lang.= Integer, java.sql.Clob). + The name of a Java class with a default basic type= : int, float, + char, java.lang.String, java.util.Date, java.lang.= Integer, java.sql.Clob etc. @@ -1647,34 +1650,34 @@ - The class name of a custom type (eg. com.= illflow.type.MyCustomType). + The class name of a custom type: com.illf= low.type.MyCustomType etc. = If you do not specify a type, Hibernate will use reflectio= n upon the named - property to take a guess at the correct Hibernate type. Hi= bernate will try to - interpret the name of the return class of the property get= ter using rules 2, 3, - 4 in that order. However, this is not always enough. - In certain cases you will still need the type - attribute. (For example, to distinguish between H= ibernate.DATE and - Hibernate.TIMESTAMP, or to specify a cu= stom type.) + property and guess the correct Hibernate type. Hibernate w= ill attempt to + interpret the name of the return class of the property get= ter using, in order, rules 2, 3, + and 4. = + In certain cases you will need the type + attribute. For example, to distinguish between Hi= bernate.DATE and + Hibernate.TIMESTAMP, or to specify a cu= stom type. = - The access attribute lets you control h= ow Hibernate will access + The access attribute allows you to cont= rol how Hibernate accesses the property at runtime. By default, Hibernate will call t= he property get/set pair. If you specify access=3D"field", Hibern= ate will bypass the get/set - pair and access the field directly, using reflection. You = may specify your own + pair and access the field directly using reflection. You c= an specify your own strategy for property access by naming a class that implem= ents the interface org.hibernate.property.PropertyAccessor. = - An especially powerful feature are derived properties. The= se properties are by - definition read-only, the property value is computed at lo= ad time. You declare - the computation as a SQL expression, this translates to a = SELECT + A powerful feature is derived properties. These properties= are by + definition read-only. The property value is computed at lo= ad time. You declare + the computation as an SQL expression. This then translates= to a SELECT clause subquery in the SQL query that loads an instance: = @@ -1686,21 +1689,21 @@ AND li.orderNumber =3D orderNumber )"/>]]> = - Note that you can reference the entities own table by not = declaring an alias on - a particular column (customerId in the = given example). Also note - that you can use the nested <formula> mapping element - if you don't like to use the attribute. + You can reference the entity table by not declaring an ali= as on + a particular column. This would be customerId in the given example. You can also use = + the nested <formula> mapping element + if you do not want to use the attribute. = = - many-to-one + Many-to-one = An ordinary association to another persistent class is dec= lared using a many-to-one element. The relational mod= el is a - many-to-one association: a foreign key in one table is ref= erencing + many-to-one association; a foreign key in one table is ref= erencing the primary key column(s) of the target table. = @@ -1751,84 +1754,84 @@ - name: The name of the prope= rty. + name: the name of the prope= rty. - column (optional): The name= of the foreign key column. - This may also be specified by nested = <column> + column (optional): the name= of the foreign key column. + This can also be specified by nested = <column> element(s). class (optional - defaults = to the property type - determined by reflection): The name of the ass= ociated class. + determined by reflection): the name of the ass= ociated class. - cascade (optional): Specifi= es which operations should + cascade (optional): specifi= es which operations should be cascaded from the parent object to the asso= ciated object. fetch (optional - defaults = to select): - Chooses between outer-join fetching or sequent= ial select fetching. + chooses between outer-join fetching or sequent= ial select fetching. - update, insert (optional - = defaults to true) + update, insert (optional - = defaults to true): specifies that the mapped columns should be in= cluded in SQL UPDATE and/or INSERT statements. S= etting both to false - allows a pure "derived" association whose valu= e is initialized from some other - property that maps to the same colum(s) or by = a trigger or other application. + allows a pure "derived" association whose valu= e is initialized from another + property that maps to the same column(s), or b= y a trigger or other application. - property-ref: (optional) Th= e name of a property of the associated + property-ref (optional): th= e name of a property of the associated class that is joined to this foreign key. If n= ot specified, the primary key of the associated class is used. - access (optional - defaults= to property): The - strategy Hibernate should use for accessing th= e property value. + access (optional - defaults= to property): the + strategy Hibernate uses for accessing the prop= erty value. - unique (optional): Enable t= he DDL generation of a unique - constraint for the foreign-key column. Also, a= llow this to be the target of - a property-ref. This makes = the association multiplicity - effectively one to one. + unique (optional): enables = the DDL generation of a unique + constraint for the foreign-key column. By allo= wing this to be the target of + a property-ref, you can mak= e the association multiplicity + one-to-one. - not-null (optional): Enable= the DDL generation of a nullability + not-null (optional): enable= s the DDL generation of a nullability constraint for the foreign key columns. optimistic-lock (optional -= defaults to true): - Specifies that updates to this property do or = do not require acquisition of the - optimistic lock. In other words, dertermines i= f a version increment should occur when + 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. lazy (optional - defaults t= o proxy): - By default, single point associations are prox= ied. lazy=3D"no-proxy" + by default, single point associations are prox= ied. lazy=3D"no-proxy" specifies that the property should be fetched = lazily when the instance variable - is first accessed (requires build-time bytecod= e instrumentation). + is first accessed. This requires build-time by= tecode instrumentation. lazy=3D"false" specifies th= at the association will always be eagerly fetched. @@ -1836,13 +1839,13 @@ not-found (optional - defau= lts to exception): - Specifies how foreign keys that reference miss= ing rows will be handled: + specifies how foreign keys that reference miss= ing rows will be handled. ignore will treat a missing= row as a null association. - entity-name (optional): The= entity name of the associated class. + entity-name (optional): the= entity name of the associated class. @@ -1857,18 +1860,18 @@ Setting a value of the cascade attribut= e to any meaningful value other than none will propagate ce= rtain operations to the - associated object. The meaningful values are the names of = Hibernate's basic - operations, persist, merge, delete, save-update, = evict, replicate, lock, - refresh, as well as the special values = delete-orphan - and all and comma-separated combination= s of operation - names, for example, cascade=3D"persist,merge,evic= t" or + associated object. The meaningful values are divided into = three categories. First, basic + operations, which include: persist, merge, delete= , save-update, evict, replicate, lock and + refresh; second, special values: delete= -orphan; + and third,all comma-separated combinati= ons of operation + names: cascade=3D"persist,merge,evict" = or cascade=3D"all,delete-orphan". See - for a full explanation. Note that single valued associatio= ns (many-to-one and - one-to-one associations) do not support orphan delete. + for a full explanation. Note that single valued, many-to-o= ne and + one-to-one, associations do not support orphan delete. = - A typical many-to-one declaration looks= as simple as this: + Here is an example of a typical many-to-one declaration: = ]]> @@ -1876,10 +1879,10 @@ The property-ref attribute should only = be used for mapping legacy data where a foreign key refers to a unique key of the ass= ociated table other than - the primary key. This is an ugly relational model. For exa= mple, suppose the - Product class had a unique serial numbe= r, that is not the primary - key. (The unique attribute controls Hib= ernate's DDL generation with - the SchemaExport tool.) + the primary key. This is a complicated and confusing relat= ional model. For example, if the + Product class had a unique serial numbe= r that is not the primary + key. The unique attribute controls Hibe= rnate's DDL generation with + the SchemaExport tool. = ]]> @@ -1891,7 +1894,7 @@ ]]> = - This is certainly not encouraged, however. + This is not encouraged, however. = @@ -1900,7 +1903,7 @@ = - If the referenced unique key is the property of a component, = you may specify a property path: + If the referenced unique key is the property of a component, = you can specify a property path: = ]]> @@ -1908,7 +1911,7 @@ = - one-to-one + One-to-one = A one-to-one association to another persistent class is de= clared using a @@ -1946,78 +1949,78 @@ - name: The name of the prope= rty. + name: the name of the prope= rty. class (optional - defaults = to the property type - determined by reflection): The name of the ass= ociated class. + determined by reflection): the name of the ass= ociated class. - cascade (optional) specifie= s which operations should + cascade (optional): specifi= es which operations should be cascaded from the parent object to the asso= ciated object. - constrained (optional) spec= ifies that a foreign key constraint - on the primary key of the mapped table referen= ces the table of the associated + constrained (optional): spe= cifies that a foreign key constraint + on the primary key of the mapped table and ref= erences the table of the associated class. This option affects the order in which = save() and delete() are cascaded, and = determines whether the association - may be proxied (it is also used by the schema = export tool). + can be proxied. It is also used by the schema = export tool. fetch (optional - defaults = to select): - Chooses between outer-join fetching or sequent= ial select fetching. + chooses between outer-join fetching or sequent= ial select fetching. - property-ref: (optional) Th= e name of a property of the associated class + property-ref (optional): th= e name of a property of the associated class that is joined to the primary key of this clas= s. If not specified, the primary key of the associated class is used. - access (optional - defaults= to property): The - strategy Hibernate should use for accessing th= e property value. + access (optional - defaults= to property): the + strategy Hibernate uses for accessing the prop= erty value. - formula (optional): Almost = all one to one associations map to the - primary key of the owning entity. In the rare = case that this is not the case, you may - specify a some other column, columns or expres= sion to join on using an SQL formula. (See - org.hibernate.test.onetooneformula for an example.) + formula (optional): almost = all one-to-one associations map to the + primary key of the owning entity. If this is n= ot the case, you can + specify another column, columns or expression = to join on using an SQL formula. See + org.hibernate.test.onetooneformula for an example. lazy (optional - defaults t= o proxy): - By default, single point associations are prox= ied. lazy=3D"no-proxy" + by default, single point associations are prox= ied. lazy=3D"no-proxy" specifies that the property should be fetched = lazily when the instance variable - is first accessed (requires build-time bytecod= e instrumentation). + is first accessed. It requires build-time byte= code instrumentation. lazy=3D"false" specifies th= at the association will always be eagerly fetched. Note that if constrained=3D"false", - proxying is impossible and Hibernate will eage= r fetch the association! + proxying is impossible and Hibernate will eage= rly fetch the association. - entity-name (optional): The= entity name of the associated class. + entity-name (optional): the= entity name of the associated class. = - There are two varieties of one-to-one association: + There are two varieties of one-to-one associations: @@ -2029,23 +2032,23 @@ = - Primary key associations don't need an extra table column;= if two rows are related by - the association then the two table rows share the same pri= mary key value. So if you want - two objects to be related by a primary key association, yo= u must make sure that they - are assigned the same identifier value! + 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 pr= imary 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 Employee and - Person, respectively. + Person respectively: = ]]> ]]> = - Now we must ensure that the primary keys of related rows i= n the PERSON and - EMPLOYEE tables are equal. We use a special Hibernate iden= tifier generation strategy + Ensure that the primary keys of the related rows in the PE= RSON and + EMPLOYEE tables are equal. You use a special Hibernate ide= ntifier generation strategy called foreign: = @@ -2062,20 +2065,20 @@ ]]> = - A newly saved instance of Person is the= n assigned the same primary - key value as the Employee instance refe= red with the employee + A newly saved instance of Person is ass= igned the same primary + key value as the Employee instance refe= rred with the employee property of that Person. = Alternatively, a foreign key with a unique constraint, fro= m Employee to - Person, may be expressed as: + Person, can be expressed as: = ]]> = - And this association may be made bidirectional by adding t= he following to the + This association can be made bidirectional by adding the f= ollowing to the Person mapping: = @@ -2084,7 +2087,7 @@ = - natural-id + Natural-id = @@ -2093,28 +2096,28 @@ ]]> = - Even though we recommend the use of surrogate keys as prim= ary keys, you should still try + Although we recommend the use of surrogate keys as primary= keys, you should try to identify natural keys for all entities. A natural key i= s a property or combination of - properties that is unique and non-null. If it is also immu= table, even better. Map the + properties that is unique and non-null. It is also immutab= le. Map the properties of the natural key inside the <natu= ral-id> element. - Hibernate will generate the necessary unique key and nulla= bility constraints, and your + Hibernate will generate the necessary unique key and nulla= bility constraints and, as a result, your mapping will be more self-documenting. = - We strongly recommend that you implement equals()= and + It is recommended that you implement equals() and hashCode() to compare the natural key p= roperties of the entity. = - This mapping is not intended for use with entities with na= tural primary keys. + This mapping is not intended for use with entities that ha= ve natural primary keys. = - mutable (optional, defaults to = false): - By default, natural identifier properties as assum= ed to be immutable (constant). + mutable (optional - defaults to= false): + by default, natural identifier properties are assu= med to be immutable (constant). @@ -2122,13 +2125,13 @@ = - component, dynamic-component + Component and dynamic-component = The <component> element maps prop= erties of a - child object to columns of the table of a parent class. Co= mponents may, in + child object to columns of the table of a parent class. Co= mponents can, in turn, declare their own properties, components or collecti= ons. See - "Components" below. + the "Component" examples below: = @@ -2161,52 +2164,52 @@ - name: The name of the prope= rty. + name: the name of the prope= rty. class (optional - defaults = to the property type - determined by reflection): The name of the com= ponent (child) class. + determined by reflection): the name of the com= ponent (child) class. - insert: Do the mapped colum= ns appear in SQL - INSERTs? + insert: do the mapped colum= ns appear in SQL + INSERTs? - update: Do the mapped colum= ns appear in SQL - UPDATEs? + update: do the mapped colum= ns appear in SQL + UPDATEs? - access (optional - defaults= to property): The - strategy Hibernate should use for accessing th= e property value. + access (optional - defaults= to property): the + strategy Hibernate uses for accessing the prop= erty value. - lazy (optional - defaults t= o false): Specifies + lazy (optional - defaults t= o false): specifies that this component should be fetched lazily w= hen the instance variable is first - accessed (requires build-time bytecode instrum= entation). + accessed. It requires build-time bytecode inst= rumentation. optimistic-lock (option= al - defaults to true): - Specifies that updates to this component d= o or do not require acquisition of the - optimistic lock. In other words, determine= s if a version increment should occur when + specifies that updates to this component e= ither do or do not require acquisition of the + optimistic lock. It determines if a versio= n increment should occur when this property is dirty. unique (optional - defa= ults to false): - Specifies that a unique constraint exists = upon all mapped columns of the + specifies that a unique constraint exists = upon all mapped columns of the component. @@ -2226,21 +2229,21 @@ = The <dynamic-component> element a= llows a Map - to be mapped as a component, where the property names refe= r to keys of the map, see - . + to be mapped as a component, where the property names refe= r to keys of the map. See + for more informatio= n. = = - properties + Properties = The <properties> element allows t= he definition of a named, - logical grouping of properties of a class. The most import= ant use of the construct + logical grouping of the properties of a class. The most im= portant use of the construct is that it allows a combination of properties to be the ta= rget of a property-ref. It is also a convenient w= ay to define a multi-column - unique constraint. + unique constraint. For example: = @@ -2266,34 +2269,34 @@ - name: The logical name of t= he grouping - + name: the logical name of t= he grouping. It is not an actual property na= me. - insert: Do the mapped colum= ns appear in SQL - INSERTs? + insert: do the mapped colum= ns appear in SQL + INSERTs? - update: Do the mapped colum= ns appear in SQL - UPDATEs? + update: do the mapped colum= ns appear in SQL + UPDATEs? - + n optimistic-lock (option= al - defaults to true): - Specifies that updates to these properties= do or do not require acquisition of the - optimistic lock. In other words, determine= s if a version increment should occur when + specifies that updates to these properties= either do or do not require acquisition of the + optimistic lock. It determines if a versio= n increment should occur when these properties are dirty. unique (optional - defa= ults to false): - Specifies that a unique constraint exists = upon all mapped columns of the + specifies that a unique constraint exists = upon all mapped columns of the component. @@ -2306,6 +2309,7 @@ = + ... @@ -2316,7 +2320,7 @@ ]]> = - Then we might have some legacy data association which refe= rs to this unique key of + You might have some legacy data association that refers to= this unique key of the Person table, instead of to the pri= mary key: = @@ -2328,19 +2332,19 @@ ]]> = - We don't recommend the use of this kind of thing outside t= he context of mapping - legacy data. + The use of this outside the context of mapping + legacy data is not recommended. = = - subclass + Subclass = - Finally, polymorphic persistence requires the declaration = of each subclass of + Polymorphic persistence requires the declaration of each s= ubclass of the root persistent class. For the table-per-class-hierarc= hy - mapping strategy, the <subclass> = declaration is used. + mapping strategy, the <subclass> = declaration is used. For example: = @@ -2367,24 +2371,24 @@ - name: The fully qualified c= lass name of the subclass. + name: the fully qualified c= lass name of the subclass. - discriminator-value (option= al - defaults to the class name): A - value that distiguishes individual subclasses. + discriminator-value (option= al - defaults to the class name): a + value that distinguishes individual subclasses. - proxy (optional): Specifies= a class or interface to use for + proxy (optional): specifies= a class or interface used for lazy initializing proxies. - lazy (optional, defaults to= true): Setting + lazy (optional - defaults t= o true): setting lazy=3D"false" disables the= use of lazy fetching. @@ -2392,26 +2396,26 @@ = - Each subclass should declare its own persistent properties= and subclasses. + Each subclass declares its own persistent properties and s= ubclasses. <version> and <id>= properties - are assumed to be inherited from the root class. Each subc= lass in a heirarchy must - define a unique discriminator-value. If= none is specified, the + are assumed to be inherited from the root class. Each subc= lass in a hierarchy must + define a unique discriminator-value. If= this is not specified, the fully qualified Java class name is used. = - For information about inheritance mappings, see . + For information about inheritance mappings see . = = - joined-subclass + Joined-subclass = - Alternatively, each subclass may be mapped to its own tabl= e (table-per-subclass - mapping strategy). Inherited state is retrieved by joining= with the table of the - superclass. We use the <joined-subclass> element. + Each subclass can also be mapped to its own table. This is= called the table-per-subclass + mapping strategy. An inherited state is retrieved by joini= ng with the table of the + superclass. To do this you use the <joined-sub= class> element. For example: = @@ -2444,23 +2448,23 @@ - name: The fully qualified c= lass name of the subclass. + name: the fully qualified c= lass name of the subclass. - table: The name of the subc= lass table. + table: the name of the subc= lass table. - proxy (optional): Specifies= a class or interface to use + proxy (optional): specifies= a class or interface to use for lazy initializing proxies. - lazy (optional, defaults t= o true): Setting + lazy (optional, defaults t= o true): setting lazy=3D"false" disables the= use of lazy fetching. @@ -2468,10 +2472,10 @@ = - No discriminator column is required for this mapping strat= egy. Each subclass must, + A discriminator column is not required for this mapping st= rategy. Each subclass must, however, declare a table column holding the object identif= ier using the <key> element. The mapping at the= start of the chapter - would be re-written as: + would then be re-written as: = @@ -2507,23 +2511,23 @@ ]]> = - For information about inheritance mappings, see . + For information about inheritance mappings see . = = - union-subclass + Union-subclass = A third option is to map only the concrete classes of an in= heritance hierarchy - to tables, (the table-per-concrete-class strategy) where ea= ch table defines all - persistent state of the class, including inherited state. I= n Hibernate, it is - not absolutely necessary to explicitly map such inheritance= hierarchies. You - can simply map each class with a separate <clas= s> + to tables. This is called the table-per-concrete-class stra= tegy. Each table defines all + persistent states of the class, including the inherited sta= te. In Hibernate, it is + not necessary to explicitly map such inheritance hierarchie= s. You + can map each class with a separate <class> declaration. However, if you wish use polymorphic associati= ons (e.g. an association to the superclass of your hierarchy), you need to - use the <union-subclass> mapping. + use the <union-subclass> mapping. = For example: = @@ -2555,23 +2559,23 @@ - name: The fully qualified c= lass name of the subclass. + name: the fully qualified c= lass name of the subclass. - table: The name of the subc= lass table. + table: the name of the subc= lass table. - proxy (optional): Specifies= a class or interface to use + proxy (optional): specifies= a class or interface to use for lazy initializing proxies. - lazy (optional, defaults to= true): Setting + lazy (optional, defaults to= true): setting lazy=3D"false" disables the= use of lazy fetching. @@ -2583,17 +2587,17 @@ = - For information about inheritance mappings, see . + For information about inheritance mappings see . = = - join + Join = Using the <join> element, it is p= ossible to map - properties of one class to several tables, when there's a = 1-to-1 relationship between the tables. + properties of one class to several tables that have a one-= to-one relationship. For example: = @@ -2622,30 +2626,30 @@ - table: The name of the join= ed table. + table: the name of the join= ed table. - schema (optional): Override= the schema name specified by + schema (optional): override= s the schema name specified by the root <hibernate-mapping> element. - catalog (optional): Overrid= e the catalog name specified by + catalog (optional): overrid= es the catalog name specified by the root <hibernate-mapping> element. fetch (optional - defaults = to join): - If set to join, the default= , Hibernate will use an inner join - to retrieve a <join> = defined by a class or its superclasses - and an outer join for a <join><= /literal> defined by a subclass. + if set to join, the default= , Hibernate will use an inner join + to retrieve a <join> = defined by a class or its superclasses. It will use + an outer join for a <join> defined by a subclass. If set to select then Hiber= nate will use a sequential select for - a <join> 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 + a <join> defined on a= subclass. This will be issued only + if a row represents an instance of the subclas= s. Inner joins will still be used to retrieve a <join> defined by the class and its superclasses. @@ -2653,23 +2657,23 @@ inverse (optional - default= s to false): - If enabled, Hibernate will not try to insert o= r update the properties defined + if enabled, Hibernate will not insert or updat= e the properties defined by this join. optional (optional - defaul= ts to false): - If enabled, Hibernate will insert a row only i= f the properties defined by this - join are non-null and will always use an outer= join to retrieve the properties. + if enabled, Hibernate will insert a row only i= f the properties defined by this + join are non-null. It will always use an outer= join to retrieve the properties. = - For example, the address information for a person can be m= apped to a separate - table (while preserving value type semantics for all prope= rties): + For example, address information for a person can be mappe= d to a separate + table while preserving value type semantics for all proper= ties: = = - This feature is often only useful for legacy data models, = we recommend fewer + This feature is often only useful for legacy data models. = We recommend fewer tables than classes and a fine-grained domain model. Howev= er, it is useful for switching between inheritance mapping strategies in a = single hierarchy, as explained later. @@ -2695,13 +2699,13 @@ = - key + Key = = - - We've seen the <key> element crop= up a few times - now. It appears anywhere the parent mapping element define= s a join to - a new table, and defines the foreign key in the joined tab= le, that references - the primary key of the original table. + = = + The <key> element has featured a = few times within this guide. + It appears anywhere the parent mapping element defines a j= oin to + a new table that references + the primary key of the original table. It also defines the= foreign key in the joined table: = = @@ -2709,7 +2713,7 @@ - + = = @@ -2725,51 +2729,51 @@ - column (optional): The name= of the foreign key column. - This may also be specified by nested = <column> + column (optional): the name= of the foreign key column. + This can also be specified by nested = <column> element(s). - on-delete (optional, defaul= ts to noaction): - Specifies whether the foreign key constraint h= as database-level cascade delete + on-delete (optional - defau= lts to noaction): + specifies whether the foreign key constraint h= as database-level cascade delete enabled. - property-ref (optional): Sp= ecifies that the foreign key refers - to columns that are not the primary key of the= orginal table. (Provided for - legacy data.) + property-ref (optional): sp= ecifies that the foreign key refers + to columns that are not the primary key of the= original table. It is provided for + legacy data. - not-null (optional): Specif= ies that the foreign key columns - are not nullable (this is implied whenever the= foreign key is also part of the - primary key). + not-null (optional): specif= ies that the foreign key columns + are not nullable. This is implied whenever the= foreign key is also part of the + primary key. - update (optional): Specifie= s that the foreign key should never - be updated (this is implied whenever the forei= gn key is also part of the primary - key). + update (optional): specifie= s that the foreign key should never + be updated. This is implied whenever the forei= gn key is also part of the primary + key. - + file:///usr/share/doc/HTML/= en-US/index.html - unique (optional): Specifie= s that the foreign key should have - a unique constraint (this is implied whenever = the foreign key is also the primary key). + unique (optional): specifie= s that the foreign key should have + a unique constraint. This is implied whenever = the foreign key is also the primary key. = - We recommend that for systems where delete performance is = important, all keys should be - defined on-delete=3D"cascade", and Hibe= rnate will use a database-level + For systems where delete performance is important, we reco= mmend that all keys should be + defined on-delete=3D"cascade". Hibernat= e uses a database-level ON CASCADE DELETE constraint, instead o= f many individual DELETE statements. Be aware that this f= eature bypasses Hibernate's usual optimistic locking strategy for versioned data. @@ -2777,7 +2781,7 @@ = The not-null and update attributes are useful when - mapping a unidirectional one to many association. If you m= ap a unidirectional one to many + mapping a unidirectional one-to-many association. If you m= ap a unidirectional one-to-many association to a non-nullable foreign key, you must declare the key column using <key not-null=3D"true">. @@ -2785,11 +2789,11 @@ = - column and formula elements + Column and formula elements - Any mapping element which accepts a column attribute will alternatively + Mapping elements which accept a column a= ttribute will alternatively accept a <column> subelement. Like= wise, <formula> - is an alternative to the formula attribu= te. + is an alternative to the formula attribu= te. For example: = SQL expression]]><= /programlisting> = - column and formula a= ttributes may even be combined + column and formula a= ttributes can even be combined within the same property or association mapping to express= , for example, exotic join conditions. @@ -2822,13 +2826,13 @@ = - import + Import = - Suppose your application has two persistent classes with t= he same name, and you don't want to - specify the fully qualified (package) name in Hibernate qu= eries. Classes may be "imported" - explicitly, rather than relying upon auto-import= =3D"true". You may even import - classes and interfaces that are not explicitly mapped. + If your application has two persistent classes with the sa= me name, and you do not want to + specify the fully qualified package name in Hibernate quer= ies, classes can be "imported" + explicitly, rather than relying upon auto-import= =3D"true". You can also import + classes and interfaces that are not explicitly mapped: = ]]> @@ -2845,13 +2849,13 @@ - class: The fully qualified = class name of of any Java class. + class: the fully qualified = class name of any Java class. rename (optional - defaults= to the unqualified class name): - A name that may be used in the query language. + a name that can be used in the query language. @@ -2860,21 +2864,21 @@ = - any + Any = - There is one further type of property mapping. The <any> mapping element - defines a polymorphic association to classes from multiple= tables. This type of mapping always - requires more than one column. The first column holds the = type of the associated entity. - The remaining columns hold the identifier. It is impossibl= e to specify a foreign key constraint - for this kind of association, so this is most certainly no= t meant as the usual way of mapping - (polymorphic) associations. You should use this only in ve= ry special cases (eg. audit logs, - user session data, etc). + There is one more type of property mapping. The &= lt;any> mapping element + defines a polymorphic association to classes from multiple= tables. This type of mapping + requires more than one column. The first column contains t= he type of the associated entity. + The remaining columns contain the identifier. It is imposs= ible to specify a foreign key constraint + for this kind of association. This is not the usual way of= mapping + polymorphic associations and you should use this only in s= pecial cases. For example, for audit logs, + user session data, etc. = - The meta-type attribute lets the appli= cation specify a custom type that - maps database column values to persistent classes which h= ave identifier properties of the + The meta-type attribute allows the app= lication to specify a custom type that + maps database column values to persistent classes that ha= ve identifier properties of the type specified by id-type. You must sp= ecify the mapping from values of the meta-type to class names. @@ -2925,7 +2929,7 @@ meta-type (optional - defau= lts to string): - Any type that is allowed for a discriminator m= apping. + any type that is allowed for a discriminator m= apping. @@ -2936,15 +2940,15 @@ - access (optional - defaults= to property): The - strategy Hibernate should use for accessing th= e property value. - + access (optional - defaults= to property): the + strategy Hibernate uses for accessing the prop= erty value. + file:///usr/share/doc/HTML/en-US/index.html optimistic-lock (optional -= defaults to true): - Specifies that updates to this property do or = do not require acquisition of the - optimistic lock. In other words, define if a v= ersion increment should occur if this + 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. @@ -2956,71 +2960,71 @@ = - Hibernate Types + Hibernate types = Entities and values = - To understand the behaviour of various Java language-level= objects with respect - to the persistence service, we need to classify them into = two groups: + In relation to the persistence service, Java language-leve= l objects are classified = + into two groups: = An entity exists independently of any= other objects holding - references to the entity. Contrast this with the usual Jav= a model where an + references to the entity. Contrast this with the usual Jav= a model, where an unreferenced object is garbage collected. Entities must be= explicitly saved and - deleted (except that saves and deletions may be = cascaded - from a parent entity to its children). This is different f= rom the ODMG model of - object persistence by reachablity - and corresponds more c= losely to how + deleted. Saves and deletions, however, can be ca= scaded + from a parent entity to its children. This is different fr= om the ODMG model of + object persistence by reachability and corresponds more cl= osely to how application objects are usually used in large systems. Ent= ities support - circular and shared references. They may also be versioned. + circular and shared references. They can also be versioned. = An entity's persistent state consists of references to oth= er entities and - instances of value types. Values are = primitives, - collections (not what's inside a collection), components a= nd certain immutable - objects. Unlike entities, values (in particular collection= s and components) + instances of value types. Values are = primitives: + collections (not what is inside a collection), components = and certain immutable + objects. Unlike entities, values in particular collections= and components, are persisted and deleted by reachabi= lity. Since value - objects (and primitives) are persisted and deleted along w= ith their containing - entity they may not be independently versioned. Values hav= e no independent + objects and primitives are persisted and deleted along wit= h their containing + entity, they cannot be independently versioned. Values hav= e no independent identity, so they cannot be shared by two entities or coll= ections. = - Up until now, we've been using the term "persistent class"= to refer to - entities. We will continue to do that. Strictly speaking, = however, not all - user-defined classes with persistent state are entities. A - component is a user defined class wit= h value semantics. + Until now, we have been using the term "persistent class" = to refer to + entities. We will continue to do that. Not all + user-defined classes with a persistent state, however, are= entities. A + component is a user-defined class wit= h value semantics. A Java property of type java.lang.String also has value - semantics. Given this definition, we can say that all type= s (classes) provided - by the JDK have value type semantics in Java, while user-d= efined types may + semantics. Given this definition, all types (classes) prov= ided + by the JDK have value type semantics in Java, while user-d= efined types can be mapped with entity or value type semantics. This decisi= on is up to the - application developer. A good hint for an entity class in = a domain model are + application developer. An entity class in a domain model w= ill normally have shared references to a single instance of that class, whil= e composition or aggregation usually translates to a value type. = - We'll revisit both concepts throughout the documentation. + We will revisit both concepts throughout this reference gu= ide. = - The challenge is to map the Java type system (and the deve= lopers' definition of - entities and value types) to the SQL/database type system.= The bridge between - both systems is provided by Hibernate: for entities we use - <class>, <subclass>= ; and so on. + The challenge is to map the Java type system, and the deve= lopers' definition of + entities and value types, to the SQL/database type system.= The bridge between + both systems is provided by Hibernate. For entities, + <class>, <subclass>= ; and so on are used. For value types we use <property>, - <component>, etc, usually with a = type + <component>etc., that usually hav= e a type attribute. The value of this attribute is the name of a Hi= bernate - mapping type. Hibernate provides many= mappings (for standard - JDK value types) out of the box. You can write your own ma= pping types and implement your - custom conversion strategies as well, as you'll see later. + mapping type. Hibernate provides a ra= nge of mappings for standard + JDK value types out of the box. You can write your own map= ping types and implement your own + custom conversion strategies. = - All built-in Hibernate types except collections support nu= ll semantics. + With the exception of collections, all built-in Hibernate = types support null semantics. = @@ -3029,7 +3033,7 @@ Basic value types = - The built-in basic mapping types may = be roughly categorized into + The built-in basic mapping types can = be roughly categorized into the following: = @@ -3129,7 +3133,7 @@ Maps serializable Java types to an appropr= iate SQL binary type. You - may also indicate the Hibernate type serializable with + can also indicate the Hibernate type serializable with the name of a serializable Java class or i= nterface that does not default to a basic type. @@ -3140,9 +3144,9 @@ Type mappings for the JDBC classes java.sql.Clob and - java.sql.Blob. These ty= pes may be inconvenient for some - applications, since the blob or clob objec= t may not be reused outside of - a transaction. (Furthermore, driver suppor= t is patchy and inconsistent.) + java.sql.Blob. These ty= pes can be inconvenient for some + applications, since the blob or clob objec= t cannot be reused outside of + a transaction. Driver support is patchy an= d inconsistent. @@ -3153,13 +3157,13 @@ - Type mappings for what are usually conside= red mutable Java types, where + Type mappings for what are considered muta= ble Java types. This is where Hibernate makes certain optimizations appr= opriate only for immutable Java types, and the application treats the= object as immutable. For example, you should not call Date= .setTime() for an instance mapped as imm_timestamp<= /literal>. To change the value of the property, and have that chang= e made persistent, the - application must assign a new (nonidentica= l) object to the property. + application must assign a new, nonidentica= l, object to the property. @@ -3168,9 +3172,9 @@ = - Unique identifiers of entities and collections may be of a= ny basic type except + Unique identifiers of entities and collections can be of a= ny basic type except binary, blob and clob. - (Composite identifiers are also allowed, see below.) + Composite identifiers are also allowed. See below for more= information. = @@ -3188,7 +3192,7 @@ It is relatively easy for developers to create their own v= alue types. For example, you might want to persist properties of type java= .lang.BigInteger to VARCHAR columns. Hibernate does not = provide a built-in type - for this. But custom types are not limited to mapping a pr= operty (or collection element) + for this. Custom types are not limited to mapping a proper= ty, or collection element, to a single table column. So, for example, you might have = a Java property getName()/setName() = of type java.lang.String that is persisted to t= he columns @@ -3198,7 +3202,7 @@ To implement a custom type, implement either org.= hibernate.UserType or org.hibernate.CompositeUserType and = declare properties using the - fully qualified classname of the type. Check out + fully qualified classname of the type. View org.hibernate.test.DoubleStringType to = see the kind of things that are possible. @@ -3220,7 +3224,7 @@ = - You may even supply parameters to a UserType in the mapping file. To + You can even supply parameters to a UserType in the mapping file. To do this, your UserType must implement t= he org.hibernate.usertype.ParameterizedType interface. To supply parameters to your custom type, you can use the <type>= element in your mapping @@ -3239,9 +3243,9 @@ = - If you use a certain UserType very ofte= n, it may be useful to define a + If you regularly use a certain UserType= , it is useful to define a shorter name for it. You can do this using the &l= t;typedef> element. - Typedefs assign a name to a custom type, and may also cont= ain a list of default + Typedefs assign a name to a custom type, and can also cont= ain a list of default parameter values if the type is parameterized. = @@ -3258,13 +3262,13 @@ = Even though Hibernate's rich range of built-in types and s= upport for components means you - will very rarely need to use a custom= type, it is nevertheless - considered good form to use custom types for (non-entity) = classes that occur frequently + will rarely need to use a custom type, it is + considered good practice to use custom types for non-entit= y classes that occur frequently in your application. For example, a MonetaryAmoun= t class is a good - candidate for a CompositeUserType, even= though it could easily be mapped - as a component. One motivation for this is abstraction. Wi= th a custom type, your mapping - documents would be future-proofed against possible changes= in your way of representing - monetary values. + candidate for a CompositeUserType, 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. = @@ -3275,8 +3279,8 @@ Mapping a class more than once It is possible to provide more than one mapping for a particul= ar persistent class. In this - case you must specify an entity name do d= isambiguate between instances - of the two mapped entities. (By default, the entity name is th= e same as the class name.) + case, you must specify an entity name to = disambiguate between instances + of the two mapped entities. By default, the entity name is the= same as the class name. Hibernate lets you specify the entity name when working with p= ersistent objects, when writing queries, or when mapping associations to the named entity. @@ -3300,7 +3304,7 @@ ]]> = - Notice how associations are now specified using entit= y-name instead of + Associations are now specified using entity-name instead of class. = @@ -3309,10 +3313,10 @@ SQL quoted identifiers - You may force Hibernate to quote an identifier in the gene= rated SQL by enclosing the table or + You can force Hibernate to quote an identifier in the gene= rated SQL by enclosing the table or column name in backticks in the mapping document. Hibernat= e will use the correct quotation - style for the SQL Dialect (usually doub= le quotes, but brackets for SQL - Server and backticks for MySQL). + style for the SQL Dialect. This is usua= lly double quotes, but the SQL + Server uses brackets and MySQL uses backticks. = @@ -3328,7 +3332,7 @@ Metadata alternatives = - XML isn't for everyone, and so there are some alternative ways to = define O/R mapping metadata in Hibernate. + XML does not suit all users so there are some alternative ways to = define O/R mapping metadata in Hibernate. = @@ -3336,9 +3340,9 @@ = Many Hibernate users prefer to embed mapping information direc= tly in sourcecode using - XDoclet @hibernate.tags. We will not cover = this approach in this - document, since strictly it is considered part of XDoclet. How= ever, we include the - following example of the Cat class with XDo= clet mappings. + XDoclet @hibernate.tags. We do not cover th= is approach in this + reference guide since it is considered part of XDoclet. Howeve= r, we include the + following example of the Cat class with XDo= clet mappings: = = - See the Hibernate web site for more examples of XDoclet and Hi= bernate. + See the Hibernate website for more examples of XDoclet and Hib= ernate. = @@ -3456,14 +3460,14 @@ Using JDK 5.0 Annotations = - JDK 5.0 introduced XDoclet-style annotations at the language l= evel, type-safe and - checked at compile time. This mechnism is more powerful than X= Doclet annotations and + JDK 5.0 introduced XDoclet-style annotations at the language l= evel that are type-safe and + checked at compile time. This mechanism is more powerful than = XDoclet annotations and better supported by tools and IDEs. IntelliJ IDEA, for example= , supports auto-completion and syntax highlighting of JDK 5.0 annotations. The new revisi= on of the EJB specification (JSR-220) uses JDK 5.0 annotations as the primary metadata mec= hanism for entity beans. - Hibernate3 implements the EntityManager of = JSR-220 (the persistence API), - support for mapping metadata is available via the Hi= bernate Annotations - package, as a separate download. Both EJB3 (JSR-220) and Hiber= nate3 metadata is supported. + Hibernate3 implements the EntityManager of = JSR-220 (the persistence API). + Support for mapping metadata is available via the Hi= bernate Annotations + package as a separate download. Both EJB3 (JSR-220) and Hibern= ate3 metadata is supported. = @@ -3493,63 +3497,66 @@ // Getter/setter and business methods }]]> = - - Note that support for JDK 5.0 Annotations (and JSR-220) is sti= ll work in progress and - not completed. Please refer to the Hibernate Annotations modul= e for more details. + + Note + + Support for JDK 5.0 Annotations (and JSR-220) is currently und= er development. = + Please refer to the Hibernate Annotations module for more deta= ils. + = = - Generated Properties + Generated properties - Generated properties are properties which have their values ge= nerated by the + Generated properties are properties that have their values gen= erated by the database. Typically, Hibernate applications needed to refresh - objects which contain any properties for which the database wa= s generating values. + objects that contain any properties for which the database was= generating values. Marking properties as generated, however, lets the application= delegate this - responsibility to Hibernate. Essentially, whenever Hibernate = issues an SQL INSERT - or UPDATE for an entity which has defined generated properties= , it immediately + responsibility to Hibernate. When Hibernate issues an SQL INS= ERT + or UPDATE for an entity that has defined generated properties,= it immediately issues a select afterwards to retrieve the generated values. Properties marked as generated must additionally be non-insert= able and non-updateable. Only versions, timestamps, and - simple properti= es can be marked as + simple properti= es, can be marked as generated. - never (the default) - means that the given proper= ty value + never (the default): the given property value is not generated within the database. - insert - states that the given property value is = generated on - insert, but is not regenerated on subsequent updates. Things like c= reated-date would - fall into this category. Note that even thought + insert: the given property value is generated on + insert, but is not regenerated on subsequent updates. Properties li= ke created-date + fall into this category. Even though version and timestamp pro= perties can - be marked as generated, this option is not available there... + be marked as generated, this option is not available. - always - states that the property value is genera= ted both + always: the property value is generated both on insert and on update. = - Auxiliary Database Objects + Auxiliary database objects - Allows CREATE and DROP of arbitrary database objects, in conju= nction with - Hibernate's schema evolution tools, to provide the ability to = fully define + Auxiliary database objects allow for the CREATE and DROP of ar= bitrary database objects. In conjunction with + Hibernate's schema evolution tools, they have the ability to f= ully define a user schema within the Hibernate mapping files. Although de= signed specifically - for creating and dropping things like triggers or stored proce= dures, really any + for creating and dropping things like triggers or stored proce= dures, any SQL command that can be run via a java.sql.Statement.= execute() - method is valid here (ALTERs, INSERTS, etc). There are essent= ially two modes for - defining auxiliary database objects... + method is valid (for example, ALTERs, INSERTS, etc.). There a= re essentially two modes for + defining auxiliary database objects: - The first mode is to explicitly list the CREATE and DROP comma= nds out in the mapping + The first mode is to explicitly list the CREATE and DROP comma= nds in the mapping file: @@ -3560,7 +3567,7 @@ ]]> - The second mode is to supply a custom class which knows how to= construct the + The second mode is to supply a custom class that constructs the CREATE and DROP commands. This custom class must implement the org.hibernate.mapping.AuxiliaryDatabaseObject interface. @@ -3571,7 +3578,7 @@ ]]> - Additionally, these database objects can be optionally scoped = such that they only + Additionally, these database objects can be optionally scoped = so that they only apply when certain dialects are used. Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/batch.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/batch.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/batch.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -29,7 +29,7 @@ Batch processing = - A naive approach to inserting 100 000 rows in the database using H= ibernate might = + A naive approach to inserting 100,000 rows in the database using H= ibernate might = look like this: = @@ -44,26 +44,27 @@ = This would fall over with an OutOfMemoryException somewhere = - around the 50 000th row. That's because Hibernate caches all the n= ewly inserted = - Customer instances in the session-level cache. = + around the 50,000th row. That is because Hibernate caches all the = newly inserted = + Customer instances in the session-level cache. = In this chapter = + we will show you how to avoid this problem. = - In this chapter we'll show you how to avoid this problem. First, h= owever, if you - are doing batch processing, it is absolutely critical that you ena= ble the use of - JDBC batching, if you intend to achieve reasonable performance. Se= t the JDBC batch = - size to a reasonable number (say, 10-50): + = + If you are undertaking batch processing you will need to enable th= e use of + JDBC batching. This is absolutely essential if you want to achiev= e optimal performance. + Set the JDBC batch size to a reasonable number (10-50, for example): = = - Note that Hibernate disables insert batching at the JDBC level tra= nsparently if you - use an identiy identifier generator. + Hibernate disables insert batching at the JDBC level transparently= if you + use an identity identifier generator. = - You also might like to do this kind of work in a process where int= eraction with = + You can also do this kind of work in a process where interaction w= ith = the second-level cache is completely disabled: = @@ -78,8 +79,8 @@ Batch inserts = - When making new objects persistent, you must flush()<= /literal> and = - then clear() the session regularly, to cont= rol the size of + When making new objects persistent flush() = and = + then clear() the session regularly in order= to control the size of the first-level cache. = @@ -105,7 +106,7 @@ Batch updates = - For retrieving and updating data the same ideas apply. In addi= tion, you need to = + For retrieving and updating data, the same ideas apply. In add= ition, you need to = use scroll() to take advantage of server-si= de cursors for = queries that return many rows of data. @@ -135,18 +136,18 @@ The StatelessSession interface - Alternatively, Hibernate provides a command-oriented API that = may be used for = + Alternatively, Hibernate provides a command-oriented API that = can be used for = streaming data to and from the database in the form of detache= d objects. A = StatelessSession has no persistence context= associated with it and does not provide many of the higher-level life cyc= le semantics. In particular, a stateless session does not implement a first-= level cache nor interact with any second-level or query cache. It does not imp= lement = transactional write-behind or automatic dirty checking. Operat= ions performed - using a stateless session do not ever cascade to associated in= stances. Collections = + using a stateless session never cascade to associated instance= s. Collections = are ignored by a stateless session. Operations performed via a= stateless session = - bypass Hibernate's event model and interceptors. Stateless ses= sions are vulnerable = - to data aliasing effects, due to the lack of a first-level cac= he. A stateless - session is a lower-level abstraction, much closer to the under= lying JDBC. + bypass Hibernate's event model and interceptors. Due to the la= ck of a first-level cache, = + Stateless sessions are vulnerable to data aliasing effects. A statele= ss + session is a lower-level abstraction that is much closer to th= e underlying JDBC. = = - Note that in this code example, the Customer instances returned + In this code example, the Customer instance= s returned by the query are immediately detached. They are never associat= ed with any persistence context. @@ -172,9 +173,9 @@ The insert(), update() and delete(= ) operations defined by the StatelessSession interface a= re considered to be - direct database row-level operations, which result in immediat= e execution of a SQL - INSERT, UPDATE or DELETE= respectively. Thus, - they have very different semantics to the save(), sav= eOrUpdate() = + direct database row-level operations. They result in the immed= iate execution of a SQL + INSERT, UPDATE or DELETE= respectively. = + They have different semantics to the save(), saveOrUp= date() = and delete() operations defined by the Session = interface. @@ -186,18 +187,20 @@ = As already discussed, automatic and transparent object/relatio= nal mapping is concerned - with the management of object state. This implies that the obj= ect state is available - in memory, hence manipulating (using the SQL Data Man= ipulation Language - (DML) statements: INSERT, UPDATE, DELETE) - data directly in the database will not affect in-memory state.= However, Hibernate provides methods - for bulk SQL-style DML statement execution which are performed= through the + with the management of the object state. The object state is a= vailable in memory. This means that manipulating data directly in the datab= ase (using the SQL Data Manipulation Language + (DML) the statements: INSERT, UPDA= TE, DELETE) + will not affect in-memory state. However, Hibernate provides m= ethods + for bulk SQL-style DML statement execution that is performed t= hrough the Hibernate Query Language (HQL). = The pseudo-syntax for UPDATE and D= ELETE statements - is: ( UPDATE | DELETE ) FROM? EntityName (WHERE where= _conditions)?. Some - points to note: + is: ( UPDATE | DELETE ) FROM? EntityName (WHERE where= _conditions)?. = + + + + Some points to note: = @@ -208,17 +211,17 @@ - There can only be a single entity named in the from-cl= ause; it can optionally be + There can only be a single entity named in the from-cl= ause. It can, however, be aliased. If the entity name is aliased, then any prop= erty references must - be qualified using that alias; if the entity name is n= ot aliased, then it is + be qualified using that alias. If the entity name is n= ot aliased, then it is illegal for any property references to be qualified. - No joins= (either implicit or explicit) - can be specified in a bulk HQL query. Sub-queries may be= used in the where-clause; - the subqueries, themselves, may contain joins. + No joins= , 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. @@ -230,8 +233,8 @@ = As an example, to execute an HQL UPDATE, us= e the - Query.executeUpdate() method (the method is= named for - those familiar with JDBC's PreparedStatement.executeU= pdate()): + Query.executeUpdate() method. The method is= named for + those familiar with JDBC's PreparedStatement.executeU= pdate(): = = - HQL UPDATE statements, by default do not ef= fect the + In keeping with the EJB3 specification, HQL UPDATE statements, by default, do not effect the version or the timesta= mp property values - for the affected entities; this is in keeping with the EJB3 sp= ecification. However, - you can force Hibernate to properly reset the version= or + for the affected entities. However, + you can force Hibernate to reset the version or timestamp property values through the use o= f a versioned update. This is achieved by adding the VERSIONED ke= yword after the UPDATE keyword. @@ -267,7 +270,7 @@ session.close();]]> = - Note that custom version types (org.hibernate.usertyp= e.UserVersionType) + Custom version types, org.hibernate.usertype.UserVers= ionType, are not allowed in conjunction with a update versione= d statement. = @@ -289,13 +292,13 @@ = The int value returned by the Quer= y.executeUpdate() - method indicate the number of entities effected by the operati= on. Consider this may or may not + method indicates the number of entities effected by the operat= ion. 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-subc= lass, for example. The returned + multiple actual SQL statements being executed (for joined-subc= lass, 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 subcla= sses may actually result in deletes against not just the table to which that subclass i= s mapped, but also the "root" - table and potentially joined-subclass tables further down the = inheritence hierarchy. + table and potentially joined-subclass tables further down the = inheritance hierarchy. = @@ -310,10 +313,10 @@ Only the INSERT INTO ... SELECT ... form is supported;= not the INSERT INTO ... VALUES ... form. - The properties_list is analogous to the colum= n speficiation + The properties_list is analogous to the colum= n specification in the SQL INSERT statement. For e= ntities involved in mapped - inheritence, only properties directly defined on that = given class-level can be - used in the properties_list. Superclass properties ar= e not allowed; and subclass + inheritance, only properties directly defined on that = given class-level can be + used in the properties_list. Superclass properties ar= e not allowed and subclass properties do not make sense. In other words, INSERT statements are inherently non-polymorphic. @@ -322,8 +325,8 @@ select_statement can be any valid HQL select query, wi= th the caveat that the return types must match the types expected by the insert. Currentl= y, this is checked during query - compilation rather than allowing the check to relegate= to the database. Note however - that this might cause problems between Hibernate Types which are + compilation rather than allowing the check to relegate= to the database. = + This might, however, cause problems between Hibernate = Types which are equivalent as opposed to equal. This might cause issues with mismatches between a property defined as a= org.hibernate.type.DateType and a property defined as a org.hibernate.typ= e.TimestampType, even though the @@ -333,14 +336,14 @@ For the id property, the insert statement gives you tw= o options. You can either - explicitly specify the id property in the properties_l= ist (in which case its value - is taken from the corresponding select expression) or = omit it from the properties_list - (in which case a generated value is used). This later= option is only available when + explicitly specify the id property in the properties_l= ist, in which case its value + is taken from the corresponding select expression, or = omit it from the properties_list, + in which case a generated value is used. This latter = option is only available when using id generators that operate in the database; atte= mpting to use this option with - any "in memory" type generators will cause an exceptio= n during parsing. Note that - for the purposes of this discussion, in-database gener= ators are considered to be + any "in memory" type generators will cause an exceptio= n during parsing. = + For the purposes of this discussion, in-database gener= ators are considered to be org.hibernate.id.SequenceGenerator = (and its subclasses) and - any implementors of org.hibernate.id.PostInse= rtIdentifierGenerator. + any implementers of org.hibernate.id.PostInse= rtIdentifierGenerator. The most notable exception here is org.hibern= ate.id.TableHiLoGenerator, which cannot be used because it does not expose a sele= ctable way to get its values. @@ -349,15 +352,15 @@ For properties mapped as either version or timestamp, the insert statement gives you two options. You can e= ither 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= seed value defined - by the org.hibernate.type.VersionType is used). + 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= seed value defined + by the org.hibernate.type.VersionType is used. = - An example HQL INSERT statement execution: + The following is an example of an HQL INSERT statement execution: = - Write fine-grained classes and map them using &= lt;component>. + Write fine-grained classes and map them using &= lt;component>: Use an Address class to encapsulate= street, @@ -40,17 +40,17 @@ - Declare identifier properties on persistent classes. + Declare identifier properties on persistent classes: - Hibernate makes identifier properties optional. There = are all sorts of reasons why - you should use them. We recommend that identifiers be = 'synthetic' (generated, with - no business meaning). + Hibernate makes identifier properties optional. There = are a range of reasons why + you should use them. We recommend that identifiers be = 'synthetic', that is, generated with + no business meaning. - Identify natural keys. + Identify natural keys: Identify natural keys for all entities, and map them u= sing = @@ -60,17 +60,17 @@ - Place each class mapping in its own file. + Place each class mapping in its own file: - Don't use a single monolithic mapping document. Map <= literal>com.eg.Foo in = - the file com/eg/Foo.hbm.xml. This = makes particularly good sense in = + Do not use a single monolithic mapping document. Map = com.eg.Foo in = + the file com/eg/Foo.hbm.xml. This = makes sense, particularly in = a team environment. - Load mappings as resources. + Load mappings as resources: Deploy the mappings along with the classes they map. @@ -78,11 +78,11 @@ - Consider externalising query strings. + Consider externalizing query strings: - This is a good practice if your queries call non-ANSI-= standard SQL functions. = - Externalising the query strings to mapping files will = make the application more = + This is recommended if your queries call non-ANSI-stan= dard SQL functions. = + Externalizing the query strings to mapping files will = make the application more = portable. @@ -91,103 +91,103 @@ Use bind variables. - As in JDBC, always replace non-constant values by "?"= . Never use string manipulation to = - bind a non-constant value in a query! Even better, co= nsider using named parameters in + 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. - Don't manage your own JDBC connections. + Do not manage your own JDBC connections: - Hibernate lets the application manage JDBC connections= . This approach should be considered = - a last-resort. If you can't use the built-in connectio= ns providers, consider providing your = + Hibernate allows the application to manage JDBC connec= tions, but his approach should be considered = + a last-resort. If you cannot use the built-in connecti= on providers, consider providing your = own implementation of org.hibernate.connectio= n.ConnectionProvider. - Consider using a custom type. + Consider using a custom type: - Suppose you have a Java type, say from some library, t= hat needs to be persisted but doesn't = + Suppose you have a Java type from a library that needs= to be persisted but does not = provide the accessors needed to map it as a component.= You should consider implementing org.hibernate.UserType. This approa= ch frees the application - code from implementing transformations to / from a Hib= ernate type. + code from implementing transformations to/from a Hiber= nate type. - Use hand-coded JDBC in bottlenecks. + Use hand-coded JDBC in bottlenecks: In performance-critical areas of the system, some kind= s of operations might benefit from = - direct JDBC. But please, wait until you know= something is a bottleneck. = - And don't assume that direct JDBC is necessarily faste= r. If you need to use direct JDBC, it might = - be worth opening a Hibernate Session and using that JDBC connection. That = + direct JDBC. Do not assume, however, that JDBC is nece= ssarily faster. Please wait until you know something i= s a bottleneck. = + If you need to use direct JDBC, = + you can open a Hibernate Session an= d usingfile:///usr/share/doc/HTML/en-US/index.html that JDBC connection. Th= is = way you can still use the same transaction strategy an= d underlying connection provider. - Understand Session flushing. + Understand Session flushing: - From time to time the Session synchronizes its persist= ent state with the database. Performance will - be affected if this process occurs too often. You may = sometimes minimize unnecessary flushing by = - disabling automatic flushing or even by changing the o= rder of queries and other operations within a = + Sometimes the Session synchronizes its persistent stat= e 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. + In a three tiered architecture, consider using detached = objects: - When using a servlet / session bean architecture, you = could pass persistent objects loaded in - the session bean to and from the servlet / JSP layer. = Use a new session to service each request. = + When using a servlet/session bean architecture, you ca= n pass persistent objects loaded in + the session bean to and from the servlet/JSP layer. Us= e a new session to service each request. = Use Session.merge() or Ses= sion.saveOrUpdate() to = synchronize objects with the database. - In a two tiered architecture, consider using long persis= tence contexts. + In a two tiered architecture, consider using long persis= tence contexts: Database Transactions have to be as short as possible = for best scalability. However, it is often - neccessary to implement long running applica= tion transactions, a single = + necessary to implement long running applicat= ion transactions, a single = unit-of-work from the point of view of a user. An appl= ication transaction might span several = client request/response cycles. It is common to use de= tached objects to implement application - transactions. An alternative, extremely appropriate in= two tiered architecture, is to maintain - a single open persistence contact (session) for the wh= ole life cycle of the application transaction = - and simply disconnect from the JDBC connection at the = end of each request and reconnect at the = + transactions. An appropriate alternative in a two tier= ed architecture, is to maintain + a single open persistence contact session for the whol= e 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 sin= gle session across more than one application = - transaction, or you will be working with stale data. + transaction or you will be working with stale data. - Don't treat exceptions as recoverable. + Do not treat exceptions as recoverable: This is more of a necessary practice than a "best" pra= ctice. When an exception occurs, roll back - the Transaction and close the Session. If you don't, Hibernate - can't guarantee that in-memory state accurately repres= ents persistent state. As a special case of this, + the Transaction and close the Session. If you do not do this, Hibernate + cannot guarantee that in-memory state accurately repre= sents the persistent state. For example, do not use Session.load() to determ= ine if an instance with the given identifier = exists on the database; use Session.get() or a query instead. - Prefer lazy fetching for associations. + Prefer lazy fetching for associations: Use eager fetching sparingly. Use proxies and lazy col= lections for most associations to classes that = are not likely to be completely held in the second-lev= el cache. For associations to cached classes, = where there is an a extremely high probability of a ca= che hit, explicitly disable eager fetching using = - lazy=3D"false". When an join fetchi= ng is appropriate to a particular use + lazy=3D"false". When join fetching = is appropriate to a particular use case, use a query with a left join fetch. @@ -195,7 +195,7 @@ Use the open session in view pattern,= or a disciplined = - assembly phase to avoid problems with= unfetched data. + assembly phase to avoid problems with= unfetched data: @@ -203,40 +203,40 @@ In a traditional EJB architecture, DTOs serve dual pur= poses: first, they work around the problem that entity beans are not serializable; second, they i= mplicitly define an assembly phase where all data to be used by the view is fetched and marshal= led into the DTOs before returning control = - to the presentation tier. Hibernate eliminates the fir= st purpose. However, you will still need - an assembly phase (think of your business methods as h= aving a strict contract with the presentation - tier about what data is available in the detached obje= cts) unless you are prepared to hold the - persistence context (the session) open across the view= rendering process. This is not a limitation - of Hibernate! It is a fundamental requirement of safe = transactional data access. + to the presentation tier. Hibernate eliminates the fir= st 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 h= aving a strict contract with the presentation + tier about what data is available in the detached obje= cts. This is not a limitation + of Hibernate. It is a fundamental requirement of safe = transactional data access. - Consider abstracting your business logic from Hibernate.= + Consider abstracting your business logic from Hibernate:= - Hide (Hibernate) data-access code behind an interface.= Combine the DAO and = + Hide Hibernate data-access code behind an interface. C= ombine the DAO and = Thread Local Session patterns. Yo= u can even have some classes persisted by - handcoded JDBC, associated to Hibernate via a UserType. (This advice is = - intended for "sufficiently large" applications; it is = not appropriate for an application with - five tables!) + handcoded JDBC associated to Hibernate via a = UserType. This advice is, however, = + intended for "sufficiently large" applications. It is = not appropriate for an application with + five tables. - Don't use exotic association mappings. + Do not use exotic association mappings: - Good usecases for a real many-to-many associations are= rare. Most of the time you need + Practical test cases for real many-to-many association= s 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-to-many associations to an intermediate li= nk class. In fact, we think that - most associations are one-to-many and many-to-one, you= should be careful when using any - other association style and ask yourself if it is real= ly neccessary. + use two one-to-many associations to an intermediate li= nk 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. + Prefer bidirectional associations: Unidirectional associations are more difficult to quer= y. In a large application, almost Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/collection_mapping.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/collection_mapping.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/collection_mapping.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -26,14 +26,14 @@ = - Collection Mapping + Collection mapping = Persistent collections = Hibernate requires that persistent collection-valued fields be= declared - as an interface type, for example: + as an interface type. For example: = java.util.Set, java.util.Collection, java.util.Li= st, java.util.Map, java.util.SortedSet= , - java.util.SortedMap or ... anything you lik= e! (Where = - "anything you like" means you will have to write an implementa= tion of = + java.util.SortedMap or anything you like = + ("anything you like" means you will have to write an implement= ation of = org.hibernate.usertype.UserCollectionType.) = - Notice how we initialized the instance variable with an instan= ce of + Notice how the instance variable was initialized with an insta= nce of HashSet. This is the best way to initialize= collection valued properties of newly instantiated (non-persistent) insta= nces. When - you make the instance persistent - by calling persist= (), - for example - Hibernate will actually replace the Has= hSet + you make the instance persistent, by calling persist(= ) + for example, Hibernate will actually replace the Hash= Set with an instance of Hibernate's own implementation of Set. - Watch out for errors like this: + Be aware of the following errors: = HashMap, HashSet, TreeMap, TreeSet or - ArrayList, depending upon the interface typ= e. + ArrayList, depending on the interface type. = Collections instances have the usual behavior of value types. = They are = automatically persisted when referenced by a persistent object= and = - automatically deleted when unreferenced. If a collection is pa= ssed from one + are automatically deleted when unreferenced. If a collection i= s passed from one persistent object to another, its elements might be moved from= one table to - another. Two entities may not share a reference to the same co= llection = + another. Two entities cannot share a reference to the same col= lection = instance. Due to the underlying relational model, collection-v= alued properties - do not support null value semantics; Hibernate does not distin= guish between = + do not support null value semantics. Hibernate does not distin= guish between = a null collection reference and an empty collection. = - You shouldn't have to worry much about any of this. Use persis= tent collections = - the same way you use ordinary Java collections. Just make sure= you understand = - the semantics of bidirectional associations (discussed later). + Use persistent collections = + the same way you use ordinary Java collections. However, pleas= e ensure you understand = + the semantics of bidirectional associations (these are discuss= ed later). = @@ -106,15 +106,15 @@ = - There are quite a range of mappings that can be generated = for collections, covering + There are quite a range of mappings that can be generated = for collections that cover many common relational models. We suggest you experiment w= ith the schema generation tool - to get a feeling for how various mapping declarations tran= slate to database tables. + so that you understand how various mapping declarations tr= anslate to database tables. = The Hibernate mapping element used for mapping a collection de= pends upon - the type of the interface. For example, a <set>= = + the type of interface. For example, a <set> = element is used for mapping properties of type Set. = @@ -177,94 +177,94 @@ - name the collection property na= me + name: the collection property n= ame - table (optional - defaults to p= roperty name) the - name of the collection table (not used for one-to-= many associations) + table (optional - defaults to p= roperty name): the + name of the collection table. It is not used for o= ne-to-many associations. - schema (optional) the name of a= table schema to + schema (optional): the name of = a table schema to override the schema declared on the root element - lazy (optional - defaults to true) - may be used to disable lazy fetching and specify t= hat the association is = - always eagerly fetched, or to enable "extra-lazy" = fetching where most = - operations do not initialize the collection (suita= ble for very large = - collections) + lazy (optional - defaults to true): + disables lazy fetching and specifies that the asso= ciation is = + always eagerly fetched. It can also be used to ena= ble "extra-lazy" fetching where most = + operations do not initialize the collection. This = is suitable for large = + collections. - inverse (optional - defaults to= false) - mark this collection as the "inverse" end of a bid= irectional association + inverse (optional - defaults to= false): + marks this collection as the "inverse" end of a bi= directional association. - cascade (optional - defaults to= none) - enable operations to cascade to child entities + cascade (optional - defaults to= none): + enables operations to cascade to child entities. - sort (optional) specify a sorte= d collection with - natural sort order, or a given = comparator class + sort (optional): specifies a so= rted collection with + natural sort order or a given c= omparator class. - order-by (optional, JDK1.4 only= ) specify a table column (or columns) + order-by (optional, JDK1.4 only= ): specifies a table column or columns that define the iteration order of the Ma= p, Set - or bag, together with an optional asc or desc + or bag, together with an optional asc or desc. - where (optional) specify an arb= itrary SQL WHERE - condition to be used when retrieving or removing t= he collection (useful if the - collection should contain only a subset of the ava= ilable data) + where (optional): specifies an = arbitrary SQL WHERE + condition that is used when retrieving or removing= the collection. This is useful if the + collection needs to contain only a subset of the a= vailable data. - fetch (optional, defaults to select) Choose + fetch (optional, defaults to select): chooses between outer-join fetching, fetching by sequentia= l select, and fetching by sequential subselect. - batch-size (optional, defaults = to 1) specify a + batch-size (optional, defaults = to 1): specifies a "batch size" for lazily fetching instances of this= collection. - access (optional - defaults to = property): The - strategy Hibernate should use for accessing the co= llection property value. + access (optional - defaults to = property): the + strategy Hibernate uses for accessing the collecti= on property value. optimistic-lock (optional - def= aults to true): = - Species that changes to the state of the collectio= n results in increment of the - owning entity's version. (For one to many associat= ions, it is often reasonable to - disable this setting.) + specifies that changes to the state of the collect= ion results in increments of the + owning entity's version. For one-to-many associati= ons you may want to + disable this setting. mutable (optional - defaults to= true): = - A value of false specifies that= the elements of the = - collection never change (a minor performance optim= ization in some cases). + a value of false specifies that= the elements of the = + collection never change. This allows for minor per= formance optimization in some cases. @@ -276,22 +276,22 @@ Collection instances are distinguished in the database by = the foreign key of the entity that owns the collection. This foreign key is r= eferred to as the - collection key column (or columns) of= the collection = + collection key column, or columns, of= the collection = table. The collection key column is mapped by the <key> = element. = = - There may be a nullability constraint on the foreign key c= olumn. For most - collections, this is implied. For unidirectional one to ma= ny associations, - the foreign key column is nullable by default, so you migh= t need to specify + There can be a nullability constraint on the foreign key c= olumn. For most + collections, this is implied. For unidirectional one-to-ma= ny associations, + the foreign key column is nullable by default, so you may = need to specify not-null=3D"true". = ]]> = - The foreign key constraint may use ON DELETE CASC= ADE. + The foreign key constraint can use ON DELETE CASC= ADE. = ]]> @@ -307,12 +307,12 @@ Collection elements = - Collections may contain almost any other Hibernate type, i= ncluding all basic types, - custom types, components, and of course, references to oth= er entities. This is an - important distinction: an object in a collection might be = handled with "value" = - semantics (its life cycle fully depends on the collection = owner) or it might be a - reference to another entity, with its own life cycle. In t= he latter case, only the = - "link" between the two objects is considered to be state h= eld by the collection. = + Collections can contain almost any other Hibernate type, i= ncluding: basic types, + custom types, components and references to other entities.= This is an + important distinction. An object in a collection might be = handled with "value" = + semantics (its life cycle fully depends on the collection = owner), or it might be a + reference to another entity with its own life cycle. In th= e latter case, only the = + "link" between the two objects is considered to be a state= held by the collection. = = @@ -331,15 +331,15 @@ = All collection mappings, except those with set and bag sem= antics, need an - index column in the collection table = - a column that maps to an + index column in the collection table.= An index column is a column that maps to an array index, or List index, or Map key. The index of a Map may be of any basic type= , mapped with = - <map-key>, it may be an entity re= ference mapped with = - <map-key-many-to-many>, or it may= be a composite type, + <map-key>. It can be an entity re= ference mapped with = + <map-key-many-to-many>, or it can= be a composite type mapped with <composite-map-key>. = The index of an array or = list is always of type integer and is m= apped using the = <list-index> element. The mapped = column contains = - sequential integers (numbered from zero, by default). + sequential integers that are numbered from zero by default. = @@ -353,13 +353,13 @@ - column_name (required): The nam= e of the column holding the + column_name (required): the nam= e of the column holding the collection index values. - base (optional, defaults to 0): The value + base (optional - defaults to 0): the value of the index column that corresponds to the first = element of the list or array. @@ -381,19 +381,19 @@ - column (optional): The name of = the column holding the + column (optional): the name of = the column holding the collection index values. - formula (optional): A SQL formu= la used to evaluate the + formula (optional): a SQL formu= la used to evaluate the key of the map. - type (reguired): The type of th= e map keys. + type (required): the type of th= e map keys. @@ -413,19 +413,19 @@ - column (optional): The name of = the foreign key + column (optional): the name of = the foreign key column for the collection index values. - formula (optional): A SQL formu= la used to evaluate the + formula (optional): a SQ formul= a used to evaluate the foreign key of the map key. - class (required): The entity cl= ass used as the map key. + class (required): the entity cl= ass used as the map key. @@ -433,9 +433,9 @@ = = - If your table doesn't have an index column, and you still = wish to use List = - as the property type, you should map the property as a Hib= ernate <bag>. - A bag does not retain its order when it is retrieved from = the database, but it may be = + If your table does not have an index column, and you still= wish to use List = + as the property type, you can map the property as a Hibern= ate <bag>. + A bag does not retain its order when it is retrieved from = the database, but it can be = optionally sorted or ordered. = @@ -445,14 +445,14 @@ Collections of values and many-to-many associations = - Any collection of values or many-to-many association requires = a dedicated = + Any collection of values or many-to-many associations requires= a dedicated = collection table with a foreign key colum= n or columns, = - collection element column or columns and = possibly = + collection element column or columns, and= possibly = an index column or columns. = - For a collection of values, we use the <element>= ; tag. + For a collection of values use the <element> tag. For example: = @@ -475,19 +475,19 @@ - column (optional): The name of = the column holding the + column (optional): the name of = the column holding the collection element values. - formula (optional): An SQL form= ula used to evaluate the + formula (optional): an SQL form= ula used to evaluate the element. - type (required): The type of th= e collection element. + type (required): the type of th= e collection element. @@ -524,54 +524,54 @@ - column (optional): The name of = the element foreign key column. + column (optional): the name of = the element foreign key column. - formula (optional): An SQL form= ula used to evaluate the element + formula (optional): an SQL form= ula used to evaluate the element foreign key value. - class (required): The name of t= he associated class. + class (required): the name of t= he associated class. fetch (optional - defaults to <= literal>join): enables outer-join or sequential select fetching f= or this association. This - is a special case; for full eager fetching (in a s= ingle SELECT) + is a special case; for full eager fetching in a si= ngle SELECT of an entity and its many-to-many relationships to= other entities, you would - enable join fetching not only o= f the collection itself, + enable join fetching,not only o= f the collection itself, but also with this attribute on the <m= any-to-many> nested element. - unique (optional): Enable the D= DL generation of a unique + unique (optional): enables the = DDL generation of a unique constraint for the foreign-key column. This makes = the association multiplicity - effectively one to many. + effectively one-to-many. not-found (optional - defaults to = exception): = - Specifies how foreign keys that reference missing row= s will be handled: = + specifies how foreign keys that reference missing row= s will be handled: = ignore will treat a missing row as= a null association. - entity-name (optional): The ent= ity name of the associated class, + entity-name (optional): the ent= ity name of the associated class, as an alternative to class. - property-ref: (optional) The na= me of a property of the associated = + property-ref (optional): the na= me of a property of the associated = class that is joined to this foreign key. If not s= pecified, the primary key of the associated class is used. = @@ -579,8 +579,11 @@ = + + Here are some examples. + - Some examples, first, a set of strings: + A set of strings: = @@ -589,8 +592,8 @@ ]]> = - A bag containing integers (with an iteration order determined = by the - order-by attribute): + A bag containing integers with an iteration order determined b= y the + order-by attribute: = ]]> = - An array of entities - in this case, a many to many associatio= n: + An array of entities, in this case, a many-to-many association: = ]]> = - A list of components (discussed in the next chapter): + A list of components (this is discussed in the next chapter): = One-to-many associations = - A one to many association links the table= s of two classes - via a foreign key, with no intervening collection table. This = mapping loses = + A one-to-many association links the table= s of two classes + via a foreign key with no intervening collection table. This m= apping loses = certain semantics of normal Java collections: = - An instance of the contained entity class may not belo= ng to more than - one instance of the collection + An instance of the contained entity class cannot belon= g to more than + one instance of the collection. - An instance of the contained entity class may not appe= ar at more than - one value of the collection index + An instance of the contained entity class cannot appea= r at more than + one value of the collection index. = An association from Product to Par= t requires = - existence of a foreign key column and possibly an index column= to the Part = - table. A <one-to-many> tag indicates = that this is a one to many = + the existence of a foreign key column and possibly an index co= lumn to the Part = + table. A <one-to-many> tag indicates = that this is a one-to-many = association. = @@ -689,19 +692,19 @@ - class (required): The name of t= he associated class. + class (required): the name of t= he associated class. not-found (optional - defaults to exception): = - Specifies how cached identifiers that reference missing = rows will be handled: = + specifies how cached identifiers that reference missing = rows will be handled. ignore will treat a missing row as a = null association. - entity-name (optional): The ent= ity name of the associated class, + entity-name (optional): the ent= ity name of the associated class, as an alternative to class. @@ -709,24 +712,26 @@ = - Notice that the <one-to-many> element= does not need to + The <one-to-many> element does not ne= ed to declare any columns. Nor is it necessary to specify the table name anywhere. = - - Very important note: If the foreign key c= olumn of a = + = + + If the foreign key column of a = <one-to-many> association is declared= NOT NULL, = you must declare the <key> mapping = not-null=3D"true" or use a bidire= ctional association = with the collection mapping marked inverse=3D"true". See the discussion = - of bidirectional associations later in this chapter. + of bidirectional associations later in this chapter for more i= nformation. - = + + = - This example shows a map of Part entities b= y name (where - partName is a persistent property of Part). - Notice the use of a formula-based index. + The following example shows a map of Part e= ntities by name, where + partName is a persistent property of Part. + Notice the use of a formula-based index: = = - If you want the database itself to order the collection elemen= ts use the + If you want the database itself to order the collection elemen= ts, use the order-by attribute of set, bag or map mappings. This solution is only avai= lable under - JDK 1.4 or higher (it is implemented using LinkedHash= Set or - LinkedHashMap). This performs the ordering = in the SQL query, = - not in memory. + JDK 1.4 or higher and is implemented using LinkedHash= Set or + LinkedHashMap. This performs the ordering i= n the SQL query and = + not in the memory. = @@ -794,14 +799,17 @@ ]]> = - - Note that the value of the order-by attribu= te is an SQL ordering, not - a HQL ordering! + + Note + + The value of the order-by attribute is an S= QL ordering, not + an HQL ordering. + = - Associations may even be sorted by some arbitrary criteria at = runtime using a collection - filter(). + Associations can even be sorted by arbitrary criteria at runti= me using a collection + filter(): = @@ -821,7 +829,7 @@ one-to-many - set or bag valued at one end, single-valued at= the other + set or bag valued at one end and single-valued= at the other @@ -838,14 +846,14 @@ = - You may specify a bidirectional many-to-many association simpl= y by mapping two + You can specify a bidirectional many-to-many association by ma= pping two many-to-many associations to the same database table and decla= ring one end as - inverse (which one is your choice, but it= can not be an - indexed collection). + inverse. You cannot select an + indexed collection. = - Here's an example of a bidirectional many-to-many association;= each category can + Here is an example of a bidirectional many-to-many association= that illustrates how each category can have many items and each item can be in many categories: = @@ -872,9 +880,9 @@ Changes made only to the inverse end of the association are not persisted. This means that Hibernate has two representations i= n memory for every - bidirectional association, one link from A to B and another li= nk from B to A. This - is easier to understand if you think about the Java object mod= el and how we create - a many-to-many relationship in Java: + bidirectional association: one link from A to B and another li= nk from B to A. This + is easier to understand if you think about the Java object mod= el and how + a many-to-many relationship in Javais created: = = - You may define a bidirectional one-to-many association by mapp= ing a one-to-many association + You can define a bidirectional one-to-many association by mapp= ing a one-to-many association to the same table column(s) as a many-to-one association and d= eclaring the many-valued end inverse=3D"true". @@ -913,8 +921,8 @@ ]]> = - Mapping one end of an association with inverse=3D"tru= e" doesn't - affect the operation of cascades, these are orthogonal concept= s! + Mapping one end of an association with inverse=3D"tru= e" does not + affect the operation of cascades as these are orthogonal conce= pts. = @@ -923,8 +931,8 @@ Bidirectional associations with indexed collections A bidirectional association where one end is represented as a = <list> - or <map> requires special considerati= on. If there is a property of - the child class which maps to the index column, no problem, we= can continue using = + or <map>, requires special considerat= ion. If there is a property of + the child class that maps to the index column you can use = inverse=3D"true" on the collection mapping: = @@ -951,10 +959,10 @@ ]]> = - But, if there is no such property on the child class, we can't= think of the association as - truly bidirectional (there is information available at one end= of the association that is - not available at the other end). In this case, we can't map th= e collection = - inverse=3D"true". Instead, we could use the= following mapping: + If there is no such property on the child class, the associati= on cannot be considered + truly bidirectional. That is, there is information available a= t one end of the association that is + not available at the other end. In this case, you cannot map t= he collection = + inverse=3D"true". Instead, you could use th= e following mapping: = @@ -982,7 +990,7 @@ = Note that in this mapping, the collection-valued end of the ass= ociation is responsible for = - updates to the foreign key. TODO: Does this really result in so= me unnecessary update statements? + updates to the foreign key. = @@ -991,7 +999,7 @@ Ternary associations = - There are three possible approaches to mapping a ternary assoc= iation. One is to use a = + There are three possible approaches to mapping a ternary assoc= iation. One approach is to use a = Map with an association as its index: = @@ -1008,12 +1016,12 @@ ]]> = - A second approach is to simply remodel the association as an e= ntity class. This - is the approach we use most commonly. + A second approach is to remodel the association as an entity c= lass. This + is the most common approach. = - A final alternative is to use composite elements, which we wil= l discuss later. = + A final alternative is to use composite elements, which will b= e discussed later. = = @@ -1022,19 +1030,18 @@ <literal>Using an <idbag></literal> = - If you've fully embraced our view that composite keys are a ba= d thing and that - entities should have synthetic identifiers (surrogate keys), t= hen you might - find it a bit odd that the many to many associations and colle= ctions of values - that we've shown so far all map to tables with composite keys!= Now, this point - is quite arguable; a pure association table doesn't seem to be= nefit much from - a surrogate key (though a collection of composite values might). - Nevertheless, Hibernate provides a feature that allows you to = map many to many + The majority of the many-to-many associations and collections = of values + shown previously all map to tables with composite keys, even t= hough it has been have suggested = + that entities should have synthetic identifiers (surrogate keys). A + pure association table does not seem to benefit much from + a surrogate key, although a collection of composite values might. + It is for this reason that Hibernate provides a feature that a= llows you to map many-to-many associations and collections of values to a table with a surro= gate key. = The <idbag> element lets you map a List - (or Collection) with bag semantics. + (or Collection) with bag semantics. For exa= mple: = @@ -1046,17 +1053,16 @@ ]]> = - As you can see, an <idbag> has a synt= hetic id generator, - just like an entity class! A different surrogate key is assign= ed to each collection - row. Hibernate does not provide any mechanism to discover the = surrogate key value - of a particular row, however. + An <idbag> has a synthetic id generat= or, + just like an entity class. A different surrogate key is assign= ed to each collection + row. Hibernate does not, however, provide any mechanism for di= scovering the surrogate key value + of a particular row. = - Note that the update performance of an <idbag><= /literal> is - much better than a regular <b= ag>! + The update performance of an <idbag> = supersedes a regular <bag>. Hibernate can locate individual rows efficiently and update or= delete them - individually, just like a list, map or set. + individually, similar to a list, map or set. = @@ -1086,8 +1092,11 @@ Collection examples = - The previous sections are pretty confusing. So lets look at an= example. This - class: + This section covers collection examples. = + + + + The following class has a collection of Child inst= ances: = = - has a collection of Child instances. If each - child has at most one parent, the most natural mapping is a = + If each child has, at most, one parent, the most natural mappi= ng is a = one-to-many association: + = = @@ -1181,7 +1190,7 @@ alter table child add constraint childfk0 (parent_id) references parent]]>= = - Alternatively, if you absolutely insist that this association = should be unidirectional, + Alternatively, if this association must be unidirectional you can declare the NOT NULL constraint on = the <key> mapping: @@ -1208,7 +1217,7 @@ ]]> = - On the other hand, if a child might have multiple parents, a m= any-to-many + On the other hand, if a child has multiple parents, a many-to-= many association is appropriate: = @@ -1246,12 +1255,12 @@ alter table childset add constraint childsetfk1 (child_id) references chil= d]]> = - For more examples and a complete walk-through a parent/child r= elationship mapping, - see . + For more examples and a complete explanation of a parent/child= relationship mapping, + see for more informati= on. = - Even more exotic association mappings are possible, we will ca= talog all possibilities + Even more complex association mappings are covered in the next chapter. = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/component_mapping.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/component_mapping.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/component_mapping.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -29,17 +29,17 @@ Component Mapping = - The notion of a component is re-used in sever= al different contexts, - for different purposes, throughout Hibernate. + The notion of a component is re-used in sever= al different contexts and purposes + throughout Hibernate. = Dependent objects = - A component is a contained object that is persisted as a value= type, not an entity + A component is a contained object that is persisted as a value= type and not an entity reference. The term "component" refers to the object-oriented = notion of composition - (not to architecture-level components). For example, you might= model a person like this: + and not to architecture-level components. For example, you ca= n model a person like this: = = - Now Name may be persisted as a component of - Person. Notice that Name= defines getter - and setter methods for its persistent properties, but doesn't = need to declare + Now Name can be persisted as a component of + Person. Name defines get= ter + 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: + Our Hibernate mapping would look like this: = @@ -124,18 +124,17 @@ = - Like all value types, components do not support shared referen= ces. In other words, two + Like value types, components do not support shared references.= In other words, two persons could have the same name, but the two person objects w= ould contain two independent - name ojects, only "the same" by value. The null value semantic= s of a component are + name objects that were only "the same" by value. The null valu= e semantics of a component are ad hoc. When reloading the containing obj= ect, Hibernate will assume - that if all component columns are null, then the entire compon= ent is null. This should - be okay for most purposes. + that if all component columns are null, then the entire compon= ent is null. This is suitable for most purposes. = - The properties of a component may be of any Hibernate type (co= llections, many-to-one = + The properties of a component can be of any Hibernate type (co= llections, many-to-one = associations, other components, etc). Nested components should= not = - be considered an exotic usage. Hibernate is intended to suppor= t a very fine-grained = + be considered an exotic usage. Hibernate is intended to suppor= t a fine-grained = object model. = @@ -164,10 +163,10 @@ Collections of dependent objects = - Collections of components are supported (eg. an array of type + Collections of components are supported (e.g. an array of type Name). Declare your component collection by replacing the <element> tag with a - <composite-element> tag. + <composite-element> tag: = @@ -179,29 +178,31 @@ ]]> = - - Note: if you define a Set of composite elem= ents, it is = - very important to implement equals() and = + + + If you define a Set of composite elements, = it is = + important to implement equals() and = hashCode() correctly. - + = + = - Composite elements may contain components but not collections.= If your - composite element itself contains = + Composite elements can contain components but not collections.= If your + composite element contains = components, use the <nested-composite-element><= /literal> = - tag. This is a pretty exotic case - a collection of components= which = - themselves have components. By this stage you should be asking= yourself = - if a one-to-many association is more appropriate. Try remodell= ing the = - composite element as an entity - but note that even though the= Java model = + 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 ar= e still = slightly different. = - Please note that a composite element mapping doesn't support n= ull-able properties - if you're using a <set>. Hibernate - has to use each columns value to identify a record when deleti= ng objects - (there is no separate primary key column in the composite elem= ent table), + A composite element mapping does not support null-able propert= ies + if you are using a <set>. There is no= separate primary key column = + in the composite element table. Hibernate + uses each column's value to identify a record when deleting ob= jects, which is not possible with null values. You have to either use= only not-null properties in a composite-element or choose a <list>, <map>, @@ -210,10 +211,10 @@ = A special case of a composite element is a composite element w= ith a nested - <many-to-one> element. A mapping like= this allows + <many-to-one> element. This mapping a= llows you to map extra columns of a many-to-many association table t= o the composite element class. The following is a many-to-many assoc= iation - from Order to Item where = + from Order to Item, wher= e = purchaseDate, price and quantity are properties of the association: @@ -232,10 +233,10 @@ ]]> = - Of course, there can't be a reference to the purchae on the ot= her side, for - bidirectional association navigation. Remember that components= are value types and - don't allow shared references. A single Purchase can be in the - set of an Order, but it can't be referenced= by the Item + There cannot be a reference to the purchase on the other side = for + bidirectional association navigation. Components are value typ= es and + do not allow shared references. A single Purchase can be in the + set of an Order, but it cannot be reference= d by the Item at the same time. = @@ -253,7 +254,7 @@ ]]> = - Composite elements may appear in queries using the same syntax= as + Composite elements can appear in queries using the same syntax= as associations to other entities. = @@ -263,8 +264,8 @@ Components as Map indices = - The <composite-map-key> element lets = you map a - component class as the key of a Map. Make s= ure you override + The <composite-map-key> element allow= s you to map a + component class as the key of a Map. Ensure= that you override hashCode() and equals() = correctly on the component class. @@ -274,7 +275,7 @@ Components as composite identifiers = - You may use a component as an identifier of an entity class. Y= our component + You can use a component as an identifier of an entity class. Y= our component class must satisfy certain requirements: = @@ -287,25 +288,28 @@ It must re-implement equals() and - hashCode(), consistently with the d= atabase's = + hashCode() consistently with the da= tabase's = notion of composite key equality. = + + Note - Note: in Hibernate3, the second requirement is not a= n absolutely hard - requirement of Hibernate. But do it anyway. + In Hibernate3, although the second requirement is not an absol= utely hard + requirement of Hibernate, it is recommended. - - - You can't use an IdentifierGenerator to gen= erate composite keys. + + = + + You cannot use an IdentifierGenerator to ge= nerate composite keys. Instead the application must assign its own identifiers. = - Use the <composite-id> tag (with nest= ed = - <key-property> elements) in place of = the usual = + Use the <composite-id> tag, with nest= ed = + <key-property> elements, in place of = the usual = <id> declaration. For example, the OrderLine class has a primary key that depe= nds upon the (composite) primary key of Order. @@ -331,9 +335,9 @@ ]]> = - Now, any foreign keys referencing the OrderLine table are also = - composite. You must declare this in your mappings for other cl= asses. An association = - to OrderLine would be mapped like this: + Any foreign keys referencing the OrderLine = table are now = + composite. Declare this in your mappings for other classes. An= association = + to OrderLine is mapped like this: = @@ -343,12 +347,17 @@ ]]> = - - (Note that the <column> tag is an alt= ernative to the = - column attribute everywhere.) = + + + Note + = + + The <column> tag is an alternative to= the = + column attribute everywhere. + = - + A many-to-many association to Orde= rLine also uses the composite foreign key: @@ -376,7 +385,7 @@ ]]> = - (The <one-to-many> element, as usual,= declares no columns.) + The <one-to-many> element declares no= columns. = @@ -406,7 +415,7 @@ Dynamic components = - You may even map a property of type Map: + You can also map a property of type Map: = @@ -418,9 +427,9 @@ The semantics of a <dynamic-component> mapping are identical to <component>. The advantage of this= kind of mapping is = - the ability to determine the actual properties of the bean at = deployment time, just + the ability to determine the actual properties of the bean at = deployment time just by editing the mapping document. Runtime manipulation of the m= apping document is = - also possible, using a DOM parser. Even better, you can access= (and change) Hibernate's + also possible, using a DOM parser. You can also access, and ch= ange, Hibernate's configuration-time metamodel via the Configuration object. = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/configuration.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/configuration.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/configuration.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -29,11 +29,11 @@ Configuration = - Because Hibernate is designed to operate in many different environ= ments, there - are a large number of configuration parameters. Fortunately, most = have sensible + Hibernate is designed to operate in many different environments an= d, as such, there + is a broad range of configuration parameters. Fortunately, most ha= ve sensible default values and Hibernate is distributed with an example = - hibernate.properties file in etc/ that shows - the various options. Just put the example file in your classpath a= nd customize it. + hibernate.properties file in etc/ that displays + the various options. Simply put the example file in your classpath= and customize it to suit your needs. = @@ -42,14 +42,14 @@ An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application's Java types to an SQL database. The org.hibernate.cfg.Configuration - is used to build an (immutable) org.hibernate.S= essionFactory. The mappings + is used to build an immutable org.hibernate.Ses= sionFactory. The mappings are compiled from various XML mapping files. = - You may obtain a org.hibernate.cfg.Configuration instance by instantiating + You can obtain a org.hibernate.cfg.Configuration instance by instantiating it directly and specifying XML mapping documents. If the mappi= ng files are in the classpath, - use addResource(): + use addResource(). For example: = = - An alternative (sometimes better) way is to specify the mapped= class, and - let Hibernate find the mapping document for you: + An alternative way is to specify the mapped class and + allow Hibernate to find the mapping document for you: = = - Then Hibernate will look for mapping files named /or= g/hibernate/auction/Item.hbm.xml + Hibernate will then search for mapping files named /= org/hibernate/auction/Item.hbm.xml and /org/hibernate/auction/Bid.hbm.xml in= the classpath. This approach eliminates any hardcoded filenames. = A org.hibernate.cfg.Configuration also = allows you to specify configuration - properties: + properties. For example: = This is not the only way to pass configuration properties to H= ibernate. = - The various options include: + Some alternative options include: = @@ -108,18 +108,18 @@ Include <property> elements in - hibernate.cfg.xml (discussed later). + hibernate.cfg.xml (this is discusse= d later). = - hibernate.properties is the easiest appro= ach if you want to get started quickly. + If you want to get started quicklyhibernate.properti= es is the easiest approach. = - The org.hibernate.cfg.Configuration is = intended as a startup-time object, - to be discarded once a SessionFactory is cr= eated. + The org.hibernate.cfg.Configuration is = intended as a startup-time object that will + be discarded once a SessionFactory is creat= ed. = @@ -147,7 +147,7 @@ JDBC connections = - Usually, you want to have the org.hibernate.Ses= sionFactory create and pool + It is advisable to have the org.hibernate.Sessi= onFactory create and pool JDBC connections for you. If you take this approach, opening a= org.hibernate.Session is as simple as: @@ -155,18 +155,18 @@ = - As soon as you do something that requires access to the databa= se, a JDBC connection will be obtained from + Once you start a task that requires access to the database, a = JDBC connection will be obtained from the pool. = - For this to work, we need to pass some JDBC connection propert= ies to Hibernate. All Hibernate property - names and semantics are defined on the class org.hi= bernate.cfg.Environment. We will - now describe the most important settings for JDBC connection c= onfiguration. + Before you can do this, you first need to pass some JDBC conne= ction properties to Hibernate. All Hibernate property + names and semantics are defined on the class org.hi= bernate.cfg.Environment. = + The most important settings for JDBC connection configuration = are outlined below. = - Hibernate will obtain (and pool) connections using = java.sql.DriverManager + Hibernate will obtain and pool connections using ja= va.sql.DriverManager if you set the following properties: = @@ -227,25 +227,25 @@ = - Hibernate's own connection pooling algorithm is however quite = rudimentary. = + Hibernate's own connection pooling algorithm is, however, quit= e rudimentary. = It is intended to help you get started and is not in= tended for use = - in a production system or even for performance test= ing. You should + in a production system, or even for performance tes= ting. You should use a third party pool for best performance and stability. Jus= t replace the = hibernate.connection.pool_size property w= ith connection pool specific settings. This will turn off Hibernate's interna= l pool. For - example, you might like to use C3P0. + example, you might like to use c3p0. = C3P0 is an open source JDBC connection pool distributed along = with Hibernate in the lib directory. Hibernate will use its org.hibernate.con= nection.C3P0ConnectionProvider - for connection pooling if you set hibernate.c3p0.* properties. If you'd like to use Proxool + for connection pooling if you set hibernate.c3p0.* properties. If you would like to use Proxool, refer to the packaged hibernate.properties and the Hibernate web site for more information. = - Here is an example hibernate.properties f= ile for C3P0: + The following is an example hibernate.properties file for c3p0: = For use inside an application server, you should almost always= configure Hibernate to obtain connections - from an application server javax.sql.Datasource= registered in JNDI. You'll + from an application server javax.sql.Datasource= registered in JNDI. You will need to set at least one of the following properties: = @@ -321,7 +321,7 @@ = - Here's an example hibernate.properties fi= le for an application server provided JNDI + Here is an example hibernate.properties f= ile for an application server provided JNDI datasource: = @@ -338,13 +338,13 @@ = - Arbitrary connection properties may be given by prepending "hibernate.connection" to the - connection property name. For example, you may specify a charSet + Arbitrary connection properties can be given by prepending "hibernate.connection" to the + connection property name. For example, you can specify a charSet connection property using hibernate.connection.charS= et. = - You may define your own plugin strategy for obtaining JDBC con= nections by implementing the + You can define your own plugin strategy for obtaining JDBC con= nections by implementing the interface org.hibernate.connection.ConnectionPr= ovider, and specifying your custom implementation via the hibernate.connection.p= rovider_class property. @@ -355,14 +355,14 @@ Optional configuration properties = - There are a number of other properties that control the behavi= our of Hibernate at runtime. All are optional + There are a number of other properties that control the behavi= or of Hibernate at runtime. All are optional and have reasonable default values. = - Warning: some of these properties are "system-level" on= ly. System-level properties can + Some of these properties are "system-level" on= ly. System-level properties can be set only via java -Dproperty=3Dvalue or = hibernate.properties. They - may not be set by the other techniques de= scribed above. + cannot be set by the other techniques des= cribed above. = @@ -385,12 +385,12 @@ The classname of a Hibernate org.hi= bernate.dialect.Dialect which allows Hibernate to generate SQL optimized for= a particular relational database. - eg. = + e.g. = full.classname.of.Dialect - In most cases Hibernate will actually be a= ble to chose the correct - org.hibernate.dialect.Dialect implementation to use based on the + In most cases Hibernate will actually be a= ble to choose the correct + org.hibernate.dialect.Dialect implementation based on the JDBC metadata returned = by the JDBC driver. @@ -404,7 +404,7 @@ to setting the log category org.hiber= nate.SQL to debug. - eg. = + e.g. = true | false @@ -416,7 +416,7 @@ Pretty print the SQL in the log and console. - eg. = + e.g. = true | false @@ -429,7 +429,7 @@ Qualify unqualified table names with the given= schema/tablespace in generated SQL. - eg. = + e.g. = SCHEMA_NAME @@ -439,10 +439,10 @@ hibernate.default_catalog - Qualify unqualified table names with the given= catalog + Qualifies unqualified table names with the giv= en catalog in generated SQL. - eg. = + e.g. = CATALOG_NAME @@ -455,7 +455,7 @@ The org.hibernate.SessionFactor= y will be automatically bound to this name in JNDI after it has been c= reated. - eg. = + e.g. = jndi/composite/name @@ -465,11 +465,11 @@ hibernate.max_fetch_depth - Set a maximum "depth" for the outer join fetch= tree + Sets a maximum "depth" for the outer join fetc= h tree for single-ended associations (one-to-one, man= y-to-one). A 0 disables default outer = join fetching. - eg. = + e.g. = recommended values between 0 and = 3 @@ -480,9 +480,9 @@ hibernate.default_batch_fetch_size - Set a default size for Hibernate batch fetchin= g of associations. + Sets a default size for Hibernate batch fetchi= ng of associations. - eg. = + e.g. = recommended values 4, <= literal>8, = 16 @@ -493,7 +493,7 @@ hibernate.default_entity_mode - Set a default mode for entity representation f= or all sessions + Sets a default mode for entity representation = for all sessions opened from this SessionFactory dynamic-map, d= om4j, @@ -506,11 +506,11 @@ hibernate.order_updates - Force Hibernate to order SQL updates by the pr= imary key value + Forces Hibernate to order SQL updates by the p= rimary key value of the items being updated. This will result i= n fewer transaction deadlocks in highly concurrent systems. - eg. = + e.g. = true | false @@ -523,7 +523,7 @@ If enabled, Hibernate will collect statistics = useful for performance tuning. - eg. + e.g. true | false @@ -536,7 +536,7 @@ If enabled, generated identifier properties wi= ll be reset to default values when objects are delet= ed. - eg. + e.g. true | false @@ -549,7 +549,7 @@ If turned on, Hibernate will generate comments= inside the SQL, for easier debugging, defaults to false. - eg. + e.g. true | false @@ -588,7 +588,7 @@ A non-zero value enables use of JDBC2 batch up= dates by Hibernate. - eg. + e.g. recommended values between 5 and 30 @@ -599,11 +599,11 @@ Set this property to true i= f your JDBC driver returns - correct row counts from executeBatch(= ) (it is usually - safe to turn this option on). Hibernate will t= hen use batched DML for + correct row counts from executeBatch(= ). Iit is usually + safe to turn this option on. Hibernate will th= en use batched DML for automatically versioned data. Defaults to false. - eg. + e.g. true | false @@ -616,7 +616,7 @@ Select a custom org.hibernate.j= dbc.Batcher. Most applications will not need this configuration property. - eg. + e.g. classname.of.BatcherFactory @@ -627,10 +627,10 @@ Enables use of JDBC2 scrollable resultsets by = Hibernate. - This property is only necessary when using use= r supplied - JDBC connections, Hibernate uses connection me= tadata otherwise. + This property is only necessary when using use= r-supplied + JDBC connections. Hibernate uses connection me= tadata otherwise. - eg. = + e.g. = true | false @@ -643,7 +643,7 @@ Use streams when writing/reading bina= ry or serializable types to/from JDBC. *system-level pr= operty* - eg. + e.g. true | false @@ -653,13 +653,13 @@ hibernate.jdbc.use_get_generated_key= s - Enable use of JDBC3 PreparedStatement= .getGeneratedKeys() + Enables use of JDBC3 PreparedStatemen= t.getGeneratedKeys() to retrieve natively generated keys after inse= rt. Requires JDBC3+ driver and JRE1.4+, set to false if your driver has p= roblems with the Hibernate - identifier generators. By default, tries to de= termine the driver capabilities + identifier generators. By default, it tries to= determine the driver capabilities using connection metadata. - eg. + e.g. true|false @@ -672,7 +672,7 @@ The classname of a custom org.h= ibernate.connection.ConnectionProvider which provides JDBC connections to Hibernate. - eg. = + e.g. = classname.of.ConnectionProvider @@ -682,11 +682,11 @@ hibernate.connection.isolation - Set the JDBC transaction isolation level. Check java.sql.Connection - for meaningful values but note that most databases= do not support all isolation levels and some + Sets the JDBC transaction isolation level. Check <= interfacename>java.sql.Connection + for meaningful values, but note that most database= s do not support all isolation levels and some define additional, non-standard isolations. - eg. = + e.g. = 1, 2, 4, 8 @@ -696,9 +696,9 @@ hibernate.connection.autocommit - Enables autocommit for JDBC pooled connections= (not recommended). + Enables autocommit for JDBC pooled connections= (it is not recommended). - eg. + e.g. true | false @@ -708,9 +708,9 @@ hibernate.connection.release_mode - Specify when Hibernate should release JDBC con= nections. By default, = + Specifies when Hibernate should release JDBC c= onnections. By default, = a JDBC connection is held until the session is= explicitly closed or - disconnected. For an application server JTA da= tasource, you should use + disconnected. For an application server JTA da= tasource, use after_statement to aggressi= vely release connections after every JDBC call. For a non-JTA connectio= n, it often makes sense to release the connection at the end of each tran= saction, by using @@ -719,12 +719,12 @@ strategies and after_transaction for the JDBC = transaction strategy. - eg. = + e.g. = auto (default) | on_close | after_transaction | after_statement - Note that this setting only affects Sessions returned from + This setting only affects Session= s returned from SessionFactory.openSession. For Sessions obtained through SessionFactory.g= etCurrentSession, the CurrentSessionContext i= mplementation configured for use @@ -774,7 +774,7 @@ The classname of a custom CacheProvid= er. - eg. = + e.g. = classname.of.CacheProvider @@ -784,12 +784,12 @@ hibernate.cache.use_minimal_puts - Optimize second-level cache operation to minim= ize writes, at the + Optimizes second-level cache operation to mini= mize writes, at the cost of more frequent reads. This setting is m= ost useful for = clustered caches and, in Hibernate3, is enable= d by default for clustered cache implementations. - eg. = + e.g. = true|false @@ -799,9 +799,9 @@ hibernate.cache.use_query_cache - Enable the query cache, individual queries sti= ll have to be set cachable. + Enables the query cache. Individual queries st= ill have to be set cachable. - eg. = + e.g. = true|false @@ -811,11 +811,11 @@ hibernate.cache.use_second_level_cach= e - May be used to completely disable the second l= evel cache, which is enabled + Can be used to completely disable the second l= evel cache, which is enabled by default for classes which specify a <cache> mapping. - eg. = + e.g. = true|false @@ -828,7 +828,7 @@ The classname of a custom QueryCache<= /literal> interface, defaults to the built-in StandardQuer= yCache. - eg. + e.g. classname.of.QueryCache @@ -840,7 +840,7 @@ A prefix to use for second-level cache region = names. - eg. = + e.g. = prefix @@ -853,7 +853,7 @@ Forces Hibernate to store data in the second-l= evel cache in a more human-friendly format. - eg. + e.g. true|false @@ -883,7 +883,7 @@ to use with Hibernate Transaction API (defaults to JDBCTransactionFactory). - eg. = + e.g. = classname.of.TransactionFactory @@ -897,7 +897,7 @@ obtain the JTA UserTransaction from the application server. - eg. = + e.g. = jndi/composite/name @@ -907,11 +907,11 @@ hibernate.transaction.manager_lookup_= class - The classname of a TransactionManager= Lookup - - required when JVM-level caching is enabled o= r when using hilo = + The classname of a TransactionManager= Lookup. It is + required when JVM-level caching is enabled or = when using hilo = generator in a JTA environment. - eg. = + e.g. = classname.of.TransactionManagerLo= okup @@ -926,7 +926,7 @@ automatic session context management is prefer= red, see . - eg. = + e.g. = true | false @@ -938,10 +938,10 @@ If enabled, the session will be automatically = closed during the after completion phase of the transaction. Bui= lt-in and - utomatic session context management is preferr= ed, see + automatic session context management is prefer= red, see . - eg. = + e.g. = true | false @@ -967,12 +967,12 @@ hibernate.current_session_context_cla= ss - Supply a (custom) strategy for the scoping of = the "current" + Supply a custom strategy for the scoping of th= e "current" Session. See for more information about the built-in strategies. - eg. + e.g. jta | thread | managed | cust= om.Class @@ -985,7 +985,7 @@ Chooses the HQL parser implementation. - eg. = + e.g. = org.hibernate.hql.ast.ASTQueryTra= nslatorFactory or org.hibernate.hql.classic.Classic= QueryTranslatorFactory @@ -996,10 +996,10 @@ hibernate.query.substitutions - Mapping from tokens in Hibernate queries to SQ= L tokens + Is used to map from tokens in Hibernate querie= s to SQL tokens (tokens might be function or literal names, fo= r example). - eg. = + e.g. = hqlLiteral=3DSQL_LITERAL, hqlFunc= tion=3DSQLFUNC @@ -1009,13 +1009,13 @@ hibernate.hbm2ddl.auto - Automatically validate or export schema DDL to= the database = + Automatically validates or exports schema DDL = to the database = when the SessionFactory is = created. With create-drop, the database s= chema will be = dropped when the SessionFactory is closed = explicitly. - eg. = + e.g. = validate | upd= ate | = create | creat= e-drop @@ -1026,12 +1026,12 @@ hibernate.cglib.use_reflection_optimi= zer - Enables use of CGLIB instead of runtime reflec= tion (System-level - property). Reflection can sometimes be useful = when troubleshooting, - note that Hibernate always requires CGLIB even= if you turn off the - optimizer. You can not set this property in hibernate.cfg.xml. + Enables the use of CGLIB instead of runtime re= flection (System-level + property). Reflection can sometimes be useful = when troubleshooting. + Hibernate always requires CGLIB even if you tu= rn off the + optimizer. You cannot set this property in hibernate.cfg.xml. - eg. = + e.g. = true | false @@ -1044,10 +1044,10 @@ SQL Dialects = - You should always set the hibernate.dialect property to the correct + Always set the hibernate.dialect proper= ty to the correct org.hibernate.dialect.Dialect subclass = for your database. If you specify a dialect, Hibernate will use sensible defaults fo= r some of the - other properties listed above, saving you the effort of sp= ecifying them manually. + other properties listed above. This means that you will no= t have to specify them manually. =
@@ -1142,17 +1142,17 @@ If your database supports ANSI, Oracle or Sybase style out= er joins, outer join fetching will often increase performance by lim= iting the number of round - trips to and from the database (at the cost of possibly mo= re work performed by - the database itself). Outer join fetching allows a whole g= raph of objects connected + trips to and from the database. This is, however, at the c= ost of possibly more work performed by + the database itself. Outer join fetching allows a whole gr= aph of objects connected by many-to-one, one-to-many, many-to-many and one-to-one a= ssociations to be retrieved = in a single SQL SELECT. = - Outer join fetching may be disabled globally by setting + Outer join fetching can be disabled globally by setting the property hibernate.max_fetch_depth = to 0. A setting of 1 or higher enables outer = join fetching for - one-to-one and many-to-one associations which have been ma= pped with = + one-to-one and many-to-one associations that have been map= ped with = fetch=3D"join". = @@ -1166,8 +1166,8 @@ Binary Streams = - Oracle limits the size of byte arrays t= hat may - be passed to/from its JDBC driver. If you wish to use larg= e instances of + Oracle limits the size of byte arrays t= hat can + be passed to and/or from its JDBC driver. If you wish to u= se large instances of binary or serializable type, you should enable hibernate.jdbc.use_streams_for_binary. This is a system-level setting only. @@ -1182,7 +1182,7 @@ The properties prefixed by hibernate.cache allow you to use a process or cluster scoped second-level = cache system with Hibernate. See the for - more details. + more information. = @@ -1191,21 +1191,21 @@ Query Language Substitution = - You may define new Hibernate query tokens using h= ibernate.query.substitutions. + You can define new Hibernate query tokens using h= ibernate.query.substitutions. For example: = hibernate.query.substitutions true=3D1, false= =3D0 = - would cause the tokens true and false to be translated to + This would cause the tokens true and false to be translated to integer literals in the generated SQL. = hibernate.query.substitutions toLowercase=3DLO= WER = - would allow you to rename the SQL LOWER= function. + This would allow you to rename the SQL LOWER function. = @@ -1214,8 +1214,8 @@ Hibernate statistics = - If you enable hibernate.generate_statistics, Hibernate will = - expose a number of metrics that are useful when tuning a r= unning system via + If you enable hibernate.generate_statistics, Hibernate = + exposes a number of metrics that are useful when tuning a = running system via SessionFactory.getStatistics(). Hiberna= te can even be configured to expose these statistics via JMX. Read the Javadoc of th= e interfaces in org.hibernate.stats for more informatio= n. @@ -1231,15 +1231,15 @@ Hibernate utilizes Simple= Logging Facade for Java (SLF4J) in order to log various system events. SLF4J can direc= t your logging output to several logging frameworks (NOP, Simple, log4j version 1.2, JD= K 1.4 logging, JCL or logback) depending on your - chosen binding. In order to setup logging properly you will ne= ed slf4j-api.jar in + chosen binding. In order to setup logging you will need slf4j-api.jar in your classpath together with the jar file for your preferred b= inding - slf4j-log4j12.jar = in the case of Log4J. See the SLF4J documentation for more detail. - To use Log4j you will also need to place a log4j.pro= perties file in your classpath, - an example properties file is distributed with Hibernate in th= e src/ directory. + To use Log4j you will also need to place a log4j.pro= perties file in your classpath. + An example properties file is distributed with Hibernate in th= e src/ directory. = - We strongly recommend that you familiarize yourself with Hiber= nate's log + It is recommended that you familiarize yourself with Hibernate= 's log messages. A lot of work has been put into making the Hibernate= log as detailed as possible, without making it unreadable. It is an e= ssential troubleshooting device. The most interesting log categories ar= e the @@ -1302,8 +1302,8 @@ org.hibernate - Log everything (a lot of information, but = very useful for - troubleshooting) + Log everything. This is a lot of informati= on but it is useful for + troubleshooting @@ -1328,7 +1328,7 @@ = - You may provide rules for automatically generating database id= entifiers from + You can provide rules for automatically generating database id= entifiers 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 repe= titive noise @@ -1337,7 +1337,7 @@ = - You may specify a different strategy by calling + You can specify a different strategy by calling Configuration.setNamingStrategy() before ad= ding mappings: = @@ -1365,7 +1365,7 @@ = - The XML configuration file is by default expected to be in the= root o + The XML configuration file is by default expected to be in the= root of your CLASSPATH. Here is an example: = @@ -1403,22 +1403,22 @@ ]]> = - As you can see, the advantage of this approach is the external= ization of the + The advantage of this approach is the externalization of the mapping file names to configuration. The hibernate.cf= g.xml - is also more convenient once you have to tune the Hibernate ca= che. Note that is + is also more convenient once you have to tune the Hibernate ca= che. It is your choice to use either hibernate.properties or - hibernate.cfg.xml, both are equivalent, exc= ept for the above + hibernate.cfg.xml. Both are equivalent, exc= ept for the above mentioned benefits of using the XML syntax. = - With the XML configuration, starting Hibernate is then as simpl= e as + With the XML configuration, starting Hibernate is then as simpl= e as: = = - You can pick a different XML configuration file using + You can select a different XML configuration file using: = TransactionManager and= a ResourceManager take care of transactio= n management (CMT), - esp. distributed transaction handling across several datas= ources. You may - of course also demarcate transaction boundaries programmat= ically (BMT) or + especially distributed transaction handling across several= datasources. You can + also demarcate transaction boundaries programmatically (BM= T), or you might want to use the optional Hibernate Tran= saction API for this to keep your code portable. @@ -1461,10 +1461,10 @@ - JTA Session binding: The Hibernate Session - may be automatically bound to the scope of JTA transaction= s. Simply + JTA Session binding: the Hibernate Session + can be automatically bound to the scope of JTA transaction= s. Simply lookup the SessionFactory from JNDI and= get the current - Session. Let Hibernate take care of flu= shing and closing the + Session. Let Hibernate manage flushing = and closing the Session when your JTA transaction compl= etes. Transaction demarcation is either declarative (CMT) or programmatic (B= MT/UserTransaction). @@ -1474,12 +1474,12 @@ - JMX deployment: If you have a JMX cap= able application server - (e.g. JBoss AS), you can chose to deploy Hibernate as a ma= naged MBean. This saves + JMX deployment: if you have a JMX cap= able application server + (e.g. JBoss AS), you can choose to deploy Hibernate as a m= anaged MBean. This saves you the one line startup code to build your Sessi= onFactory from a Configuration. The container will sta= rtup your - HibernateService, and ideally also take= care of service - dependencies (Datasource has to be available before Hibern= ate starts, etc). + HibernateService and also take care of = service + dependencies (datasource has to be available before Hibern= ate starts, etc). @@ -1495,8 +1495,8 @@ = The Hibernate Session API is independen= t of any transaction - demarcation system in your architecture. If you let Hibern= ate use JDBC directly, - through a connection pool, you may begin and end your tran= sactions by calling + demarcation system in your architecture. If you let Hibern= ate use JDBC directly + through a connection pool, you can begin and end your tran= sactions by calling the JDBC API. If you run in a J2EE application server, you= might want to use bean-managed transactions and call the JTA API and UserTransac= tion when needed. @@ -1509,7 +1509,7 @@ = - There are three standard (built-in) choices: + There are three standard, or built-in, choices: = @@ -1523,9 +1523,9 @@ org.hibernate.transaction.JTATransactio= nFactory - delegates to container-managed transaction if = an existing transaction is - underway in this context (e.g. EJB session bea= n method), otherwise - a new transaction is started and bean-managed = transaction are used. + delegates to container-managed transactions if= an existing transaction is + underway in this context (for example, EJB ses= sion bean method). Otherwise, + a new transaction is started and bean-managed = transactions are used. @@ -1538,15 +1538,15 @@ = - You may also define your own transaction strategies (for a= CORBA transaction service, + 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, C= ontextual Sessions with JTA, etc.) + Some features in Hibernate (i.e., the second level cache, = Contextual Sessions with JTA, etc.) require access to the JTA TransactionManager in a managed environment. - In an application server you have to specify how Hibernate= should obtain a reference to the - TransactionManager, since J2EE does not= standardize a single mechanism: + In an application server, since J2EE does not standardize = a single mechanism, you have to specify how Hibernate should obtain a refer= ence to the + TransactionManager: =
@@ -1611,18 +1611,18 @@ JNDI-bound <literal>SessionFactory</literal> = - A JNDI bound Hibernate SessionFactory c= an simplify the lookup - of the factory and the creation of new Sessions. Note that this - is not related to a JNDI bound Datasource, both simply use the - same registry! + A JNDI-bound Hibernate SessionFactory c= an simplify the lookup + function of the factory and create new Sessions. This + is not, however, related to a JNDI bound Datasour= ce; both simply use the + same registry. = If you wish to have the SessionFactory = bound to a JNDI namespace, specify - a name (eg. java:hibernate/SessionFactory) using the property + a name (e.g. java:hibernate/SessionFactory) using the property hibernate.session_factory_name. If this= property is omitted, the - SessionFactory will not be bound to JND= I. (This is especially useful in - environments with a read-only JNDI default implementation,= e.g. Tomcat.) + SessionFactory will not be bound to JND= I. This is especially useful in + environments with a read-only JNDI default implementation = (in Tomcat, for example). = @@ -1634,18 +1634,18 @@ = Hibernate will automatically place the SessionFac= tory in JNDI after - you call cfg.buildSessionFactory(). Thi= s means you will at least have - this call in some startup code (or utility class) in your = application, unless you use - JMX deployment with the HibernateService (discussed later). + you call cfg.buildSessionFactory(). Thi= s means you will have + this call in some startup code, or utility class in your a= pplication, unless you use + JMX deployment with the HibernateService (this is discussed later in greater detail). = - If you use a JNDI SessionFactory, an EJ= B or any other class may - obtain the SessionFactory using a JNDI= lookup. + If you use a JNDI SessionFactory, an EJ= B or any other class, you can + obtain the SessionFactory using a JNDI = lookup. = - We recommend that you bind the SessionFactory to JNDI in + It is recommended that you bind the SessionFactor= y to JNDI in a managed environment and use a static = singleton otherwise. To shield your application code from these details, we als= o recommend to hide the actual lookup code for a SessionFactory= in a helper class, @@ -1659,15 +1659,15 @@ Current Session context management with JTA = - The easiest way to handle Sessions and = transactions is - Hibernates automatic "current" Session = management. - See the discussion of current sessions. + The easiest way to handle Sessions and = transactions is + Hibernate's automatic "current" Session= management. + For a discussion of contextual sessions see . Using the "jta" session context, if the= re is no Hibernate Session associated with the current JTA= transaction, one will be started and associated with that JTA transaction the first= time you call sessionFactory.getCurrentSession(). The Sessions - retrieved via getCurrentSession() in "jta" context - will be set to automatically flush before the transaction com= pletes, close + retrieved via getCurrentSession() in the"jta" context + are set to automatically flush before the transaction complet= es, close after the transaction completes, and aggressively release JDB= C connections after each statement. This allows the Sessions to be managed by the life cycle of the JTA transaction to which = it is associated, @@ -1686,15 +1686,15 @@ The line cfg.buildSessionFactory() stil= l has to be executed somewhere to get a SessionFactory into = JNDI. You can do this - either in a static initializer block (l= ike the one in - HibernateUtil) or you deploy Hibernate = as a managed + either in a static initializer block, l= ike the one in + HibernateUtil, or you can deploy Hibern= ate as a managed service. = Hibernate is distributed with org.hibernate.jmx.H= ibernateService for deployment on an application server with JMX capabilit= ies, such as JBoss AS. - The actual deployment and configuration is vendor specific= . Here is an example + The actual deployment and configuration is vendor-specific= . Here is an example jboss-service.xml for JBoss 4.0.x: = @@ -1746,7 +1746,7 @@ in a JAR file with the extension .sar (= service archive). You also need to package Hibernate, its required third-party libraries, = your compiled persistent classes, as well as your mapping files in the same archive. Your en= terprise beans (usually session - beans) may be kept in their own JAR file, but you may incl= ude this EJB JAR file in the + beans) can be kept in their own JAR file, but you can incl= ude this EJB JAR file in the main service archive to get a single (hot-)deployable unit= . Consult the JBoss AS documentation for more information about JMX service and E= JB deployment. Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/events.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/events.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/events.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -29,9 +29,9 @@ Interceptors and events = - It is often useful for the application to react to certain events = that occur - inside Hibernate. This allows implementation of certain kinds of g= eneric = - functionality, and extension of Hibernate functionality. + It is useful for the application to react to certain events that o= ccur + inside Hibernate. This allows for the implementation of generic = + functionality and the extension of Hibernate functionality. = @@ -39,7 +39,7 @@ = The Interceptor interface provides callback= s from the session to the = - application allowing the application to inspect and/or manipul= ate properties of a + application, allowing the application to inspect and/or manipu= late properties of a persistent object before it is saved, updated, deleted or load= ed. One = possible use for this is to track auditing information. For ex= ample, the following = Interceptor automatically sets the createTimestamp = @@ -49,7 +49,7 @@ = - You may either implement Interceptor direct= ly or (better) extend + You can either implement Interceptor direct= ly or extend EmptyInterceptor. = @@ -137,7 +137,7 @@ }]]> = - Interceptors come in two flavors: Session-s= coped and + There are two kinds of inteceptors: Session= -scoped and SessionFactory-scoped. = @@ -151,11 +151,11 @@ = A SessionFactory-scoped interceptor is regi= stered with the Configuration - object prior to building the SessionFactory= . In this case, the supplied interceptor - will be applied to all sessions opened from that Sess= ionFactory; this is true unless - a session is opened explicitly specifying the interceptor to u= se. SessionFactory-scoped - interceptors must be thread safe, taking care to not store ses= sion-specific state since multiple - sessions will use this interceptor (potentially) concurrently. + object prior to building the SessionFactory= . Unless + a session is opened explicitly specifying the interceptor to u= se, the supplied interceptor + will be applied to all sessions opened from that Sess= ionFactory. SessionFactory-scoped + interceptors must be thread safe. Ensure that you do not store= session-specific states, since multiple + sessions will use this interceptor potentially concurrently. = @@ -166,38 +166,38 @@ Event system = - If you have to react to particular events in your persistence = layer, you may + If you have to react to particular events in your persistence = layer, you can also use the Hibernate3 event architectur= e. The event - system can be used in addition or as a replacement for interce= ptors. + system can be used in addition, or as a replacement, for inter= ceptors. = - Essentially all of the methods of the Session interface correlate - to an event. You have a LoadEvent, a FlushEvent, etc - (consult the XML configuration-file DTD or the org.hi= bernate.event - package for the full list of defined event types). When a requ= est is made of one of + All the methods of the Session interface co= rrelate + to an event. You have a LoadEvent, a FlushEvent, etc. + Consult the XML configuration-file DTD or the org.hib= ernate.event + package for the full list of defined event types. When a reque= st is made of one of these methods, the Hibernate Session genera= tes an appropriate event and passes it to the configured event listeners for that= type. Out-of-the-box, these listeners implement the same processing in which those m= ethods always resulted. However, you are free to implement a customization of one of t= he listener interfaces - (i.e., the LoadEvent is processed by the re= gistered implemenation + (i.e., the LoadEvent is processed by the re= gistered implementation of the LoadEventListener interface), in whi= ch case their implementation would be responsible for processing any load() requests made of the Session. = - The listeners should be considered effectively singletons; mea= ning, they are shared between - requests, and thus should not save any state as instance varia= bles. + The listeners should be considered singletons. This means they= are shared between + requests, and should not save any state as instance variables. = - A custom listener should implement the appropriate interface f= or the event it wants to + 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-the-box as these are declar= ed non-final for this purpose). Custom listeners can either be registered programmat= ically through the Configuration object, or specified in the H= ibernate configuration - XML (declarative configuration through the properties file is = not supported). Here's an + XML. Declarative configuration through the properties file is = not supported. Here is an example of a custom load event listener: = @@ -227,7 +227,7 @@ ]]> = - Instead, you may register it programmatically: + Instead, you can register it programmatically: = Listeners registered declaratively cannot share instances. If = the same class name is used in multiple <listener/> elements= , each reference will - result in a separate instance of that class. If you need the c= apability to share + result in a separate instance of that class. If you need to sh= are listener instances between listener types you must use the pro= grammatic registration approach. = - Why implement an interface and define the specific type during= configuration? Well, a + Why implement an interface and define the specific type during= configuration? A listener implementation could implement multiple event listene= r interfaces. Having the type additionally defined during registration makes it easier = to turn custom listeners on or off during configuration. @@ -255,8 +255,8 @@ Hibernate declarative security Usually, declarative security in Hibernate applications is man= aged in a session facade - layer. Now, Hibernate3 allows certain actions to be permission= ed via JACC, and authorized = - via JAAS. This is optional functionality built on top of the e= vent architecture. + layer. Hibernate3 allows certain actions to be permissioned vi= a JACC, and authorized = + via JAAS. This is an optional functionality that is built on t= op of the event architecture. = @@ -270,13 +270,13 @@ ]]> = - Note that <listener type=3D"..." class=3D"..."/>= ; is just a shorthand + Note that <listener type=3D"..." class=3D"..."/>= ; is shorthand for <event type=3D"..."><listener class=3D".= .."/></event> when there is exactly one listener for a particular event type. = - Next, still in hibernate.cfg.xml, bind the = permissions to roles: + Next, while still in hibernate.cfg.xml, bin= d the permissions to roles: = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/example_mappings.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/example_mappings.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/example_mappings.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -27,9 +27,10 @@ = Example: Various Mappings - = + = + - This chapters shows off some more complex association mappings. + This chapters explores some more complex association mappings. = @@ -37,8 +38,8 @@ = The following model of the relationship between Emplo= yer and = - Employee uses an actual entity class (Employment) = - to represent the association. This is done because there might= be more than one + Employee uses an entity class (Emp= loyment) = + 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. @@ -53,7 +54,7 @@ = - Heres a possible mapping document: + Here is a possible mapping document: = @@ -106,7 +107,7 @@ ]]> = - And heres the table schema generated by SchemaExport. + Here is the table schema generated by SchemaExport. = Consider the following model of the relationships between Work, - Author and Person. We re= present the relationship - between Work and Author = as a many-to-many - association. We choose to represent the relationship between <= literal>Author = - and Person as one-to-one association. Anoth= er possibility would be to = + Author and Person. In th= e example, the relationship + between Work and Author = is represented as a many-to-many + association and the relationship between Author = + and Person is represented as one-to-one ass= ociation. Another possibility would be to = have Author extend Person. = = @@ -223,11 +224,11 @@ ]]> = - There are four tables in this mapping. works, = + There are four tables in this mapping: works, authors and persons hold wor= k, author and person data respectively. author_work is an= association - table linking authors to works. Heres the table schema, as generat= ed by - SchemaExport. + table linking authors to works. Here is the table schema, as gener= ated by + SchemaExport: = Customer/Order/Product = - Now consider a model of the relationships between Cus= tomer, - Order and LineItem and <= literal>Product. + In this section we consider a model of the relationships betwe= en Customer, + Order, Line Item and Product. There is a one-to-many association between Customer and - Order, but how should we represent Order / = - LineItem / Product? I've= chosen to map - LineItem as an association class representi= ng the many-to-many + Order, but how can you represent O= rder / = + LineItem / Product? In t= he example, = + LineItem is mapped as an association class = representing the many-to-many association between Order and Prod= uct. In - Hibernate, this is called a composite element. + Hibernate this is called a composite element. = @@ -291,7 +292,7 @@ = - The mapping document: + The mapping document will look like this: = @@ -379,12 +380,12 @@ Miscellaneous example mappings = - These examples are all taken from the Hibernate test suite. You - will find many other useful example mappings there. Look in the + These examples are available from the Hibernate test suite. You + will find many other useful example mappings there by searchin= g in the test folder of the Hibernate distribution. = - TODO: put words around this stuff + = "Typed" one-to-one association Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/example_parentchild.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/example_parentchild.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/example_parentchild.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -29,36 +29,36 @@ Example: Parent/Child = - One of the very first things that new users try to do with Hiberna= te is to model a parent / child type = - relationship. There are two different approaches to this. For vari= ous reasons the most convenient = + One of the first things that new users want to do with Hibernate i= s to model a parent/child type = + relationship. There are two different approaches to this. The most= convenient = approach, especially for new users, is to model both Pare= nt and Child = as entity classes with a <one-to-many> as= sociation from Parent = - to Child. (The alternative approach is to decla= re the Child as a = - <composite-element>.) Now, it turns out t= hat default semantics of a one to many = - association (in Hibernate) are much less close to the usual semant= ics 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 rel= ationship efficiently and elegantly. = - It's not at all difficult! + to Child. The alternative approach is to declar= e the Child as a = + <composite-element>. The default semantic= s of a one-to-many = + association in Hibernate are much less close to the usual semantic= s 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 relat= ionship efficiently and elegantly. = + = = A note about collections = - Hibernate collections are considered to be a logical part of t= heir owning entity; never of the - contained entities. This is a crucial distinction! It has the = following consequences: + Hibernate collections are considered to be a logical part of t= heir owning entity and not of the + contained entities. Be aware that this is a critical distincti= on that has the following consequences: = - When we remove / add an object from / to a collection, the= version number of the collection owner + When you remove/add an object from/to a collection, the ve= rsion number of the collection owner is incremented. - If an object that was removed from a collection is an inst= ance of a value type (eg, a composite + If an object that was removed from a collection is an inst= ance of a value type (e.g. a composite element), that object will cease to be persistent and its = state will be completely removed from the database. Likewise, adding a value type instance to th= e collection will cause its state to be immediately persistent. @@ -66,9 +66,9 @@ - On the other hand, if an entity is removed from a collecti= on (a one-to-many or many-to-many - association), it will not be deleted, by default. This beh= aviour is completely consistent - a - change to the internal state of another entity should not = cause the associated entity to vanish! + Conversely, if an entity is removed from a collection (a o= ne-to-many or many-to-many + association), it will not be deleted by default. This beha= vior is completely consistent; a + change to the internal state of another entity should not = cause the associated entity to vanish. Likewise, adding an entity to a collection does not cause = that entity to become persistent, by default. @@ -76,9 +76,9 @@ = - Instead, the default behaviour is that adding an entity to a c= ollection merely creates a link between - the two entities, while removing it removes the link. This is = very appropriate for all sorts of cases. - Where it is not appropriate at all is the case of a parent / c= hild relationship, where the life of the + Adding an entity to a collection, by default, merely creates a= link between + the two entities. Removing the entity will remove the link. Th= is is appropriate for all sorts of cases. + However, it is not appropriate in the case of a parent/child r= elationship. In this case, the life of the child is bound to the life cycle of the parent. = @@ -98,7 +98,7 @@ ]]> = - If we were to execute the following code + If we were to execute the following code: = This is not only inefficient, but also violates any N= OT NULL constraint on the - parent_id column. We can fix the nullabilit= y constraint violation by specifying + parent_id column. You can fix the nullabili= ty constraint violation by specifying not-null=3D"true" in the collection mapping: = @@ -138,21 +138,21 @@ However, this is not the recommended solution. - The underlying cause of this behaviour is that the link (the f= oreign key parent_id) = + The underlying cause of this behavior is that the link (the fo= reign key parent_id) = from p to c is not consi= dered part of the state of the = - Child object and is therefore not created i= n the INSERT. So the = + Child object and is therefore not created i= n the INSERT. The = solution is to make the link part of the Child mapping. = ]]> = - (We also need to add the parent property to= the Child class.) + You also need to add the parent property to= the Child class. = Now that the Child entity is managing the s= tate of the link, we tell the collection = - not to update the link. We use the inverse = attribute. + not to update the link. We use the inverse = attribute to do this: = @@ -161,7 +161,7 @@ ]]> = - The following code would be used to add a new Child + The following code would be used to add a new Child: = = - And now, only one SQL INSERT would be issue= d! + Only one SQL INSERT would now be issued. = - To tighten things up a bit, we could create an addChi= ld() method of + You could also create an addChild() method = of Parent. = @@ -186,7 +186,7 @@ }]]> = - Now, the code to add a Child looks like + The code to add a Child looks like this: = Cascading life cycle = - The explicit call to save() is still annoy= ing. We will address this by + You can address the frustrations of the explicit call to save() by using cascades. = @@ -211,7 +211,7 @@ ]]> = - This simplifies the code above to + This simplifies the code above to: = = - Similarly, we don't need to iterate over the children when sa= ving or deleting a Parent. + Similarly, we do not need to iterate over the children when s= aving or deleting a Parent. The following removes p and all its childr= en from the database. = @@ -229,7 +229,7 @@ session.flush();]]> = - However, this code + However, the following code: = = - will not remove c from the database; it wi= ll ony remove the link to p - (and cause a NOT NULL constraint violation= , in this case). You need to explicitly + will not remove c from the database. In th= is case, it will only remove the link to p + and cause a NOT NULL constraint violation.= You need to explicitly delete() the Child. = @@ -251,8 +251,8 @@ session.flush();]]> = - Now, in our case, a Child can't really exi= st without its parent. So if we remove - a Child from the collection, we really do = want it to be deleted. For this, we must + In our case, a Child cannot exist without = its parent. So if we remove + a Child from the collection, we do want it= to be deleted. To do this, we must use cascade=3D"all-delete-orphan". = @@ -262,8 +262,8 @@ ]]> = - Note: even though the collection mapping specifies i= nverse=3D"true", cascades are = - still processed by iterating the collection elements. So if y= ou require that an object be saved, = + Even though the collection mapping specifies inverse= =3D"true", 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 collect= ion. It is not enough to simply call setParent(). @@ -275,10 +275,10 @@ = Suppose we loaded up a Parent in one Session, made some changes = - in a UI action and wish to persist these changes in a new ses= sion by calling update(). = - The Parent will contain a collection of ch= ilden and, since cascading update is enabled, = + in a UI action and wanted to persist these changes in a new s= ession by calling update(). = + The Parent will contain a collection of ch= ildren and, since the cascading update is enabled, = Hibernate needs to know which children are newly instantiated= and which represent existing rows in the = - database. Lets assume that both Parent and= Child have genenerated + database. We will also assume that both Parent and Child have generated identifier properties of type Long. Hibern= ate will use the identifier and = version/timestamp property value to determine which of the ch= ildren are new. (See .) In H= ibernate3, it is no longer necessary to specify @@ -287,7 +287,7 @@ = The following code will update parent and = child and insert = - newChild. + newChild: = = - Well, that's all very well for the case of a generated identi= fier, but what about assigned identifiers - and composite identifiers? This is more difficult, since Hibe= rnate can't use the identifier property to - distinguish between a newly instantiated object (with an iden= tifier assigned by the user) and an = + This may be suitable for the case of a generated identifier, = but what about assigned identifiers + and composite identifiers? This is more difficult, since Hibe= rnate cannot use the identifier property to + distinguish between a newly instantiated object, with an iden= tifier 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, w= orst case, the database, to see if the = row exists. @@ -363,7 +363,7 @@ }]]> = - Don't worry; in Hibernate3 you don't need to write any of this kind of = code if you don't want to. + Do not worry; in Hibernate3 you do not need to write any of this kind o= f code if you do not want to. --> @@ -372,15 +372,15 @@ Conclusion = - There is quite a bit to digest here and it might look confusi= ng first time around. However, in practice, = - it all works out very nicely. Most Hibernate applications use= the parent / child pattern in many places. + The sections we have just covered can be a bit confusing. How= ever, 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 t= he above issues exist in the case of - <composite-element> mappings, which = have exactly the semantics of a parent / child - relationship. Unfortunately, there are two big limitations to= composite element classes: composite elements = - may not own collections, and they should not be the child of = any entity other than the unique parent. + <composite-element> mappings, which = have exactly the semantics of a parent/child + relationship. Unfortunately, there are two big limitations wi= th composite element classes: composite elements = + cannot own collections and they should not be the child of an= y entity other than the unique parent. = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/example_weblog.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/example_weblog.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/example_weblog.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -32,9 +32,9 @@ Persistent Classes = - The persistent classes represent a weblog, and an item posted + The persistent classes here represent a weblog and an item pos= ted in a weblog. They are to be modelled as a standard parent/child - relationship, but we will use an ordered bag, instead of a set. + relationship, but we will use an ordered bag, instead of a set: = Hibernate Mappings = - The XML mappings should now be quite straightforward. + The XML mappings are now straightforward. For example: = @@ -210,7 +210,7 @@ = The following class demonstrates some of the kinds of things - we can do with these classes, using Hibernate. + we can do with these classes using Hibernate: = Hibernate3 provides an innovative new approach to handling data wi= th "visibility" rules. - A Hibernate filter is a global, named, parame= terized filter that may be = + A Hibernate filter is a global, named, parame= terized filter that can be = enabled or disabled for a particular Hibernate session. = @@ -38,12 +38,12 @@ Hibernate filters = - Hibernate3 adds the ability to pre-define filter criteria and = attach those filters at both - a class and a collection level. A filter criteria is the abili= ty to define a restriction clause - very similiar to the existing "where" attribute available on t= he class and various collection - elements. Except these filter conditions can be parameterized.= The application can then make - the decision at runtime whether given filters should be enable= d and what their parameter - values should be. Filters can be used like database views, but= parameterized inside the + Hibernate3 has the ability to pre-define filter criteria and a= ttach those filters at both + a class level and a collection level. A filter criteria allows= you to define a restriction clause + similar to the existing "where" attribute available on the cla= ss and various collection + elements. These filter conditions, however, can be parameteriz= ed. The application can then + decide at runtime whether certain filters should be enabled an= d what their parameter + values should be. Filters can be used like database views, but= they are parameterized inside the application. = @@ -58,7 +58,7 @@ ]]> = - Then, this filter can be attached to a class: + This filter can then be attached to a class: = @@ -67,7 +67,7 @@ ]]> = - or, to a collection: + Or, to a collection: = @@ -75,26 +75,26 @@ ]]> = - or, even to both (or multiples of each) at the same time. + Or, to both or multiples of each at the same time. = The methods on Session are: enable= Filter(String filterName), getEnabledFilter(String filterName), and disableFilter(String filterName). - By default, filters are not enabled for a= given session; they must be explcitly + By default, filters are not enabled for a= given session. Filters must be enabled through use of the Session.enableFilter() method, which returns an - instance of the Filter interface. Using the= simple filter defined above, this - would look like: + instance of the Filter interface. If you us= ed the simple filter defined above, it would + look like this: = = - Note that methods on the org.hibernate.Filter interface do all= ow the method-chaining common to much of Hibernate. + Methods on the org.hibernate.Filter interface do allow the met= hod-chaining common to much of Hibernate. = - A full example, using temporal data with an effective record d= ate pattern: + The following is a full example, using temporal data with an e= ffective record date pattern: = @@ -126,7 +126,7 @@ ]]> = - Then, in order to ensure that you always get back currently ef= fective records, simply + In order to ensure that you are provided with currently effect= ive records, enable the filter on the session prior to retrieving employee = data: = @@ -138,32 +138,32 @@ ]]> = - In the HQL above, even though we only explicitly mentioned a s= alary constraint on the results, - because of the enabled filter the query will return only curre= ntly active employees who have - a salary greater than a million dollars. + Even though a salary constraint was mentioned explicitly on th= e results in the above HQL, + because of the enabled filter, the query will return only curr= ently active employees who have + a salary greater than one million dollars. = - Note: if you plan on using filters with outer joining (either = through HQL or load fetching) be - careful of the direction of the condition expression. Its saf= est to set this up for left - outer joining; in general, place the parameter first followed = by the column name(s) after + 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 s= afest to set this up for left + outer joining. Place the parameter first followed by the colum= n name(s) after the operator. = - After being defined a filter might be attached to multiple ent= ities and/or - collections each with its own condition. That can be tedious = when the - conditions are the same each time. Thus <filter-d= ef/> - allows defining a default condition, either as an attribute or= CDATA: + After being defined, a filter might be attached to multiple en= tities and/or + collections each with its own condition. This can be problema= tic when the + conditions are the same each time. Using <filter-= def/> + allows you to definine a default condition, either as an attri= bute or CDATA: = xyz">... abc=3Dxyz]]> = - This default condition will then be used whenever the filter i= s attached to something - without specifying a condition. Note that this means you can = give a specific condition - as part of the attachment of the filter which overrides the de= fault condition in that + This default condition will be used whenever the filter is att= ached to something + without specifying a condition. This means you can give a spe= cific condition + as part of the attachment of the filter that overrides the def= ault condition in that particular case. = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/inheritance_mapping.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/inheritance_mapping.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/inheritance_mapping.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -26,10 +26,10 @@ = - Inheritance Mapping + Inheritance mapping = - The Three Strategies + The three strategies = Hibernate supports the three basic inheritance mapping strateg= ies: @@ -68,25 +68,25 @@ = It is possible to use different mapping strategies for differe= nt - branches of the same inheritance hierarchy, and then make use = of implicit + branches of the same inheritance hierarchy. You can then make = use of implicit polymorphism to achieve polymorphism across the whole hierarch= y. However, = Hibernate does not support mixing <subclass>, - and <joined-subclass> and = + <joined-subclass> and = <union-subclass> mappings under the s= ame root <class> element. It is possible to mi= x together - the table per hierarchy and table per subclass strategies, und= er the + the table per hierarchy and table per subclass strategies unde= r the the same <class> element, by combinin= g the = <subclass> and <join><= /literal> - elements (see below). + elements (see below for an example). = It is possible to define subclass, union-subclass, - and joined-subclass mappings in separate m= apping documents, directly beneath - hibernate-mapping. This allows you to exte= nd a class hierachy just by adding + and joined-subclass mappings in separate m= apping documents directly beneath + hibernate-mapping. This allows you to exte= nd a class hierarchy by adding a new mapping file. You must specify an extends attribute in the subclass mapping, - naming a previously mapped superclass. Note: Previously this = feature made the ordering of the mapping - documents important. Since Hibernate3, the ordering of mappin= g files does not matter when using the + naming a previously mapped superclass. Previously this featur= e made the ordering of the mapping + documents important. Since Hibernate3, the ordering of mappin= g files is irrelevant when using the extends keyword. The ordering inside a single mapping file st= ill needs to be defined as superclasses before subclasses. @@ -103,10 +103,10 @@ Table per class hierarchy = - Suppose we have an interface Payment, with = implementors + Suppose we have an interface Payment with t= he implementors CreditCardPayment, CashPayment, - ChequePayment. The table per hierarchy mapp= ing would - look like: + and ChequePayment. The table per hierarchy = mapping would + display in the following way: = @@ -129,9 +129,9 @@ ]]> = - Exactly one table is required. There is one big limitation of = this mapping = + Exactly one table is required. There is a limitation of this m= apping = strategy: columns declared by the subclasses, such as CCTYPE, = - may not have NOT NULL constraints. + cannot have NOT NULL constraints. = @@ -140,7 +140,7 @@ Table per subclass = - A table per subclass mapping would look like: + A table per subclass mapping looks like this: = @@ -166,25 +166,25 @@ = Four tables are required. The three subclass tables have prima= ry - key associations to the superclass table (so the relational mo= del - is actually a one-to-one association). + key associations to the superclass table so the relational mod= el + is actually a one-to-one association. = = - Table per subclass, using a discriminator + Table per subclass: using a discriminator = - Note that Hibernate's implementation of table per subclass req= uires - no discriminator column. Other object/relational mappers use a - different implementation of table per subclass which requires = a type + Hibernate's implementation of table per subclass + does not require a discriminator column. Other object/relation= al mappers use a + different implementation of table per subclass that requires a= type discriminator column in the superclass table. The approach tak= en by - Hibernate is much more difficult to implement but arguably more - correct from a relational point of view. If you would like to = use + Hibernate is much more difficult to implement, but arguably mo= re + correct from a relational point of view. If you want to use a discriminator column with the table per subclass strategy, y= ou - may combine the use of <subclass> and = - <join>, as follow: + can combine the use of <subclass> and = + <join>, as follows: = @@ -227,8 +227,8 @@ Mixing table per class hierarchy with table per subclass</t= itle> = <para> - You may even mix the table per hierarchy and table per subclas= s strategies - using this approach: + You can even mix the table per hierarchy and table per subclas= s strategies + using the following approach: </para> = <programlisting><![CDATA[<class name=3D"Payment" table=3D"PAYMENT"> @@ -266,8 +266,8 @@ <title>Table per concrete class = - There are two ways we could go about mapping the table per con= crete class - strategy. The first is to use <union-subclass><= /literal>. + There are two ways we can map the table per concrete class + strategy. First, you can use <union-subclass>. = @@ -296,23 +296,23 @@ The limitation of this approach is that if a property is mappe= d on the = superclass, the column name must be the same on all subclass t= ables. - (We might relax this in a future release of Hibernate.) The id= entity - generator strategy is not allowed in union subclass inheritance, indeed - the primary key seed has to be shared accross all unioned subclasses - of a hierarchy. + The identity generator strategy is not allowed in union subcla= ss inheritance. + The primary key seed has to be shared across all unioned subclasses + of a hierarchy. + = = If your superclass is abstract, map it with abstract= =3D"true". - Of course, if it is not abstract, an additional table (default= s to - PAYMENT in the example above) is needed to = hold instances + If it is not abstract, an additional table (it defaults to + PAYMENT in the example above), is needed to= hold instances of the superclass. = = - Table per concrete class, using implicit polymorphism</titl= e> + <title>Table per concrete class using implicit polymorphism = An alternative approach is to make use of implicit polymorphis= m: @@ -343,12 +343,12 @@ ]]> = - Notice that nowhere do we mention the Payment interface = - explicitly. Also notice that properties of Payment are = + Notice that the Payment interface = + is not mentioned explicitly. Also notice that properties of Payment are = mapped in each of the subclasses. If you want to avoid duplica= tion, consider using XML entities - (e.g. [ <!ENTITY allproperties SYSTEM "allproperti= es.xml"> ] - in the DOCTYPE declartion and = + (for example, [ <!ENTITY allproperties SYSTEM "all= properties.xml"> ] + in the DOCTYPE declaration and = &allproperties; in the mapping). = @@ -372,15 +372,15 @@ = = - + Mixing implicit polymorphism with other inheritance mapping= s = - There is one further thing to notice about this mapping. Since= the subclasses = - are each mapped in their own <class> = element (and since + Since the subclasses = + are each mapped in their own <class> = element, and since Payment is just an interface), each of the = subclasses could = - easily be part of another inheritance hierarchy! (And you can = still use polymorphic - queries against the Payment interface.) + easily be part of another inheritance hierarchy. You can still= use polymorphic + queries against the Payment interface. = @@ -412,12 +412,12 @@ ]]> = - Once again, we don't mention Payment explic= itly. If we - execute a query against the Payment interfa= ce - for - example, from Payment - Hibernate + Once again, Payment is not mentioned explic= itly. If we + execute a query against the Payment interfa= ce, for + example from Payment, Hibernate automatically returns instances of CreditCardPayment<= /literal> (and its subclasses, since they also implement Paymen= t), - CashPayment and ChequePayment but + CashPayment and ChequePayment, but not instances of NonelectronicTransaction. = @@ -429,7 +429,7 @@ Limitations = - There are certain limitations to the "implicit polymorphism" a= pproach to + There are limitations to the "implicit polymorphism" approach = to the table per concrete-class mapping strategy. There are somew= hat less restrictive limitations to <union-subclass> mappings. Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/performance.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/performance.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/performance.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -32,9 +32,9 @@ Fetching strategies = - A fetching strategy is the strategy Hiber= nate will use for = - retrieving associated objects if the application needs to navi= gate the association. = - Fetch strategies may be declared in the O/R mapping metadata, = or over-ridden by a = + Hibernate uses a fetching strategy to + retrieve associated objects if the application needs to naviga= te the association. = + Fetch strategies can be declared in the O/R mapping metadata, = or over-ridden by a = particular HQL or Criteria query. = @@ -45,35 +45,35 @@ - Join fetching - Hibernate retriev= es the + Join fetching: Hibernate retrieve= s the associated instance or collection in the same SELECT, using an OUTER JOIN. - Select fetching - a second SELECT + Select fetching: a second SELECT is used to retrieve the associated entity or collectio= n. Unless you explicitly disable lazy fetching by specifying lazy=3D"false", = - this second select will only be executed when you actu= ally access the + this second select will only be executed when you acce= ss the association. - Subselect fetching - a second SELECT + Subselect fetching: a second SELECT is used to retrieve the associated collections for all= entities retrieved in a previous query or fetch. Unless you explicitly disable= lazy fetching by specifying = lazy=3D"false", this second select = will only be executed when you = - actually access the association. + access the association. - Batch fetching - an optimization = strategy - for select fetching - Hibernate retrieves a batch of e= ntity instances = - or collections in a single SELECT, = by specifying = - a list of primary keys or foreign keys. + Batch fetching: an optimization s= trategy + for select fetching. Hibernate retrieves a batch of en= tity instances = + or collections in a single SELECT b= y specifying = + a list of primary or foreign keys. @@ -85,45 +85,45 @@ - Immediate fetching - an associati= on, collection or - attribute is fetched immediately, when the owner is lo= aded. + Immediate fetching: an associatio= n, collection or + attribute is fetched immediately when the owner is loa= ded. - Lazy collection fetching - a coll= ection is fetched = - when the application invokes an operation upon that co= llection. (This - is the default for collections.) + Lazy collection fetching: a colle= ction is fetched = + when the application invokes an operation upon that co= llection. This + is the default for collections. - "Extra-lazy" collection fetching = - individual + "Extra-lazy" collection fetching:= individual elements of the collection are accessed from the datab= ase as needed. Hibernate tries not to fetch the whole collection into= memory unless - absolutely needed (suitable for very large collections) + absolutely needed. It is suitable for large collection= s. - Proxy fetching - a single-valued = association is = + Proxy fetching: a single-valued a= ssociation is = fetched when a method other than the identifier getter= is invoked upon the associated object. - "No-proxy" fetching - a single-va= lued association is = + "No-proxy" fetching: a single-val= ued association is = fetched when the instance variable is accessed. Compar= ed to proxy fetching, = - this approach is less lazy (the association is fetched= even when only the = - identifier is accessed) but more transparent, since no= proxy is visible to = + this approach is less lazy; the association is fetched= even when only the = + identifier is accessed. It is also more transparent, = since no proxy is visible to = the application. This approach requires buildtime byte= code instrumentation = and is rarely necessary. - Lazy attribute fetching - an attr= ibute or single + Lazy attribute fetching: an attri= bute or single valued association is fetched when the instance variab= le is accessed. = This approach requires buildtime bytecode instrumentat= ion and is rarely = necessary. @@ -133,8 +133,8 @@ = We have two orthogonal notions here: when= is the association - fetched, and how is it fetched (what SQL = is used). Don't - confuse them! We use fetch to tune performa= nce. We may use = + fetched and how is it fetched. It is impo= rtant that you do not + confuse them. We use fetch to tune performa= nce. We can use = lazy to define a contract for what data is = always available = in any detached instance of a particular class. @@ -144,19 +144,19 @@ = By default, Hibernate3 uses lazy select fetching for colle= ctions and lazy proxy - fetching for single-valued associations. These defaults ma= ke sense for almost - all associations in almost all applications. = + fetching for single-valued associations. These defaults ma= ke sense for most + associations in the majority of applications. = = - Note: if you set = + If you set = hibernate.default_batch_fetch_size, Hib= ernate will use the = - batch fetch optimization for lazy fetching (this optimizat= ion may also be enabled = - at a more granular level). + batch fetch optimization for lazy fetching. This optimizat= ion can also be enabled = + at a more granular level. = - However, lazy fetching poses one problem that you must be = aware of. Access to a = + Please be aware that access to a = lazy association outside of the context of an open Hiberna= te session will result = in an exception. For example: @@ -177,22 +177,22 @@ Since the permissions collection was not initialized when = the = Session was closed, the collection will= not be able to = load its state. Hibernate does not support lazy = initialization = - for detached objects. The fix is to move the co= de that reads = + for detached objects. This can be fixed by movi= ng the code that reads = from the collection to just before the transaction is comm= itted. = - Alternatively, we could use a non-lazy collection or assoc= iation, = + Alternatively, you can use a non-lazy collection or associ= ation, = by specifying lazy=3D"false" for the as= sociation mapping. However, it is intended that lazy initialization be used f= or almost all = collections and associations. If you define too many non-l= azy associations = - in your object model, Hibernate will end up needing to fet= ch the entire = - database into memory in every transaction! + in your object model, Hibernate will fetch the entire = + database into memory in every transaction. = - On the other hand, we often want to choose join fetching (= which is non-lazy by = - nature) instead of select fetching in a particular transac= tion. We'll now see + On the other hand, you can use join fetching, which is non= -lazy by = + nature, instead of select fetching in a particular transac= tion. We will now explain how to customize the fetching strategy. In Hibernate3, the= mechanisms for choosing a fetch strategy are identical for single-valued = associations and collections. @@ -244,13 +244,13 @@ = - No matter what fetching strategy you use, the defined non-= lazy graph is guaranteed - to be loaded into memory. Note that this might result in s= everal immediate selects + Irrespective of the fetching strategy you use, the defined= non-lazy graph is guaranteed + to be loaded into memory. This might, however, result in s= everal immediate selects being used to execute a particular HQL query. = - Usually, we don't use the mapping document to customize fe= tching. Instead, we + Usually, the mapping document is not used to customize fet= ching. Instead, we keep the default behavior, and override it for a particula= r transaction, using = left join fetch in HQL. This tells Hibe= rnate to fetch = the association eagerly in the first select, using an oute= r join. In the @@ -259,9 +259,9 @@ = - If you ever feel like you wish you could change the fetchi= ng strategy used by - get() or load(), sim= ply use a = - Criteria query, for example: + If you want to change the fetching strategy used by + get() or load(), you= can use a = + Criteria query. For example: = = - (This is Hibernate's equivalent of what some ORM solutions= call a "fetch plan".) + This is Hibernate's equivalent of what some ORM solutions = call a "fetch plan". = - A completely different way to avoid problems with N+1 sele= cts is to use the = + A completely different approach to problems with N+1 selec= ts is to use the = second-level cache. = @@ -288,11 +288,11 @@ of persistent collections. However, a different mechanism = is needed for lazy behavior in single-ended associations. The target entity o= f the association must be proxied. Hibernate implements lazy initializing proxies= for persistent objects - using runtime bytecode enhancement (via the excellent CGLI= B library). + using runtime bytecode enhancement which is accessed via t= he CGLIB library. = - By default, Hibernate3 generates proxies (at startup) for = all persistent classes + At startup, Hibernate3 generates proxies by default for al= l persistent classes and uses them to enable lazy fetching of many-to-= one and one-to-one associations. @@ -300,13 +300,12 @@ The mapping file may declare an interface to use as the pr= oxy interface for that class, with the proxy attribute. By def= ault, Hibernate uses a subclass - of the class. Note that the proxied class must i= mplement a default constructor - with at least package visibility. We recommend this constr= uctor for all persistent classes! + of the class. The proxied class must implement a= default constructor + with at least package visibility. This constructor is reco= mmended for all persistent classes. = - There are some gotchas to be aware of when extending this = approach to polymorphic - classes, eg. + There are potential problems to note when extending this a= pproach to polymorphic classes.For example: = @@ -329,7 +328,7 @@ }]]> = - Secondly, it is possible to break proxy =3D=3D. + Secondly, it is possible to break proxy =3D=3D: = = - Third, you may not use a CGLIB proxy for a final<= /literal> class or a class + Third, you cannot use a CGLIB proxy for a final class or a class with any final methods. = - Finally, if your persistent object acquires any resources = upon instantiation (eg. in + 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 pe= rsistent class. = These problems are all due to fundamental limitations in J= ava's single inheritance model. - If you wish to avoid these problems your persistent classe= s must each implement an interface - that declares its business methods. You should specify the= se interfaces in the mapping file. eg. + To avoid these problems your persistent classes must each = implement an interface + that declares its business methods. You should specify the= se interfaces in the mapping file where = + CatImpl implements the interface Cat and DomesticCatImpl + implements the interface DomesticCat. For exam= ple: = = @@ -370,36 +371,40 @@ ]]> = - where CatImpl implements the interface = Cat and - DomesticCatImpl implements the interfac= e DomesticCat. Then - proxies for instances of Cat and DomesticCat may be returned - by load() or iterate(). (Note that list() - does not usually return proxies.) + Then proxies for instances of Cat and <= literal>DomesticCat can be returned + by load() or iterate(). = = = - + = + Note + + list() does not usually return proxies. + + + = + Relationships are also lazily initialized. This means you = must declare any properties to be of type Cat, not CatImpl. = - Certain operations do not require pro= xy initialization + Certain operations do not require pro= xy initialization: = - equals(), if the persistent cla= ss does not override + equals(): if the persistent cla= ss does not override equals() - hashCode(), if the persistent c= lass does not override + hashCode(): if the persistent c= lass does not override hashCode() @@ -417,8 +422,8 @@ = By choosing lazy=3D"no-proxy" instead o= f the default = - lazy=3D"proxy", we can avoid the proble= ms associated with typecasting. - However, we will require buildtime bytecode instrumentatio= n, and all operations + lazy=3D"proxy", you can avoid problems = associated with typecasting. + However, buildtime bytecode instrumentation is required, a= nd all operations will result in immediate proxy initialization. = @@ -429,19 +434,19 @@ = A LazyInitializationException will be t= hrown by Hibernate if an uninitialized = - collection or proxy is accessed outside of the scope of th= e Session, ie. when = + collection or proxy is accessed outside of the scope of th= e Session, i.e., when = the entity owning the collection or having the reference t= o the proxy is in the detached state. = - Sometimes we need to ensure that a proxy or collection is = initialized before closing the - Session. Of course, we can alway force = initialization by calling + Sometimes a proxy or collection needs to be initialized be= fore closing the + Session. You can force initialization b= y calling cat.getSex() or cat.getKittens= ().size(), for example. - But that is confusing to readers of the code and is not co= nvenient for generic code. + However, this can be confusing to readers of the code and = it is not convenient for generic code. = - The static methods Hibernate.initialize() and Hibernate.isInitialized() + The static methods Hibernate.initialize() and Hibernate.isInitialized(), provide the application with a convenient way of working w= ith lazily initialized collections or proxies. Hibernate.initialize(cat) will= force the initialization of a proxy, cat, as long as its Session is still open. @@ -450,7 +455,7 @@ = - Another option is to keep the Session o= pen until all needed + Another option is to keep the Session o= pen until all required collections and proxies have been loaded. In some applicat= ion architectures, particularly where the code that accesses data using Hiber= nate, and the code that uses it are in different application layers or different p= hysical processes, it = @@ -462,7 +467,7 @@ In a web-based application, a servlet filter can b= e used to close the - Session only at the very end of= a user request, once + Session only at the end of a us= er 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 appl= ication infrastructure. = @@ -475,7 +480,7 @@ In an application with a separate business tier, t= he business logic must - "prepare" all collections that will be needed by t= he web tier before + "prepare" all collections that the web tier needs = before returning. This means that the business tier shoul= d load all the data and return all the data already initialized to the pre= sentation/web tier that is required for a particular use case. Usually, th= e application calls @@ -489,18 +494,18 @@ - You may also attach a previously loaded object to = a new Session + You can also attach a previously loaded object to = a new Session with merge() or lock()= before - accessing uninitialized collections (or other prox= ies). No, Hibernate does not, - and certainly should not do t= his automatically, since it = - would introduce ad hoc transaction semantics! + accessing uninitialized collections or other proxi= es. Hibernate does not, + and certainly should not, do = this automatically since it = + would introduce impromptu transaction semantics. = - Sometimes you don't want to initialize a large collection,= but still need some - information about it (like its size) or a subset of the da= ta. + Sometimes you do not want to initialize a large collection= , but still need some + information about it, like its size, for example, or a sub= set of the data. = @@ -522,29 +527,29 @@ Using batch fetching = - Hibernate can make efficient use of batch fetching, that i= s, Hibernate can load several uninitialized - proxies if one proxy is accessed (or collections. Batch fe= tching is an optimization of the lazy select - fetching strategy. There are two ways you can tune batch f= etching: on the class and the collection level. + Using batch fetching, Hibernate can load several uninitial= ized + proxies if one proxy is accessed. Batch fetching is an opt= imization of the lazy select + fetching strategy. There are two ways you can configure ba= tch fetching: on the class level and the collection level. = - Batch fetching for classes/entities is easier to understan= d. Imagine you have the following situation - at runtime: You have 25 Cat instances l= oaded in a Session, each + Batch fetching for classes/entities is easier to understan= d. Consider the following example: + at runtime you have 25 Cat instances lo= aded in a Session, and each Cat has a reference to its own= er, a Person. The Person class is mapped with a proxy= , lazy=3D"true". If you now - iterate through all cats and call getOwner() on each, Hibernate will by default - execute 25 SELECT statements, to retrie= ve the proxied owners. You can tune this + iterate through all cats and call getOwner() on each, Hibernate will, by default, + execute 25 SELECT statements to retriev= e the proxied owners. You can tune this behavior by specifying a batch-size in = the mapping of Person: = ...]]> = - Hibernate will now execute only three queries, the pattern= is 10, 10, 5. + Hibernate will now execute only three queries: the pattern= is 10, 10, 5. = - You may also enable batch fetching of collections. For exa= mple, if each Person has + You can also enable batch fetching of collections. For exa= mple, if each Person has a lazy collection of Cats, and 10 perso= ns are currently loaded in the Session, iterating through all persons = will generate 10 SELECTs, one for every call to getCats(). If you= enable batch fetching for the @@ -565,9 +570,9 @@ = - Batch fetching of collections is particularly useful if yo= u have a nested tree of items, ie. - the typical bill-of-materials pattern. (Although a nested set or a - materialized path might be a better o= ption for read-mostly trees.) + Batch fetching of collections is particularly useful if yo= u have a nested tree of items, i.e. + the typical bill-of-materials pattern. However, a nested set or a + materialized path might be a better o= ption for read-mostly trees. = @@ -576,9 +581,9 @@ Using subselect fetching = - If one lazy collection or single-valued proxy has to be fe= tched, Hibernate loads all of + If one lazy collection or single-valued proxy has to be fe= tched, Hibernate will load all of them, re-running the original query in a subselect. This w= orks in the same way as - batch-fetching, without the piecemeal loading. + batch-fetching but without the piecemeal loading. = @@ -591,10 +596,10 @@ Hibernate3 supports the lazy fetching of individual proper= ties. This optimization technique is also known as fetch groups. Please= note that this is mostly a - marketing feature, as in practice, optimizing row reads is= much more important than - optimization of column reads. However, only loading some p= roperties of a class might - be useful in extreme cases, when legacy tables have hundre= ds of columns and the data model - can not be improved. + marketing feature; optimizing row reads is much more impor= tant than + optimization of column reads. However, only loading some p= roperties of a class could + be useful in extreme cases. For example, when legacy table= s have hundreds of columns and the data model + cannot be improved. = @@ -612,9 +617,9 @@ ]]> = - Lazy property loading requires buildtime bytecode instrume= ntation! If your persistent - classes are not enhanced, Hibernate will silently ignore l= azy property settings and - fall back to immediate fetching. + Lazy property loading requires buildtime bytecode instrume= ntation. If your persistent + classes are not enhanced, Hibernate will ignore lazy prope= rty settings and + return to immediate fetching. = @@ -636,14 +641,14 @@ ]]> = - A different (better?) way to avoid unnecessary column read= s, at least for - read-only transactions is to use the projection features o= f HQL or Criteria + A different way of avoiding unnecessary column reads, at l= east for + read-only transactions, is to use the projection features = of HQL or Criteria queries. This avoids the need for buildtime bytecode proce= ssing and is certainly a preferred solution. = - You may force the usual eager fetching of properties using= fetch all + You can force the usual eager fetching of properties using= fetch all properties in HQL. = @@ -657,19 +662,19 @@ A Hibernate Session is a transaction-level = cache of persistent data. It is possible to configure a cluster or JVM-level (Session= Factory-level) cache on = - a class-by-class and collection-by-collection basis. You may e= ven plug in a clustered cache. Be = - careful. Caches are never aware of changes made to the persist= ent store by another application = - (though they may be configured to regularly expire cached data= ). + a class-by-class and collection-by-collection basis. You can e= ven plug in a clustered cache. Be = + aware that caches are not aware of changes made to the persist= ent store by another application. = + They can, however, be configured to regularly expire cached da= ta. = You have the option to tell Hibernate which caching implementa= tion to use by specifying the name of a class that implements org.hi= bernate.cache.CacheProvider using the property hibernate.cache.provider_class. Hibernate - comes bundled with a number of built-in integrations with open= -source cache providers - (listed below); additionally, you could implement your own and= plug it in as - outlined above. Note that versions prior to 3.2 defaulted to = use EhCache as the - default cache provider; that is no longer the case as of 3.2. + is bundled with a number of built-in integrations with the ope= n-source cache providers + that are listed below. You can also implement your own and plu= g it in as + outlined above. Note that versions prior to 3.2 use EhCache as= the default + cache provider. =
@@ -767,16 +772,16 @@ = - region (optional, defaults = to the class or - collection role name) specifies the name of th= e second level cache = + region (optional: defaults = to the class or + collection role name): specifies the name of t= he second level cache = region = - include (optional, defaults= to all) = - non-lazy specifies that pro= perties of the entity mapped - with lazy=3D"true" may not = be cached when attribute-level + include (optional: defaults= to all) = + non-lazy: specifies that pr= operties of the entity mapped + with lazy=3D"true" cannot b= e cached when attribute-level lazy fetching is enabled = @@ -784,7 +789,7 @@ = - Alternatively (preferably?), you may specify <= class-cache> and = + Alternatively, you can specify <class-cache>= ; and = <collection-cache> elements in hibernate.cfg.xml. = @@ -798,9 +803,9 @@ Strategy: read only = - If your application needs to read but never modify instanc= es of a persistent class, a = - read-only cache may be used. This is th= e simplest and best performing - strategy. It's even perfectly safe for use in a cluster. + If your application needs to read, but not modify, instanc= es of a persistent class, a = + read-only cache can be used. This is th= e simplest and optimal performing + strategy. It is even safe for use in a cluster. = @@ -818,11 +823,11 @@ If the application needs to update data, a read-w= rite cache might be appropriate. = This cache strategy should never be used if serializable t= ransaction isolation level is required. = If the cache is used in a JTA environment, you must specif= y the property = - hibernate.transaction.manager_lookup_class, naming a strategy for obtaining the = + hibernate.transaction.manager_lookup_class and naming a strategy for obtaining the = JTA TransactionManager. In other enviro= nments, you should ensure that the transaction = is completed when Session.close() or Session.disconnect() is called. = - If you wish to use this strategy in a cluster, you should = ensure that the underlying cache implementation = - supports locking. The built-in cache providers do not. + If you want to use this strategy in a cluster, you should = ensure that the underlying cache implementation = + supports locking. The built-in cache providers d= o not support locking. = @@ -840,8 +845,8 @@ Strategy: nonstrict read/write = - If the application only occasionally needs to update data = (ie. if it is extremely unlikely that two = - transactions would try to update the same item simultaneou= sly) and strict transaction isolation is + If the application only occasionally needs to update data = (i.e. if it is extremely unlikely that two = + transactions would try to update the same item simultaneou= sly), and strict transaction isolation is not required, a nonstrict-read-write ca= che might be appropriate. If the cache is = used in a JTA environment, you must specify hiber= nate.transaction.manager_lookup_class. = In other environments, you should ensure that the transact= ion is completed when = @@ -855,7 +860,7 @@ = The transactional cache strategy provid= es support for fully transactional cache - providers such as JBoss TreeCache. Such a cache may only b= e used in a JTA environment and you must = + providers such as JBoss TreeCache. Such a cache can only b= e used in a JTA environment and you must = specify hibernate.transaction.manager_lookup_clas= s. = = @@ -947,16 +952,16 @@ = Whenever you pass an object to save(), update() - or saveOrUpdate() and whenever you retrieve= an object using = + or saveOrUpdate(), and whenever you retriev= e an object using = load(), get(), = list(), = iterate() or scroll(), t= hat object is added = to the internal cache of the Session. = When flush() is subsequently called, the st= ate of that object will = - be synchronized with the database. If you do not want this syn= chronization to occur or = + be synchronized with the database. If you do not want this syn= chronization to occur, or = if you are processing a huge number of objects and need to man= age memory efficiently, = - the evict() method may be used to remove th= e object and its collections = + the evict() method can be used to remove th= e object and its collections = from the first-level cache. = @@ -973,7 +978,7 @@ = - To completely evict all objects from the session cache, call <= literal>Session.clear() + To evict all objects from the session cache, call Ses= sion.clear() = @@ -989,31 +994,31 @@ = The CacheMode controls how a particular ses= sion interacts with the second-level - cache. + cache: = - CacheMode.NORMAL - read items from and writ= e items to the second-level cache + CacheMode.NORMAL: will read items from and = write items to the second-level cache - CacheMode.GET - read items from the second-= level cache, but don't write to + CacheMode.GET: will read items from the sec= ond-level cache. Do not write to the second-level cache except when updating data - CacheMode.PUT - write items to the second-l= evel cache, but don't read from + CacheMode.PUT: will write items to the seco= nd-level cache. Do not read from the second-level cache - CacheMode.REFRESH - write items to the seco= nd-level cache, but don't read from - the second-level cache, bypass the effect of hibernat= e.cache.use_minimal_puts, forcing + CacheMode.REFRESH: will write items to the = second-level cache. Do not read from + the second-level cache. Bypass the effect of hiberna= te.cache.use_minimal_puts forcing a refresh of the second-level cache for all items read from th= e database @@ -1029,8 +1034,8 @@ .getEntries();]]> = - You'll need to enable statistics, and, optionally, force Hiber= nate to keep the cache entries in a - more human-understandable format: + You will need to enable statistics and, optionally, force Hibe= rnate to keep the cache entries in a + more readable format: = The Query Cache = - Query result sets may also be cached. This is only useful for = queries that are run - frequently with the same parameters. To use the query cache yo= u must first enable it: + Query result sets can also be cached. This is only useful for = queries that are run + frequently with the same parameters. You will first need to en= able the query cache: = = = - This setting causes the creation of two new cache regions - on= e holding cached query = + This setting creates two new cache regions: one holding cached= query = result sets (org.hibernate.cache.StandardQueryCache), the other = holding timestamps of the most recent updates to queryable tab= les = (org.hibernate.cache.UpdateTimestampsCache)= . Note that the query cache does not cache the state of the actual entities in the r= esult set; it caches = - only identifier values and results of value type. So the query= cache should always be + only identifier values and results of value type. The query ca= che should always be used in conjunction with the second-level cache. = - Most queries do not benefit from caching, so by default querie= s are not cached. To + Most queries do not benefit from caching, so by default, queri= es are not cached. To enable caching, call Query.setCacheable(true). This call allows the query to look for existing cache results or add its result= s to the cache when it is executed. = - If you require fine-grained control over query cache expiratio= n policies, you may + If you require fine-grained control over query cache expiratio= n policies, you can specify a named cache region for a particular query by calling = Query.setCacheRegion(). @@ -1093,9 +1098,9 @@ Understanding Collection performance = - We've already spent quite some time talking about collections. - In this section we will highlight a couple more issues about - how collections behave at runtime. + In the previous sections we have covered collections and their= applications. + In this section we explore some more issues in relation to + collections at runtime. = @@ -1108,10 +1113,10 @@ collections of values - one to many associations + one-to-many associations - many to many associations + many-to-many associations = @@ -1137,42 +1142,42 @@ = - All indexed collections (maps, lists, arrays) have a prima= ry key consisting + All indexed collections (maps, lists, and arrays) have a p= rimary key consisting of the <key> and <ind= ex> - columns. In this case collection updates are usually extre= mely efficient - - the primary key may be efficiently indexed and a particula= r row may be efficiently + columns. In this case, collection updates are extremely ef= ficient. + The primary key can be efficiently indexed and a particula= r row can be efficiently located when Hibernate tries to update or delete it. = Sets have a primary key consisting of <key>= and element - columns. This may be less efficient for some types of coll= ection element, particularly - composite elements or large text or binary fields; the dat= abase may not be able to index - a complex primary key as efficiently. On the other hand, = for one to many or many to many + columns. This can be less efficient for some types of coll= ection element, particularly + composite elements or large text or binary fields, as the = database may not be able to index + a complex primary key as efficiently. However, for one-to= -many or many-to-many associations, particularly in the case of synthetic identi= fiers, it is likely to be just - as efficient. (Side-note: if you want SchemaExpor= t to actually create - the primary key of a <set> for yo= u, you must declare all columns - as not-null=3D"true".) + as efficient. If you want SchemaExport = to actually create + the primary key of a <set>, you m= ust declare all columns + as not-null=3D"true". = <idbag> mappings define a surroga= te key, so they are - always very efficient to update. In fact, they are the bes= t case. + efficient to update. In fact, they are the best case. = - Bags are the worst case. Since a bag permits duplicate ele= ment values and has no - index column, no primary key may be defined. Hibernate has= no way of distinguishing + Bags are the worst case since they permit duplicate elemen= t 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 DELETE) and recreating the= collection whenever it - changes. This might be very inefficient. + in a single DELETE and recreating the c= ollection whenever it + changes. This can be inefficient. = - Note that for a one-to-many association, the "primary key"= may not be the physical - primary key of the database table - but even in this case,= the above classification - is still useful. (It still reflects how Hibernate "locates= " individual rows of the - collection.) + For a one-to-many association, the "primary key" may not b= e the physical + primary key of the database table. Even in this case, the = above classification + is still useful. It reflects how Hibernate "locates" indiv= idual rows of the + collection. = @@ -1182,29 +1187,29 @@ = From the discussion above, it should be clear that indexed= collections - and (usually) sets allow the most efficient operation in t= erms of adding, + and sets allow the most efficient operation in terms of ad= ding, removing and updating elements. = There is, arguably, one more advantage that indexed collec= tions have over sets for - many to many associations or collections of values. Becaus= e of the structure of a - Set, Hibernate doesn't ever UP= DATE a row when + many-to-many associations or collections of values. Becaus= e of the structure of a + Set, Hibernate does not UPDATE= a row when an element is "changed". Changes to a Set always work via - INSERT and DELETE (o= f individual rows). Once - again, this consideration does not apply to one to many as= sociations. + INSERT and DELETE of= individual rows. Once + again, this consideration does not apply to one-to-many as= sociations. = - After observing that arrays cannot be lazy, we would concl= ude that lists, maps and = + After observing that arrays cannot be lazy, you can conclu= de that lists, maps and = idbags are the most performant (non-inverse) collection ty= pes, with sets not far = - behind. Sets are expected to be the most common kind of co= llection in Hibernate = + 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, we usua= lly see that most collections + However, in well-designed Hibernate domain models, most co= llections are in fact one-to-many associations with inverse= =3D"true". 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. @@ -1216,13 +1221,13 @@ Bags and lists are the most efficient inverse collectio= ns = - Just before you ditch bags forever, there is a particular = case in which bags (and also lists) - are much more performant than sets. For a collection with = inverse=3D"true" - (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 + There is a particular case, however, in which bags, and al= so lists, + are much more performant than sets. For a collection with = inverse=3D"true", + 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 set, Collection.add() or Collection= .addAll() must always - return true for a bag or List (unlike a= Set). This can - make the following common code much faster. + return true for a bag or List. This can + make the following common code much faster: = One shot delete = - Occasionally, deleting collection elements one by one can = be extremely inefficient. Hibernate - isn't completely stupid, so it knows not to do that in the= case of an newly-empty collection + Deleting collection elements one by one can sometimes be e= xtremely inefficient. Hibernate + knows not to do that in the case of an newly-empty collect= ion (if you called list.clear(), for exampl= e). In this case, Hibernate will - issue a single DELETE and we are done! + issue a single DELETE. = = - Suppose we add a single element to a collection of size tw= enty and then remove two elements. + Suppose you added a single element to a collection of size= twenty and then remove two elements. Hibernate will issue one INSERT stateme= nt and two DELETE - statements (unless the collection is a bag). This is certa= inly desirable. + statements, unless the collection is a bag. This is certai= nly desirable. = @@ -1259,25 +1264,25 @@ delete eighteen rows one by one and then insert thre= e rows - remove the whole collection (in one SQL DEL= ETE) and insert - all five current elements (one by one) + remove the whole collection in one SQL DELE= TE and insert + all five current elements one by one = - Hibernate isn't smart enough to know that the second optio= n is probably quicker in this case. - (And it would probably be undesirable for Hibernate to be = that smart; such behaviour might - confuse database triggers, etc.) + Hibernate cannot know that the second option is probably q= uicker. + It would probably be undesirable for Hibernate to be that = intuitive as such behavior might + confuse database triggers, etc. = - Fortunately, you can force this behaviour (ie. the second = strategy) at any time by discarding - (ie. dereferencing) the original collection and returning = a newly instantiated collection with - all the current elements. This can be very useful and powe= rful from time to time. + Fortunately, you can force this behavior (i.e. the second = strategy) at any time by discarding + (i.e. dereferencing) the original collection and returning= a newly instantiated collection with + all the current elements. = = - Of course, one-shot-delete does not apply to collections m= apped inverse=3D"true". + One-shot-delete does not apply to collections mapped inverse=3D"true". = @@ -1304,7 +1309,7 @@ = Hibernate can also use JMX to publish metrics if you enabl= e the - StatisticsService MBean. You may enable= a single MBean for all your + StatisticsService MBean. You can enable= a single MBean for all your SessionFactory or one per factory. See = the following code for minimalistic configuration examples: @@ -1329,13 +1334,13 @@ StatisticsService stats =3D new StatisticsService(); // MBean implementati= on server.registerMBean(stats, on); // Register the MBean on the server]]> = - - TODO: This doesn't make sense: In the first case, we retri= eve and use the MBean directly. In the second one, we must give + - You can (de)activate the monitoring for a Session= Factory + You can activate and deactivate the monitoring for a SessionFactory: @@ -1365,8 +1370,8 @@ Metrics = - Hibernate provides a number of metrics, from very basic to= the specialized information - only relevant in certain scenarios. All available counters= are described in the + Hibernate provides a number of metrics, from basic informa= tion to more specialized information + that is only relevant in certain scenarios. All available = counters are described in the Statistics interface API, in three cate= gories: @@ -1378,8 +1383,8 @@ - Metrics related to he entities, collections, queri= es, and caches as a - whole (aka global metrics), + Metrics related to the entities, collections, quer= ies, and caches as a + whole (aka global metrics). @@ -1392,9 +1397,9 @@ = For example, you can check the cache hit, miss, and put ra= tio of entities, collections - and queries, and the average time a query needs. Beware th= at the number of milliseconds - is subject to approximation in Java. Hibernate is tied to = the JVM precision, on some - platforms this might even only be accurate to 10 seconds. + 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. = @@ -1404,7 +1409,7 @@ refer to the Statistics, Entit= yStatistics, CollectionStatistics, SecondLe= velCacheStatistics, and QueryStatistics API Javadoc for mor= e information. The following - code shows a simple example: + code is a simple example: = = - To work on all entities, collections, queries and region c= aches, you can retrieve - the list of names of entities, collections, queries and re= gion caches with the + You can work on all entities, collections, queries and reg= ion caches, by retrieving + the list of names of entities, collections, queries and re= gion caches using the following methods: getQueries(), getEntityNames(), getCollectionRoleNames(), and getSecondLevelCacheRegionNames(). Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/persistent_classes.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/persistent_classes.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/persistent_classes.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -32,22 +32,22 @@ Persistent classes are classes in an application that implement th= e entities of the business problem (e.g. Customer and Order in an E-commerce = application). Not all instances of a persistent class are considered to be in th= e persistent = - state - an instance may instead be transient or detached. + state. For example, an instance can instead be transient or detach= ed. = Hibernate works best if these classes follow some simple rules, al= so known as the Plain Old Java Object (POJO) programming model. However, no= ne of these rules are hard requirements. Indeed, Hibernate3 assumes very littl= e about - the nature of your persistent objects. You may express a domain mo= del in other = - ways: using trees of Map instances, for example. + the nature of your persistent objects. You can express a domain mo= del in other = + ways (using trees of Map instances, for example= ). = A simple POJO example = - Most Java applications require a persistent class representing= felines. + Most Java applications require a persistent class representing= felines. For example: = = - There are four main rules to follow here: + The four main rules of persistent classes are explored in more= detail in the following sections. = = @@ -139,8 +139,8 @@ = Cat has a no-argument constructor. All = persistent classes must = - have a default constructor (which may be non-public) so th= at Hibernate can instantiate = - them using Constructor.newInstance(). W= e strongly recommend having a = + have a default constructor (which can be non-public) so th= at Hibernate can instantiate = + them using Constructor.newInstance(). I= t is recommended that you have a = default constructor with at least package visibility for runtime proxy = generation in Hibernate. @@ -153,9 +153,9 @@ Cat has a property called id. This property = maps to the primary key column of a database table. The pr= operty might have been called anything, and its type might have been any primitive type,= any primitive "wrapper" = - type, java.lang.String or java= .util.Date. (If = - your legacy database table has composite keys, you can eve= n use a user-defined class = - with properties of these types - see the section on compos= ite identifiers later.) + type, java.lang.String or java= .util.Date. If = + your legacy database table has composite keys, you can use= a user-defined class = + with properties of these types (see the section on composi= te identifiers later in the chapter.) = @@ -164,7 +164,7 @@ = - In fact, some functionality is available only to classes w= hich declare an + In fact, some functionality is available only to classes t= hat declare an identifier property: = @@ -188,8 +188,8 @@ = - We recommend you declare consistently-named identifier pro= perties on persistent - classes. We further recommend that you use a nullable (ie.= non-primitive) type. + We recommend that you declare consistently-named identifie= r properties on persistent + classes and that you use a nullable (i.e., non-primitive) = type. = @@ -202,8 +202,8 @@ You can persist final classes that do n= ot implement an interface - with Hibernate, but you won't be able to use proxies for l= azy association fetching - - which will limit your options for performance tuning. + with Hibernate. You will not, however, be able to use prox= ies for lazy association fetching which + will ultimately limit your options for performance tuning. You should also avoid declaring public final methods on the = @@ -217,12 +217,12 @@ = Cat declares accessor methods for all i= ts persistent fields. - Many other ORM tools directly persist instance variables. = We believe it is = + Many other ORM tools directly persist instance variables. = It is = better to provide an indirection between the relational sc= hema and internal data structures of the class. By default, Hibernate persis= ts JavaBeans style = - properties, and recognizes method names of the form getFoo, = - isFoo and setFoo. Yo= u may switch to direct = - field access for particular properties, if needed. + properties and recognizes method names of the form getFoo, = + isFoo and setFoo. If= required, you can switch to direct = + field access for particular properties. = @@ -240,7 +240,7 @@ = A subclass must also observe the first and second rules. It in= herits its - identifier property from the superclass, Cat. + identifier property from the superclass, Cat. For example: = You have to override the equals() and hashCode() - methods if you = + methods if you: = intend to put instances of persistent classes in a Set - (the recommended way to represent many-valued associat= ions) = + (the recommended way to represent many-valued associat= ions); = and @@ -281,31 +281,31 @@ = Hibernate guarantees equivalence of persistent identity (datab= ase row) and Java identity - only inside a particular session scope. So as soon as we mix i= nstances retrieved in - different sessions, we must implement equals() and - hashCode() if we wish to have meaningful se= mantics for + only inside a particular session scope. When you mix instances= retrieved in + different sessions, you must implement equals() and + hashCode() if you wish to have meaningful s= emantics for Sets. = The most obvious way is to implement equals()/hashCode() by comparing the identifier value of both objects. If the valu= e is the same, both must - be the same database row, they are therefore equal (if both ar= e added to a Set, - we will only have one element in the Set). = Unfortunately, we can't use that - approach with generated identifiers! Hibernate will only assig= n identifier values to objects = - that are persistent, a newly created instance will not have an= y identifier value! Furthermore, + be the same database row, because they are equal. If both are = added to a Set, + you will only have one element in the Set).= Unfortunately, you cannot use that + approach with generated identifiers. Hibernate will only assig= n identifier values to objects = + that are persistent; a newly created instance will not have an= y identifier value. Furthermore, if an instance is unsaved and currently in a Set, saving it will assign an identifier value to the object. If equals() and hashCode() are based on the identifier value, the hash code would change,= breaking the contract of the - Set. See the Hibernate website for a full d= iscussion of this problem. Note - that this is not a Hibernate issue, but normal Java semantics = of object identity and equality. + Set. See the Hibernate website for a full d= iscussion of this problem. This is not = + a Hibernate issue, but normal Java semantics of object identity and e= quality. = - We recommend implementing equals() and hashCode() + It is recommended that you implement equals() and hashCode() using Business key equality. Business key= equality means that the equals() method compares only the propertie= s that form the business - key, a key that would identify our instance in the real world = (a + key. It is a key that would identify our instance in the real = world (a natural candidate key): = @@ -334,7 +334,7 @@ }]]> = - Note that a business key does not have to be as solid as a dat= abase + A business key does not have to be as solid as a database primary key candidate (see ). Immutable or unique properties are usually good candidates for a business key. @@ -345,30 +345,33 @@ Dynamic models = - - Note that the following features are currently consi= dered + = + Note + + The following features are currently considered experimental and may change in the near future. - - + = + + - Persistent entities don't necessarily have to be represented a= s POJO classes + Persistent entities do not necessarily have to be represented = as POJO classes or as JavaBean objects at runtime. Hibernate also supports dyn= amic models (using Maps of Maps at r= untime) and the - representation of entities as DOM4J trees. With this approach,= you don't + representation of entities as DOM4J trees. With this approach,= you do not write persistent classes, only mapping files. = - By default, Hibernate works in normal POJO mode. You may set a= default entity + By default, Hibernate works in normal POJO mode. You can set a= default entity representation mode for a particular SessionFactory using the default_entity_mode configuration option (s= ee - . + ). = - The following examples demonstrates the representation using <= literal>Maps. - First, in the mapping file, an entity-name = has to be declared - instead of (or in addition to) a class name: + The following examples demonstrate the representation using Maps. + First, in the mapping file an entity-name h= as to be declared + instead of, or in addition to, a class name: = @@ -407,14 +410,14 @@ = = - Note that even though associations are declared using target c= lass names, - the target type of an associations may also be a dynamic entit= y instead + Even though associations are declared using target class names, + the target type of associations can also be a dynamic entity i= nstead of a POJO. = After setting the default entity mode to dynamic-map<= /literal> - for the SessionFactory, we can at runtime w= ork with + for the SessionFactory, you can, at runtime= , work with Maps of Maps: = @@ -441,10 +444,10 @@ s.close();]]> = - The advantages of a dynamic mapping are quick turnaround time = for prototyping + One of the main advantages of dynamic mapping is quick turnaro= und time for prototyping, without the need for entity class implementation. However, you= lose compile-time - type checking and will very likely deal with many exceptions a= t runtime. Thanks - to the Hibernate mapping, the database schema can easily be no= rmalized and sound, + type checking and will likely deal with many exceptions at run= time. As a result of + the Hibernate mapping, the database schema can easily be norma= lized and sound, allowing to add a proper domain model implementation on top la= ter on. = @@ -472,7 +475,7 @@ EntityMode is on the Session API, not the SessionFactory. That way, the new = Session shares the underlying JDBC connection, transaction, and other = context - information. This means you don't have tocall flush()= + information. This means you do not have to call flush= () and close() on the secondary Sessi= on, and also leave the transaction and connection handling to the prim= ary unit of work. @@ -489,13 +492,16 @@ = org.hibernate.tuple.Tuplizer, and its sub-i= nterfaces, are responsible - for managing a particular representation of a piece of data, g= iven that representation's + for managing a particular representation of a piece of data gi= ven that representation's org.hibernate.EntityMode. If a given piece= of data is thought of as - a data structure, then a tuplizer is the thing which knows how= to create such a data structure + a data structure, then a tuplizer is the thing that knows how = to create such a data structure and how to extract values from and inject values into such a d= ata structure. For example, - for the POJO entity mode, the correpsonding tuplizer knows how= create the POJO through its - constructor and how to access the POJO properties using the de= fined property accessors. - There are two high-level types of Tuplizers, represented by the + 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 u= sing the defined property accessors. + + + = + There are two high-level types of Tuplizers, represented by the org.hibernate.tuple.entity.EntityTuplizer a= nd org.hibernate.tuple.component.ComponentTuplizer interfaces. EntityTuplizers are responsibl= e for managing the above mentioned contracts in regards to entities, while ComponentTupl= izers do the same for @@ -503,11 +509,11 @@ = - Users may also plug in their own tuplizers. Perhaps you requi= re that a java.util.Map + Users can also plug in their own tuplizers. Perhaps you requi= re that a java.util.Map implementation other than java.util.HashMap= be used while in the - dynamic-map entity-mode; or perhaps you need to define a diffe= rent proxy generation strategy + dynamic-map entity-mode. Or perhaps you need to define a diffe= rent proxy generation strategy than the one used by default. Both would be achieved by defin= ing a custom tuplizer - implementation. Tuplizers definitions are attached to the ent= ity or component mapping they + implementation. Tuplizer definitions are attached to the enti= ty or component mapping they are meant to manage. Going back to the example of our custome= r entity: = @@ -545,17 +551,17 @@ return new CustomMap(); } } -}]]> +}]]>m = = = - - Extentsions + = = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/preface.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/preface.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/preface.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -39,12 +39,12 @@ Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but = also provides data - query and retrieval facilities and can significantly reduce develo= pment time otherwise + query and retrieval facilities. It can also significantly reduce d= evelopment time otherwise spent with manual data handling in SQL and JDBC. = - Hibernates goal is to relieve the developer from 95 percent of com= mon data persistence + Hibernate's goal is to relieve the developer from 95 percent of co= mmon data persistence related programming tasks. Hibernate may not be the best solution = for data-centric applications that only use stored-procedures to implement the busi= ness logic in the database, it is most useful with object-oriented domain models and= business logic in @@ -75,8 +75,8 @@ - Have a look at the eg/ directory in the= Hibernate - distribution, it contains a simple standalone application.= Copy your + View the eg/ directory in the Hibernate + distribution. It contains a simple standalone application.= Copy your JDBC driver to the lib/ directory and e= dit etc/hibernate.properties, specifying co= rrect values for your database. From a command prompt in the distribution d= irectory, @@ -89,7 +89,7 @@ Use this reference documentation as your primary source of= information. Consider reading Java Persistence with Hibernate= (http://www.manning.com/bauer2) if you need more help with= application - design or if you prefer a step-by-step tutorial. Also visit + design, or if you prefer a step-by-step tutorial. Also vis= it http://caveatemptor.hibernate.org and download the example= application for Java Persistence with Hibernate. @@ -116,7 +116,7 @@ = If you have questions, use the user forum linked on the Hibernate= website. We also - provide a JIRA issue trackings system for bug reports and feature= requests. If you + provide a JIRA issue tracking system for bug reports and feature = requests. If you are interested in the development of Hibernate, join the develope= r mailing list. If you are interested in translating this documentation into your la= nguage, contact us on the developer mailing list. Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/query_criteria.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/query_criteria.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/query_criteria.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -64,7 +64,7 @@ .list();]]> = - Restrictions may be grouped logically. + Restrictions can be grouped logically. = = - There are quite a range of built-in criterion types (= Restrictions - subclasses), but one that is especially useful lets you specif= y SQL directly. + There are a range of built-in criterion types (Restri= ctions + subclasses). One of the most useful allows you to specify SQL = directly. = = - An alternative approach to obtaining a criterion is to get it = from a = + You can also obtain a criterion from a = Property instance. You can create a Property - by calling Property.forName(). + by calling Property.forName(): = Ordering the results = - You may order the results using org.hibernate.criteri= on.Order. + You can order the results using org.hibernate.criteri= on.Order. = Associations = - You may easily specify constraints upon related entities by na= vigating - associations using createCriteria(). + By navigating + associations using createCriteria() you can= specify constraints upon related entities: = = - note that the second createCriteria() retur= ns a new - instance of Criteria, which refers to the e= lements of + The second createCriteria() returns a new + instance of Criteria that refers to the ele= ments of the kittens collection. = - The following, alternate form is useful in certain circumstanc= es. + There is also an alternate form that is useful in certain circ= umstances: = = - Note that the kittens collections held by the Cat instances + The kittens collections held by the Cat ins= tances returned by the previous two queries are not pre-filtered - by the criteria! If you wish to retrieve just the kittens that= match the + by the criteria. If you want to retrieve just the kittens that= match the criteria, you must use a ResultTransformer. = @@ -202,7 +202,7 @@ Dynamic association fetching = - You may specify association fetching semantics at runtime using + You can specify association fetching semantics at runtime using setFetchMode(). = @@ -268,7 +268,7 @@ Projections, aggregation and grouping The class org.hibernate.criterion.Projections is a - factory for Projection instances. We apply a + factory for Projection instances. You can a= pply a projection to a query by calling setProjection(). = @@ -293,8 +293,8 @@ = - An alias may optionally be assigned to a projection, so that t= he projected value - may be referred to in restrictions or orderings. Here are two = different ways to + 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: = @@ -361,8 +361,8 @@ Detached queries and subqueries - The DetachedCriteria class lets you create = a query outside the scope = - of a session, and then later execute it using some arbitrary <= literal>Session. + The DetachedCriteria class allows you to cr= eate a query outside the scope = + of a session and then execute it using an arbitrary S= ession. = = - A DetachedCriteria may also be used to expr= ess a subquery. Criterion - instances involving subqueries may be obtained via Su= bqueries or + A DetachedCriteria can also be used to expr= ess a subquery. Criterion + instances involving subqueries can be obtained via Su= bqueries or Property. = = @@ -393,7 +393,7 @@ .list();]]> = - Even correlated subqueries are possible: + Correlated subqueries are also possible: = Queries by natural identifier = - For most queries, including criteria queries, the query cache = is not very efficient, - because query cache invalidation occurs too frequently. Howeve= r, there is one special - kind of query where we can optimize the cache invalidation alg= orithm: lookups by a = + For most queries, including criteria queries, the query cache = is not efficient + because query cache invalidation occurs too frequently. Howeve= r, there is a special + kind of query where you can optimize the cache invalidation al= gorithm: lookups by a = constant natural key. In some applications, this kind of query= occurs frequently. The criteria API provides special provision for this use case. = - First, you should map the natural key of your entity using = - <natural-id>, and enable use of the s= econd-level cache. + First, map the natural key of your entity using = + <natural-id> and enable use of the se= cond-level cache. = @@ -438,16 +438,13 @@ ]]> = - Note that this functionality is not intended for use with enti= ties with = + This functionality is not intended for use with entities with = mutable natural keys. = - Next, enable the Hibernate query cache. - - = - - Now, Restrictions.naturalId() allows us to = make use of + Once you have enabled the Hibernate query cache, = + the Restrictions.naturalId() allows you to = make use of the more efficient cache algorithm. = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/query_hql.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/query_hql.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/query_hql.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -29,28 +29,28 @@ HQL: The Hibernate Query Language = - Hibernate is equipped with an extremely powerful query language th= at (quite intentionally) - looks very much like SQL. But don't be fooled by the syntax; HQL i= s fully object-oriented, - understanding notions like inheritence, polymorphism and associati= on. + 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 associa= tion. = Case Sensitivity = - Queries are case-insensitive, except for names of Java classes= and properties. + With the exception of names of Java classes and properties, qu= eries are case-insensitive. So SeLeCT is the same as sELEct is the same as - SELECT but + SELECT, but org.hibernate.eg.FOO is not - org.hibernate.eg.Foo and + org.hibernate.eg.Foo, and foo.barSet is not foo.BARSET. = This manual uses lowercase HQL keywords. Some users find queri= es with uppercase keywords - more readable, but we find this convention ugly when embedded = in Java code. + more readable, but this convention is unsuitable for queries e= mbedded in Java code. = @@ -65,40 +65,40 @@ = - which simply returns all instances of the class eg.Ca= t. - We don't usually need to qualify the class name, since auto-import - is the default. So we almost always just write: + This returns all instances of the class eg.Cat. + You do not usually need to qualify the class name, since auto-import + is the default. For example: = = - Most of the time, you will need to assign an alias, since - you will want to refer to the Cat in other = parts of the - query. + = + In order to refer to the Cat in other parts= of the + query, you will need to assign an alias. = For example: = = This query assigns the alias cat to Cat - instances, so we could use that alias later in the query. The = as - keyword is optional; we could also write: + instances, so you can use that alias later in the query. The <= literal>as + keyword is optional. You could also write: = = - Multiple classes may appear, resulting in a cartesian product = or "cross" join. + Multiple classes can appear, resulting in a cartesian product = or "cross" join. = = - It is considered good practice to name query aliases using an = initial lowercase, + It is good practice to name query aliases using an initial low= ercase as this is consistent with Java naming standards for local variables - (eg. domesticCat). + (e.g. domesticCat). = @@ -107,8 +107,8 @@ Associations and joins = - We may also assign aliases to associated entities, or even to = elements of a - collection of values, using a join. + You can also assign aliases to associated entities or to eleme= nts of a + collection of values using a join. For exam= ple: = = - The supported join types are borrowed from ANSI SQL + The supported join types are borrowed from ANSI SQL: = @@ -165,8 +165,8 @@ with kitten.bodyWeight > 10.0]]> = - In addition, a "fetch" join allows associations or collections= of values to be - initialized along with their parent objects, using a single se= lect. This is particularly + A "fetch" join allows associations or collections of values to= be + initialized along with their parent objects using a single sel= ect. This is particularly useful in the case of a collection. It effectively overrides t= he outer join and lazy declarations of the mapping file for associations and col= lections. See for more information. @@ -178,9 +178,9 @@ = A fetch join does not usually need to assign an alias, because= the associated objects - should not be used in the where clause (or = any other clause). Also, - the associated objects are not returned directly in the query = results. Instead, they may - be accessed via the parent object. The only reason we might ne= ed an alias is if we are + should not be used in the where clause (or = any other clause). = + The associated objects are also not returned directly in the q= uery results. Instead, they may + be accessed via the parent object. The only reason you might n= eed an alias is if you are recursively join fetching a further collection: = @@ -190,24 +190,24 @@ left join fetch child.kittens]]> = - Note that the fetch construct may not be us= ed in queries called using - iterate() (though scroll() can be used). Nor should - fetch be used together with setMax= Results() or - setFirstResult() as these operations are ba= sed on the result rows, which + The fetch construct cannot be used in queri= es called using + iterate() (though scroll() can be used). = + Fetch should be used together with setMaxResults() or + setFirstResult(), as these operations are b= ased on the result rows which usually contain duplicates for eager collection fetching, henc= e, the number of rows is not what - you'd expect. - Nor may fetch be used together with an ad h= oc with condition. + you would expect. + Fetch should also not be used together with= impromptu with 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 colle= ction roles also sometimes gives - unexpected results for bag mappings, so be careful about how y= ou formulate your queries in this + query, so take care in this case. Join fetching multiple colle= ction roles can produce + unexpected results for bag mappings, so user discretion is adv= ised when formulating queries in this case. Finally, note that full join fetch an= d right join fetch are not meaningful. = If you are using property-level lazy fetching (with bytecode i= nstrumentation), it is - possible to force Hibernate to fetch the lazy properties immed= iately (in the first - query) using fetch all properties. + possible to force Hibernate to fetch the lazy properties in th= e first query immediately + using fetch all properties. = @@ -223,7 +223,7 @@ = - The queries shown in the previous section all use the expli= cit form where + The queries shown in the previous section all use the expli= cit form, that is, where the join keyword is explicitly used in the from clause. This is the= recommended form. = @@ -238,47 +238,50 @@ = - Refering to identifier property + Referring to identifier property = - There are, generally speaking, 2 ways to refer to an entity's = identifier property: + There are 2 ways to refer to an entity's identifier property: The special property (lowercase) id= may be used to reference the identifier - property of an entity provided that entity d= oes not define a non-identifier property + property of an entity provided that the enti= ty does not define a non-identifier property named id. - If the entity defines a named identifier property, you= may use that property name. + If the entity defines a named identifier property, you= can use that property name. = - References to composite identifier properties follow the same = naming rules. If the + References to composite identifier properties follow the same = naming rules. If the entity has a non-identifier property named id, the composite i= dentifier property can only - be referenced by its defined named; otherwise, the special id property - can be used to rerference the identifier property. + be referenced by its defined named. Otherwise, the special id property + can be used to reference the identifier property. = + - Note: this has changed significantly starting in version 3.2.2= . In previous versions, - id always referred to = the identifier property no - matter what its actual name. A ramification of that decision = was that non-identifier + Please note that, starting in version 3.2.2, this has changed = significantly. In previous versions, + id always referred to= the identifier property + regardless of its actual name. A ramification of that decisio= n was that non-identifier properties named id could never be referenc= ed in Hibernate queries. - + = = + + The select clause = The select clause picks which objects and p= roperties to return in - the query result set. Consider: + the query result set. Consider the following: = The query will select mates of other Cats. - Actually, you may express this query more compactly as: + You can express this query more compactly as: = = - Queries may return properties of any value type including prop= erties of component type: + Queries can return properties of any value type including prop= erties of component type: = = - Queries may return multiple objects and/or properties as an ar= ray of type - Object[], + Queries can return multiple objects and/or properties as an ar= ray of type + Object[]: = = - or as a List, + Or as a List: = = - or as an actual typesafe Java object, + Or - assuming that the class Family has an = appropriate constructor - as an actual typesafe Java object: = = + = - assuming that the class Family has an appro= priate constructor. + You can assign aliases to selected expressions using = as: = - - You may assign aliases to selected expressions using = as: - - = @@ -357,7 +357,7 @@ Aggregate functions = - HQL queries may even return the results of aggregate functions= on properties: + HQL queries can even return the results of aggregate functions= on properties: = - Collections may also appear inside aggregate functions in the = select + Collections can also appear inside aggregate functions in the = select clause. = @@ -374,7 +374,7 @@ --> = - The supported aggregate functions are + The supported aggregate functions are: = @@ -396,7 +396,7 @@ = - You may use arithmetic operators, concatenation, and recognize= d SQL functions + You can use arithmetic operators, concatenation, and recognize= d SQL functions in the select clause: = @@ -408,7 +408,7 @@ = - The distinct and all key= words may be used and + The distinct and all key= words can be used and have the same semantics as in SQL. = @@ -429,7 +429,7 @@ = returns instances not only of Cat, but also= of subclasses like - DomesticCat. Hibernate queries may name any Java + DomesticCat. Hibernate queries can name any Java class or interface in the from 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: @@ -445,9 +445,9 @@ = - Note that these last two queries will require more than one SQ= L SELECT. This + These last two queries will require more than one SQL SELECT. This means that the order by clause does not cor= rectly order the whole result set. - (It also means you can't call these queries using Que= ry.scroll().) + It also means you cannot call these queries using Que= ry.scroll(). = @@ -456,8 +456,8 @@ The where clause = - The where clause allows you to narrow the l= ist of instances returned. - If no alias exists, you may refer to properties by name: + The where clause allows you to refine the l= ist of instances returned. + If no alias exists, you can refer to properties by name: = @@ -469,38 +469,40 @@ = - returns instances of Cat named 'Fritz'. + This returns instances of Cat named 'Fritz'. = + + The following query: = - will return all instances of Foo for which - there exists an instance of bar with a + returns all instances of Foo with an + instance of bar with a date property equal to the startDate property of the Foo. Compound path expressions make the - where clause extremely powerful. Consider: + where clause extremely powerful. Consider t= he following: = = - This query translates to an SQL query with a table (inner) joi= n. If you were to write - something like + This query translates to an SQL query with a table (inner) joi= n. For example: + = = = - you would end up with a query that would require four table jo= ins in SQL. + would result in a query that would require four table joins in= SQL. = - The =3D operator may be used to compare not= only properties, but also + The =3D operator can be used to compare not= only properties, but also instances: = @@ -511,7 +513,7 @@ where cat.mate =3D mate]]> = - The special property (lowercase) id may be = used to reference the + The special property (lowercase) id can be = used to reference the unique identifier of an object. See for more information. @@ -521,14 +523,13 @@ from Cat as cat where cat.mate.id =3D 69]]> = - The second query is efficient. No table join is required! + The second query is efficient and does not require a table joi= n. = - Properties of composite identifiers may also be used. Suppose = Person - has a composite identifier consisting of country and - medicareNumber. Again, see - for more information regarding referencing identifier properti= es. + Properties of composite identifiers can also be used. Consider= the following example where Person + has composite identifiers consisting of country and + medicareNumber: = = - Once again, the second query requires no table join. + Once again, the second query does not require a table join. - - - Likewise, the special property class access= es the discriminator value + = + + See + for more information regarding referencing identifier properti= es) + + = + + The special property class accesses the dis= criminator 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. @@ -552,21 +558,21 @@ = - You may also use components or composite user types, or proper= ties of said - component types. See f= or more details. + You can also use components or composite user types, or proper= ties of said + component types. See f= or more information. = - An "any" type has the special properties id= and class, - allowing us to express a join in the following way (where AuditLog.item - is a property mapped with <any>). + An "any" type has the special properties id= and class that allows you + to express a join in the following way (where AuditLo= g.item + is a property mapped with <any>): = = - Notice that log.item.class and pay= ment.class + The log.item.class and payment.cla= ss would refer to the values of completely different database col= umns in the above query. = @@ -576,19 +582,19 @@ Expressions = - Expressions allowed in the where clause inc= lude - most of the kind of things you could write in SQL: + Expressions used in the where clause includ= e the following: + = = - mathematical operators +, -, *, / + mathematical operators: +, -, *, / - binary comparison operators =3D, >=3D, <= ;=3D, <>, !=3D, like + binary comparison operators: =3D, >=3D, &l= t;=3D, <>, !=3D, like @@ -598,7 +604,7 @@ - Parentheses ( ), indicating grouping + Parentheses ( ) that indicates grou= ping @@ -627,7 +633,7 @@ - current_date(), current_ti= me(), + current_date(), current_ti= me(), and current_timestamp() @@ -635,7 +641,7 @@ second(...), minute(...), hour(...), day(...), - month(...), year(...), + month(...), and year(...) @@ -674,13 +680,13 @@ HQL functions that take collection-valued path express= ions: size(), minelement(), maxelement(), minindex(), maxindex(), along with the special elements() and ind= ices functions - which may be quantified using some, all, exis= ts, any, in. + that can be quantified using some, all, exist= s, any, in. Any database-supported SQL scalar function like sign(), - trunc(), rtrim()= , sin() + trunc(), rtrim()= , and sin() @@ -690,7 +696,7 @@ - named parameters :name, :s= tart_date, :x1 + named parameters :name, :s= tart_date, and :x1 @@ -707,7 +713,7 @@ = - in and between may be us= ed as follows: + in and between can be us= ed as follows: = @@ -715,7 +721,7 @@ = - and the negated forms may be written + The negated forms can be written as follows: = @@ -723,12 +729,12 @@ = - Likewise, is null and is not null<= /literal> may be used to test + Similarly, is null and is not null= can be used to test for null values. = - Booleans may be easily used in expressions by declaring HQL qu= ery substitutions in Hibernate + Booleans can be easily used in expressions by declaring HQL qu= ery substitutions in Hibernate configuration: = @@ -742,7 +748,7 @@ <= /programlisting> = - You may test the size of a collection with the special propert= y size, or + You can test the size of a collection with the special propert= y size or the special size() function. = @@ -751,11 +757,11 @@ 0]= ]> = - For indexed collections, you may refer to the minimum and maxi= mum indices using + For indexed collections, you can refer to the minimum and maxi= mum indices using minindex and maxindex fu= nctions. Similarly, - you may refer to the minimum and maximum elements of a collect= ion of basic type + you can refer to the minimum and maximum elements of a collect= ion of basic type using the minelement and maxelemen= t - functions. + functions. For example: = current_date]]> @@ -767,7 +773,7 @@ The SQL functions any, some, all, exists, in are supported when passed the element or index set of a collection (elements and = indices functions) - or the result of a subquery (see below). + or the result of a subquery (see below): = Note that these constructs - size, elements, indices, minindex, maxindex, - minelement, maxelement -= may only be used in + minelement, maxelement -= can only be used in the where clause in Hibernate3. = - Elements of indexed collections (arrays, lists, maps) may be r= eferred to by - index (in a where clause only): + Elements of indexed collections (arrays, lists, and maps) can = be referred to by + index in a where clause only: = @@ -807,14 +813,14 @@ where order.items[ maxindex(order.items) ] =3D item and order.id =3D 11]]>= = - The expression inside [] may even be an ari= thmetic expression. + The expression inside [] can even be an ari= thmetic expression: = = - HQL also provides the built-in index() func= tion, for elements + HQL also provides the built-in index() func= tion for elements of a one-to-many association or collection of values. = @@ -823,13 +829,13 @@ where index(item) < 5]]> = - Scalar SQL functions supported by the underlying database may = be used + Scalar SQL functions supported by the underlying database can = be used: = = - If you are not yet convinced by all this, think how much longe= r and less readable the + Consider how much longer and less readable the following query would be in SQL: = @@ -869,7 +875,7 @@ The order by clause = - The list returned by a query may be ordered by any property of= a returned class or components: + The list returned by a query can be ordered by any property of= a returned class or components: = The group by clause = - A query that returns aggregate values may be grouped by any pr= operty of a returned class or components: + A query that returns aggregate values can be grouped by any pr= operty of a returned class or components: = SQL functions and aggregate functions are allowed in the having - and order by clauses, if supported by the u= nderlying database - (eg. not in MySQL). + and order by clauses if they are supported = by the underlying database + (i.e., not in MySQL). = = - Note that neither the group by clause nor t= he - order by clause may contain arithmetic expr= essions. - Also note that Hibernate currently does not expand a grouped e= ntity, - so you can't write group by cat if all prop= erties + Neither the group by clause nor the + order by clause can contain arithmetic expr= essions. + Hibernate also does not currently expand a grouped entity, + so you cannot write group by cat if all pro= perties of cat are non-aggregated. You have to list= all non-aggregated properties explicitly. @@ -962,12 +968,12 @@ from Cat as cat]]> = - Note that HQL subqueries may occur only in the select or where= clauses. + Note that HQL subqueries can occur only in the select or where= clauses. = Note that subqueries can also utilize row value const= ructor syntax. See - for more details. + for more information. = @@ -977,13 +983,13 @@ = Hibernate queries can be quite powerful and complex. In fact, = the power of the query language - is one of Hibernate's main selling points. Here are some examp= le queries very similar to queries - that I used on a recent project. Note that most queries you wi= ll write are much simpler than these! + is one of Hibernate's main strengths. The following example qu= eries are similar to queries + that have been used on recent projects. Please note that most = queries you will write will be much simpler than the following examples. = - The following query returns the order id, number of items and = total value of the order for all - unpaid orders for a particular customer and given minimum tota= l value, ordering the results by + The following query returns the order id, number of items, the= given minimum total value and the total value of the order for all + unpaid orders for a particular customer. The results are order= ed by total value. In determining the prices, it uses the current ca= talog. The resulting SQL query, against the ORDER, ORDER_LINE, PRODUCT, CATALOG and PRICE tables= has four inner joins and an @@ -1053,7 +1059,7 @@ order by status.sortOrder]]> = - If I would have mapped the statusChanges co= llection as a list, instead of a set, + If the statusChanges collection was mapped = as a list, instead of a set, the query would have been much simpler to write. = @@ -1101,7 +1107,7 @@ HQL now supports update, delete and insert ... select ... statements. - See for details. + See for more information. = @@ -1109,7 +1115,7 @@ Tips & Tricks = - You can count the number of query results without actually ret= urning them: + You can count the number of query results without returning th= em: = @@ -1132,7 +1138,7 @@ = =3D 1]]> = - If your database doesn't support subselects, use the following= query: + If your database does not support subselects, use the followin= g query: = =3D 1]]> = + - As this solution can't return a User with z= ero messages + As this solution cannot return a User with = zero messages because of the inner join, the following form is also useful: = @@ -1170,7 +1177,7 @@ List page =3D q.list();]]> = - Collection elements may be ordered or grouped using a query fi= lter: + Collection elements can be ordered or grouped using a query fi= lter: = Components = - Components might be used in just about every way that simple v= alue types can be used in HQL - queries. They can appear in the select cla= use: + Components can be used similarly to the simple value types tha= t are used in HQL + queries. They can appear in the select cla= use as follows: = @@ -1219,16 +1226,16 @@ Row value constructor syntax = - HQL supports the use of ANSI SQL row value constructo= r syntax (sometimes - called tuple syntax), even though the under= lying database may not support - that notion. Here we are generally referring to multi-valued = comparisons, typically associated + HQL supports the use of ANSI SQL row value constructo= r syntax, sometimes + referred to AS tuple syntax, even though th= e underlying database may not support + that notion. Here, we are generally referring to multi-valued= comparisons, typically associated with components. Consider an entity Person which defines a na= me component: = = - That's valid syntax, although a little verbose. It be nice to= make this a bit more concise and use + That is valid syntax although it is a little verbose. You can= make this more concise by using row value constructor syntax: = @@ -1241,8 +1248,8 @@ = - Another time using row value constructor sy= ntax can be beneficial - is when using subqueries needing to compare against multiple v= alues: + Using row value constructor syntax can also= be beneficial + when using subqueries that need to compare against multiple va= lues: = = - One thing to consider when deciding if you want to use this sy= ntax is that the query will + One thing to consider when deciding if you want to use this sy= ntax, is that the query will be dependent upon the ordering of the component sub-properties= in the metadata. = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/query_sql.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/query_sql.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/query_sql.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -28,21 +28,21 @@ Native SQL = - You may also express queries in the native SQL dialect of your - database. This is useful if you want to utilize database specific featur= es + You can also express queries in the native SQL dialect of your + database. This is useful if you want to utilize database-specific featur= es such as query hints or the CONNECT keyword in Oracle.= It also provides a clean migration path from a direct SQL/JDBC based application to Hibernate. = - Hibernate3 allows you to specify handwritten SQL (including stored - procedures) for all create, update, delete, and load operations. + Hibernate3 allows you to specify handwritten SQL, including stored + procedures, for all create, update, delete, and load operations. = Using a <literal>SQLQuery</literal> = Execution of native SQL queries is controlled via the SQLQuery interface, which is obtained by calling - Session.createSQLQuery(). The following describes h= ow + Session.createSQLQuery(). The following sections de= scribe how to use this API for querying. = @@ -55,14 +55,14 @@ sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE FROM CATS").list(); ]]> = - These will both return a List of Object arrays (Object[]) with + 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 return= ed scalar values. = To avoid the overhead of using - ResultSetMetadata or simply to be more explicit in - what is returned one can use addScalar(). + ResultSetMetadata, or simply to be more explicit = in + what is returned, one can use addScalar(): = = - This will still return Object arrays, but now it will not use + This will return Object arrays, but now it will not use ResultSetMetadata but will instead explicitly get= the ID, NAME and BIRTHDATE column as respectively a Long, String and a S= hort from the underlying resultset. This also means that only these three @@ -100,12 +100,12 @@ ]]> = This is essentially the same query as before, but now - ResultSetMetaData is used to decide the type of N= AME - and BIRTHDATE where as the type of ID is explicitly specified. + ResultSetMetaData is used to determine the type o= f NAME + and BIRTHDATE, where as the type of ID is explicitly specified. = How the java.sql.Types returned from ResultSetMetaData is mapp= ed 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 + not mapped, or does not result in the expected type, it is possible = to customize it via calls to registerHibernateType in the Dialect. @@ -165,9 +165,9 @@ .addJoin("cat.dog"); ]]> = - In this example the returned Cat's will have + In this example, the returned Cat's will ha= ve their dog property fully initialized without any - extra roundtrip to the database. Notice that we added a alias name + 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 Cat had a one-to-many to Dog @@ -179,8 +179,8 @@ ]]> = - At this stage we are reaching the limits of what is possible w= ith native queries without starting to - enhance the sql queries to make them usable in Hibernate; the = problems starts to arise when returning + 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. Prob= lems can arise when returning multiple entities of the same type or when the default alias/c= olumn names are not enough. @@ -188,10 +188,10 @@ Returning multiple entities = - Until now the result set column names are assumed to be the sa= me + Until now, the result set column names are assumed to be the s= ame as the column names specified in the mapping document. This can be - problematic for SQL queries which join multiple tables, since the sa= me - column names may appear in more than one table. + problematic for SQL queries that join multiple tables, since the same + column names can appear in more than one table. = Column alias injection is needed in the following query (which most likely will fail): @@ -201,13 +201,17 @@ .addEntity("mother", Cat.class) ]]> = - The intention for this query is to return two Cat instances per - row, a cat and its mother. This will fail since there is a conflict = of - names since they are mapped to the same column names and on some - databases the returned column aliases will most likely be on the form - "c.ID", "c.NAME", etc. which are not equal to the columns specified = in - the mappings ("ID" and "NAME"). + = = + + 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: = @@ -230,13 +234,13 @@ = The {cat.*} and {mother.*} notation used above is a shorthand = for - "all properties". Alternatively, you may list the columns explicitly= , but - even in this case we let Hibernate inject the SQL column aliases 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 proper= ty - name qualified by the table alias. In the following example, we retr= ieve + name qualified by the table alias. In the following example, you ret= rieve Cats and their mothers from a different table (cat_log) to the one - declared in the mapping metadata. Notice that we may even use the - property aliases in the where clause if we like. + declared in the mapping metadata. You can even use the + property aliases in the where clause. = Alias and property references = - For most cases the above alias injection is needed, but for - queries relating to more complex mappings like composite propertie= s, - inheritance discriminators, collections etc. there are some specif= ic - aliases to use to allow Hibernate to inject the proper aliases. + In most cases the above alias injection is needed. For + queries relating to more complex mappings, like composite properti= es, + inheritance discriminators, collections etc., you can use specific + aliases that allow Hibernate to inject the proper aliases. = - The following table shows the different possibilities of usi= ng - the alias injection. Note: the alias names in the result are examp= les, + The following table shows the different ways you can use + the alias injection. Please note that the alias names in the resul= t are simply examples; each alias will have a unique and probably different name when used. = @@ -339,7 +343,7 @@ = - roperty of the element in the collection + property of the element in the collection = {[aliasname].element.[propertyname]} = @@ -370,7 +374,7 @@ Returning non-managed entities = - It is possible to apply a ResultTransformer to native sql quer= ies. Allowing it to e.g. return non-managed entities. + It is possible to apply a ResultTransformer to native SQL quer= ies, allowing it to return non-managed entities. = @@ -396,15 +400,15 @@ Handling inheritance = - Native sql queries which query for entities that is mapped as = part + Native SQL queries which query for entities that are mapped as= part of an inheritance must include all properties for the baseclass and = all - it subclasses. + its subclasses. = Parameters = - Native sql queries support positional as well as named + Native SQL queries support positional as well as named parameters: = Named SQL queries = - Named SQL queries may be defined in the mapping document and cal= led - in exactly the same way as a named HQL query. In this case, we do + Named SQL queries can be defined in the mapping document and cal= led + in exactly the same way as a named HQL query. In this case, you do not need to call addEntity(). = @@ -440,10 +444,9 @@ .setMaxResults(50) .list();]]> = - The <return-join> and - <load-collection> elements are used to join - associations and define queries which initialize collections, - respectively. + The <return-join> element is use to joi= n associations and + the <load-collection> element is used to defi= ne queries which initialize collections, + = @@ -473,8 +476,8 @@ FROM PERSON p WHERE p.NAME LIKE 'Hiber%' ]]> = - You can externalize the resultset mapping informations in a - <resultset> element to either reuse them acro= ss + You can externalize the resultset mapping information in a + <resultset> element which will allow you to e= ither reuse them across several named queries or through the setResultSetMapping() API. = @@ -497,7 +500,7 @@ WHERE person.NAME LIKE :namePattern ]]> = - You can alternatively use the resultset mapping information in y= our + You can, alternatively, use the resultset mapping information in= your hbm files directly in java code. = Using return-property to explicitly specify column/alias names = - With <return-property> you can explic= itly - tell Hibernate what column aliases to use, instead of using the + You can explicitly + tell Hibernate what column aliases to use with <return-p= roperty>, instead of using the {}-syntax to let Hibernate inject its own - aliases. + aliases.For example: = @@ -530,7 +533,7 @@ = <return-property> also works with multiple columns. This solves a limitation with the - {}-syntax which can not allow fine grained contro= l of + {}-syntax which cannot allow fine grained control= of multi-column properties. = @@ -549,9 +552,9 @@ ORDER BY STARTDATE ASC ]]> = - Notice that in this example we used - <return-property> in combination with the - {}-syntax for injection. Allowing users to choose= how + In this example + <return-property> was used in combination w= ith the + {}-syntax for injection. This allows users to cho= ose how they want to refer column and properties. = If your mapping has a discriminator you must use @@ -562,7 +565,7 @@ Using stored procedures for querying = - Hibernate 3 introduces support for queries via stored procedur= es + Hibernate3 provides support for queries via stored procedures and functions. Most of the following documentation is equivalent for both. The stored procedure/function must return a resultset as the f= irst out-parameter to be able to work with Hibernate. An example of such a @@ -600,24 +603,24 @@ { ? =3D call selectAllEmployments() } ]]> = - Notice stored procedures currently only return scalars and + Stored procedures currently only return scalars and entities. <return-join> and <load-collection> are not supported. = Rules/limitations for using stored procedures = - To use stored procedures with Hibernate the procedures/funct= ions - have to follow some rules. If they do not follow those rules they = are + You cannot use stored procedures with Hibernate unless you f= ollow some procedure/function + rules. If they do not follow those rules they are not usable with Hibernate. If you still want to use these procedur= es you have to execute them via session.connection(). The rules are different for each database, since database vendors = have different stored procedure semantics/syntax. = - Stored procedure queries can't be paged with + Stored procedure queries cannot be paged with setFirstResult()/setMaxResults(). = - Recommended call form is standard SQL92: { ? =3D ca= ll + The recommended call form is standard SQL92: { ? = =3D call functionName(<parameters>) } or { ? =3D c= all procedureName(<parameters>}. Native call syntax is= not supported. @@ -630,8 +633,8 @@ a procedure must be an OUT that returns a result set. This is done by using a SYS_REFCURSOR type in Oracle 9 or 10. In Or= acle - you need to define a REF CURSOR type, see - Oracle literature. + you need to define a REF CURSOR type. See + Oracle literature for further information. = @@ -640,7 +643,7 @@ The procedure must return a result set. Note that since - these servers can/will return multiple result sets and update + 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 el= se will be discarded. @@ -677,8 +680,8 @@ DELETE FROM PERSON WHERE ID=3D? ]]> = - The SQL is directly executed in your database, so you are free to - use any dialect you like. This will of course reduce the portability of + The SQL is directly executed in your database, so you can + use any dialect you like. This will reduce the portability of your mapping if you use database specific SQL. = Stored procedures are supported if the callable @@ -694,18 +697,18 @@ {? =3D call updatePerson (?, ?)} ]]> = - The order of the positional parameters are currently vital, as t= hey + The order of the positional parameters is vital, as they must be in the same sequence as Hibernate expects them. = - You can see the expected order by enabling debug logging for the + You can view the expected order by enabling debug logging for the org.hibernate.persister.entity level. With this lev= el - 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 in the mapping files as that will override= the - Hibernate generated static sql.) + enabled, Hibernate will print out the static SQL that is used to creat= e, + update, delete etc. entities. To view the expected sequence, do + not include your custom SQL in the mapping files, as this will overrid= e the + Hibernate generated static SQL. = - The stored procedures are in most cases (read: better do it than - not) required to return the number of rows inserted/updated/deleted, as + The stored procedures are in most cases + required to return the number of rows inserted, updated and deleted, as Hibernate has some runtime checks for the success of the statement. Hibernate always registers the first statement parameter as a numeric output parameter for the CUD operations: @@ -728,7 +731,7 @@ Custom SQL for loading = - You may also declare your own SQL (or HQL) queries for entity + You can also declare your own SQL (or HQL) queries for entity loading: = @@ -740,7 +743,7 @@ ]]> = This is just a named query declaration, as discussed earlier. You - may reference this named query in a class mapping: + can reference this named query in a class mapping: = @@ -752,7 +755,7 @@ = This even works with stored procedures. = - You may even define a query for collection loading: + You can even define a query for collection loading: = @@ -768,7 +771,7 @@ ORDER BY STARTDATE ASC, EMPLOYEE ASC ]]> = - You could even define an entity loader that loads a collection by + You can also define an entity loader that loads a collection by join fetching: = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/session_api.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/session_api.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/session_api.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -33,7 +33,7 @@ the developer from the details of the underlying database manageme= nt system, but also offers state management of o= bjects. This is, contrary to the management of SQL statements in= common JDBC/SQL - persistence layers, a very natural object-oriented view of persist= ence in Java + persistence layers, a natural object-oriented view of persistence = in Java applications. = @@ -59,7 +59,7 @@ is not associated with a Hibernate Session. It has no persistent representation in the database and no ident= ifier value has been assigned. Transient instances will be destroyed by the= garbage collector if - the application doesn't hold a reference anymore. Use = the Hibernate + the application does not hold a reference anymore. Use= the Hibernate Session to make an object persisten= t (and let Hibernate take care of the SQL statements that need to be execut= ed for this transition). @@ -71,7 +71,7 @@ however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in= persistent state and synchronize the state with the database when the unit = of work completes. - Developers don't execute manual UPDATE statements, or + Developers do not execute manual UPDATE statements, or DELETE statements when an object sh= ould be made transient. @@ -84,14 +84,14 @@ Session at a later point in time, m= aking it (and all the modifications) persistent again. This feature enables = a programming model for long running units of work that require user think-tim= e. We call them - application transactions, i.e. a = unit of work from the + application transactions, i.e., a= unit of work from the point of view of the user. = - We'll now discuss the states and state transitions (and the Hi= bernate methods that + We will now discuss the states and state transitions (and the = Hibernate methods that trigger a transition) in more detail. = @@ -119,7 +119,7 @@ is called. If Cat has an assigned<= /literal> identifier, or a composite key, the identifier should be assig= ned to = the cat instance before calling sa= ve(). - You may also use persist() instead of save(), + You can also use persist() instead of save(), with the semantics defined in the EJB3 early draft. = @@ -127,7 +127,7 @@ persist() makes a transient instanc= e persistent. = - However, it doesn't guarantee that the identifier valu= e will be assigned to = + However, it does not guarantee that the identifier val= ue will be assigned to = the persistent instance immediately, the assignment mi= ght happen at flush time. = persist() also guarantees that it w= ill not execute an = INSERT statement if it is called ou= tside of transaction = @@ -147,7 +147,7 @@ = = - Alternatively, you may assign the identifier using an overload= ed version + Alternatively, you can assign the identifier using an overload= ed version of save(). = @@ -162,7 +162,7 @@ If the object you make persistent has associated objects (e.g.= the kittens collection in the previous example), - these objects may be made persistent in any order you like unl= ess you + these objects can be made persistent in any order you like unl= ess you have a NOT NULL constraint upon a foreign k= ey column. There is never a risk of violating foreign key constraints. Ho= wever, you = might violate a NOT NULL constraint if you @@ -170,10 +170,10 @@ = - Usually you don't bother with this detail, as you'll very like= ly use Hibernate's + Usually you do not bother with this detail, as you will normal= ly use Hibernate's transitive persistence feature to save th= e associated objects automatically. Then, even NOT NULL - constraint violations don't occur - Hibernate will take care o= f everything. + constraint violations do not occur - Hibernate will take care = of everything. Transitive persistence is discussed later in this chapter. = @@ -183,10 +183,10 @@ Loading an object = - The load() methods of Session gives you - a way to retrieve a persistent instance if you already know it= s identifier. = - load() takes a class object and will load t= he state into = - a newly instantiated instance of that class, in persistent sta= te. + The load() methods of Session provide + a way of retrieving a persistent instance if you know its iden= tifier. = + load() takes a class object and loads the s= tate into = + a newly instantiated instance of that class in a persistent st= ate. = @@ -205,11 +205,11 @@ Set kittens =3D cat.getKittens();]]> = - Note that load() will throw an unrecoverabl= e exception if = + Be aware that load() will throw an unrecove= rable exception if = there is no matching database row. If the class is mapped with= a proxy, = load() just returns an uninitialized proxy = and does not = actually hit the database until you invoke a method of the pro= xy. This = - behaviour is very useful if you wish to create an association = to an object + 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 batch-size is defined for the class mapping. @@ -217,7 +217,7 @@ = If you are not certain that a matching row exists, you should = use the = - get() method, which hits the database immed= iately and = + get() method which hits the database immedi= ately and = returns null if there is no matching row. = @@ -229,15 +229,15 @@ return cat;]]> = - You may even load an object using an SQL SELECT ... F= OR UPDATE, + You can even load an object using an SQL SELECT ... F= OR UPDATE, using a LockMode. See the API documentation= for more information. = = - Note that any associated instances or contained collections ar= e = - not selected FOR UPDATE, unless you decide + Any associated instances or contained collections will = + not be selected FOR UPDATE, unless you decide to specify lock or all a= s a cascade style for the association. @@ -253,9 +253,9 @@ sess.refresh(cat); //re-read the state (after the trigger executes)]]> = - An important question usually appears at this point: How much = does Hibernate load + How much does Hibernate load from the database and how many SQL SELECTs = will it use? This - depends on the fetching strategy and is e= xplained in + depends on the fetching strategy. This is= explained in . = @@ -265,11 +265,11 @@ Querying = - If you don't know the identifiers of the objects you are looki= ng for, = + If you do not know the identifiers of the objects you are look= ing for, = you need a query. Hibernate supports an easy-to-use but powerf= ul object = oriented query language (HQL). For programmatic query creation= , Hibernate supports a sophisticated Criteria and Example query feature (Q= BC and QBE). - You may also express your query in the native SQL of your data= base, with + You can also express your query in the native SQL of your data= base, with optional support from Hibernate for result set conversion into= objects. = @@ -308,14 +308,14 @@ Set uniqueMothers =3D new HashSet(mothersWithKittens.list());]]> = - A query is usually executed by invoking list(), the + A query is usually executed by invoking list(). The result of the query will be loaded completely into a colle= ction in memory. - Entity instances retrieved by a query are in persistent st= ate. The + Entity instances retrieved by a query are in a persistent = state. The uniqueResult() method offers a shortcut= if you - know your query will only return a single object. Note tha= t queries that + know your query will only return a single object. Queries = that make use of eager fetching of collections usually return d= uplicates of - the root objects (but with their collections initialized).= You can filter - these duplicates simply through a Set. + the root objects, but with their collections initialized. = You can filter + these duplicates through a Set. = @@ -324,7 +324,7 @@ Occasionally, you might be able to achieve better perf= ormance by executing the query using the iterate() method. - This will only usually be the case if you expect that = the actual + This will usually be the case if you expect that the a= ctual entity instances returned by the query will already be= in the session or second-level cache. If they are not already cached, iterate() will be slower than list() @@ -351,7 +351,7 @@ Queries that return tuples = - Hibernate queries sometimes return tuples of objects, = in which case each tuple + Hibernate queries sometimes return tuples of objects. = Each tuple is returned as an array: = @@ -373,9 +373,9 @@ Scalar results = - Queries may specify a property of a class in the select clause. - They may even call SQL aggregate functions. Properties= or aggregates are considered - "scalar" results (and not entities in persistent state= ). + Queries can specify a property of a class in the select clause. + They can even call SQL aggregate functions. Properties= or aggregates are considered + "scalar" results and not entities in persistent state. = ? pa= rameters. = Contrary to JDBC, Hibernate numbers paramete= rs from zero. Named parameters are identifiers of the form = :name in = - the query string. The advantages of named parameters a= re: + the query string. The advantages of named parameters a= re as follows: = @@ -414,7 +414,7 @@ - they may occur multiple times in the same query + they can occur multiple times in the same query @@ -448,8 +448,8 @@ Pagination = - If you need to specify bounds upon your result set (th= e maximum number of rows - you want to retrieve and / or the first row you want t= o retrieve) you should + If you need to specify bounds upon your result set, th= at 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 Query interface: = @@ -470,8 +470,8 @@ = If your JDBC driver supports scrollable Resul= tSets, the - Query interface may be used to obta= in a - ScrollableResults object, which all= ows flexible + Query interface can be used to obta= in a + ScrollableResults object that allow= s flexible navigation of the query results. = @@ -498,8 +498,8 @@ cats.close()]]> = - Note that an open database connection (and cursor) is = required for this - functionality, use setMaxResult()/<= literal>setFirstResult() + Note that an open database connection and cursor is re= quired for this + functionality. Use setMaxResult()/<= literal>setFirstResult() if you need offline pagination functionality. = @@ -509,9 +509,9 @@ Externalizing named queries = - You may also define named queries in the mapping docum= ent. (Remember to use a + You can also define named queries in the mapping docum= ent. Remember to use a CDATA section if your query contain= s characters that could - be interpreted as markup.) + be interpreted as markup. = = - Note that the actual program code is independent of th= e query language that - is used, you may also define native SQL queries in met= adata, or migrate + The actual program code is independent of the query la= nguage that + is used. You can also define native SQL queries in met= adata, or migrate existing queries to Hibernate by placing them in mappi= ng files. = @@ -539,7 +539,7 @@ Also note that a query declaration inside a &= lt;hibernate-mapping> element requires a global unique name for the query, w= hile a query declaration inside a <class> element is made uniqu= e automatically by prepending the - fully qualified name of the class, for example + fully qualified name of the class. For example eg.Cat.ByNameAndMaximumWeight. = @@ -550,8 +550,8 @@ Filtering collections - A collection filter is a special type= of query that may be applied to - a persistent collection or array. The query string may ref= er to this, + A collection filter is a special type= of query that can be applied to + a persistent collection or array. The query string can ref= er to this, meaning the current collection element. = @@ -563,14 +563,14 @@ );]]> = - The returned collection is considered a bag, and it's a co= py of the given - collection. The original collection is not modified (this = is contrary to - the implication of the name "filter", but consistent with = expected behavior). + The returned collection is considered a bag that is a copy= of the given + collection. The original collection is not modified. This = is contrary to + the implication of the name "filter", but consistent with = expected behavior. = - Observe that filters do not require a from clause (though they may have - one if required). Filters are not limited to returning the= collection elements themselves. + Observe that filters do not require a from clause, although they can have + one if required. Filters are not limited to returning the = collection elements themselves. = Even an empty filter query is useful, e.g. to load a subse= t of elements in a - huge collection: + large collection: = Criteria queries = - HQL is extremely powerful but some developers prefer to bu= ild queries dynamically, + HQL is extremely powerful, but some developers prefer to b= uild queries dynamically using an object-oriented API, rather than building query s= trings. Hibernate provides an intuitive Criteria query API for the= se cases: @@ -615,10 +615,10 @@ Queries in native SQL = - You may express a query in SQL, using createSQLQu= ery() and - let Hibernate take care of the mapping from result sets to= objects. Note - that you may at any time call session.connection(= ) and - use the JDBC Connection directly. If yo= u chose to use the + You can express a query in SQL, using createSQLQu= ery() and + let Hibernate manage the mapping from result sets to objec= ts. + You can at any time call session.connection() and + use the JDBC Connection directly. If yo= u choose to use the Hibernate API, you must enclose SQL aliases in braces: = @@ -634,7 +634,7 @@ .list()]]> = - SQL queries may contain named and positional parameters, j= ust like Hibernate queries. + SQL queries can contain named and positional parameters, j= ust like Hibernate queries. More information about native SQL queries in Hibernate can= be found in . @@ -647,14 +647,14 @@ Modifying persistent objects = - Transactional persistent instances (ie. o= bjects loaded, saved, created or - queried by the Session) may be manipulated = by the application + Transactional persistent instances (i.e. = objects loaded, saved, created or + queried by the Session) can be manipulated = by the application, and any changes to persistent state will be persisted when the= Session - is flushed (discussed later in this chapt= er). There is no need + is flushed. This is discussed later in t= his chapter. There is no need to call a particular method (like update(),= which has a different - purpose) to make your modifications persistent. So the most st= raightforward way to update - the state of an object is to load() it, - and then manipulate it directly, while the Session is open: + purpose) to make your modifications persistent. The most strai= ghtforward way to update + the state of an object is to load() it + and then manipulate it directly while the Session is open: = = - Sometimes this programming model is inefficient since it would= require both an SQL - SELECT (to load an object) and an SQL UPDATE - (to persist its updated state) in the same session. Therefore = Hibernate offers an - alternate approach, using detached instances. + Sometimes this programming model is inefficient, as it require= s in the same session both an SQL + SELECT to load an object and an SQL UPDATE + to persist its updated state. Hibernate offers an + alternate approach by using detached instances. = - - Note that Hibernate does not offer its own API for d= irect execution of + + Hibernate does not offer its own API for direct execution of UPDATE or DELETE stateme= nts. Hibernate is a - state management service, you don't have = to think in + state management service, you do not have= to think in statements to use it. JDBC is a perfect A= PI for executing SQL statements, you can get a JDBC Connection at any time by calling session.connection(). Furthermor= e, the notion of mass operations conflicts with object/relational mapping fo= r online transaction processing-oriented applications. Future versions = of Hibernate - may however provide special mass operation functions. See - for some possible batch operation tricks. + can, however, provide special mass operation functions. See + for some possible batch operation tricks. + = = @@ -690,7 +691,7 @@ Many applications need to retrieve an object in one transactio= n, send it to the UI layer for manipulation, then save the changes in a new tran= saction. Applications that use this kind of approach in a high-concurre= ncy environment - usually use versioned data to ensure isolation for the "long"= unit of work. + usually use versioned data to ensure isolation for the "long" = unit of work. = @@ -713,29 +714,29 @@ = If the Cat with identifier catId had already - been loaded by secondSession when the appl= ication tried to + been loaded by secondSession when the appli= cation tried to reattach it, an exception would have been thrown. = - Use update() if you are sure that the sessi= on does - not contain an already persistent instance with the same ident= ifier, and + Use update() if you are certain that the se= ssion does + not contain an already persistent instance with the same ident= ifier. Use merge() if you want to merge your modificat= ions at any time without consideration of the state of the session. In other wo= rds, update() is usually the first method you would call in a fresh session,= ensuring that - reattachment of your detached instances is the first operation= that is executed. + the reattachment of your detached instances is the first opera= tion that is executed. = The application should individually update() detached instances - reachable from the given detached instance if and on= ly if it wants - their state also updated. This can be automated of course, usi= ng transitive - persistence, see . + 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 for more information. = The lock() method also allows an applicatio= n to reassociate - an object with a new session. However, the detached instance h= as to be unmodified! + an object with a new session. However, the detached instance h= as to be unmodified. = Note that lock() can be used with various - LockModes, see the API documentation and the + LockModes. See the API documentation and the chapter on transaction handling for more information. Reattach= ment is not the only usecase for lock(). @@ -850,8 +851,8 @@ - if the object is versioned (by a <version&= gt; or - <timestamp>), and the version= property value + if the object is versioned by a <version&g= t; or + <timestamp>, and the version = property value is the same value assigned to a newly instantiated obj= ect, = save() it @@ -901,15 +902,15 @@ = Session.delete() will remove an object's st= ate from the database. - Of course, your application might still hold a reference to a = deleted object. - It's best to think of delete() as making a = persistent instance + Your application, however, can still hold a reference to a del= eted object. + It is best to think of delete() as making a= persistent instance, transient. = = - You may delete objects in any order you like, without risk of = foreign key + You can delete objects in any order, without risk of foreign k= ey constraint violations. It is still possible to violate a NOT NULL 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 @@ -922,7 +923,7 @@ Replicating object between two different datastores = - It is occasionally useful to be able to take a graph of persisten= t instances + It is sometimes useful to be able to take a graph of persistent i= nstances and make them persistent in a different datastore, without regene= rating identifier values. @@ -943,31 +944,31 @@ = The ReplicationMode determines how replicate() - will deal with conflicts with existing rows in the database. + will deal with conflicts with existing rows in the database: = - ReplicationMode.IGNORE - ignore the= object when there is + ReplicationMode.IGNORE: ignores the= object when there is an existing database row with the same identifier - ReplicationMode.OVERWRITE - overwri= te any existing database = + ReplicationMode.OVERWRITE: overwrit= es any existing database = row with the same identifier - ReplicationMode.EXCEPTION - throw a= n exception if there is + ReplicationMode.EXCEPTION: throws a= n exception if there is an existing database row with the same identifier - ReplicationMode.LATEST_VERSION - ov= erwrite the row if its + ReplicationMode.LATEST_VERSION: ove= rwrites the row if its version number is earlier than the version number of t= he object, or ignore the object otherwise @@ -986,10 +987,10 @@ Flushing the Session = - From time to time the Session will execute = the SQL statements = + Sometimes the Session will execute the SQL = statements = needed to synchronize the JDBC connection's state with the sta= te of objects held in = - memory. This process, flush, occurs by de= fault at the following = - points + memory. This process, called flush, occur= s by default at the following = + points: = @@ -1011,13 +1012,13 @@ = - The SQL statements are issued in the following order + The SQL statements are issued in the following order: = - all entity insertions, in the same order the correspon= ding objects + all entity insertions in the same order the correspond= ing objects were saved using Session.save() @@ -1043,30 +1044,30 @@ - all entity deletions, in the same order the correspond= ing objects + all entity deletions in the same order the correspondi= ng objects were deleted using Session.delete() = - (An exception is that objects using native = ID generation are = - inserted when they are saved.) + An exception is that objects using native I= D generation are = + inserted when they are saved. = - Except when you explicity flush(), there ar= e absolutely no = + Except when you explicitly flush(), there a= re absolutely no = guarantees about when the Sessio= n executes = the JDBC calls, only the order in which t= hey are executed. However, Hibernate does guarantee that the Query.list= (..) = - will never return stale data; nor will they return the wrong d= ata. + will never return stale or incorrect data. = It is possible to change the default behavior so that flush oc= curs less frequently. The FlushMode class defines three different= modes: only flush - at commit time (and only when the Hibernate Transacti= on API - is used), flush automatically using the explained routine, or = never flush unless + at commit time when the Hibernate Transaction API + is used, flush automatically using the explained routine, or n= ever flush unless flush() is called explicitly. The last mode= is useful for long running units of work, where a Session is kept open= and disconnected for a long time (see ). @@ -1108,17 +1109,17 @@ If the children in a parent/child relationship would be value = typed (e.g. a collection of addresses or strings), their life cycle would depend on the= parent and no further action would be required for convenient "cascading" of= state changes. - When the parent is saved, the value-typed child objects are sa= ved as - well, when the parent is deleted, the children will be deleted= , etc. This - even works for operations such as the removal of a child from = the collection; - Hibernate will detect this and, since value-typed objects can'= t have shared - references, delete the child from the database. + When the parent is saved, the value-typed child objects are sa= ved and + when the parent is deleted, the children will be deleted, etc.= This + works for operations such as the removal of a child from the c= ollection. + Since value-typed objects cannot have shared + references, Hibernate will detect this and delete the child fr= om the database. = Now consider the same scenario with parent and child objects b= eing entities, not value-types (e.g. categories and items, or parent and chil= d cats). Entities - have their own life cycle, support shared references (so remov= ing an entity from + have their own life cycle and support shared references. Remo= ving an entity from the collection does not mean it can be deleted), and there is = by default no cascading of state from one entity to any other associated ent= ities. Hibernate does not implement persistence by reachability by default. @@ -1142,7 +1143,7 @@ ]]> = - You may even use cascade=3D"all" to specify= that all + You can even use cascade=3D"all" to specify= that all operations should be cascaded along the association. The defau= lt cascade=3D"none" specifies that no operations are to be cascaded. @@ -1161,7 +1162,7 @@ - It doesn't usually make sense to enable cascade on a <= literal><many-to-one> + It does not usually make sense to enable cascade on a = <many-to-one> or <many-to-many> association= . Cascade is often useful for = <one-to-one> and <= ;one-to-many> associations. @@ -1190,7 +1191,7 @@ parent results in save/update/delete of the child or children. - Futhermore, a mere reference to a child from a persistent pare= nt will result in = + Furthermore, a mere reference to a child from a persistent par= ent will result in = save/update of the child. This metaphor is incomplete, however= . A child which becomes = unreferenced by its parent is not automat= ically deleted, except = in the case of a <one-to-many> associ= ation mapped with @@ -1242,7 +1243,7 @@ Finally, note that cascading of operations can be applied to a= n 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, save-upate and = delete-orphan + executed. However, save-update and delete-orphan are transitive for all associated entities reachable during fl= ush of the Session. @@ -1253,16 +1254,16 @@ Using metadata = - Hibernate requires a very rich meta-level model of all entity = and value types. From time - to time, this model is very useful to the application itself. = For example, the application + Hibernate requires a rich meta-level model of all entity and v= alue types. = + This model can be useful to the application itself. For exampl= e, the application might use Hibernate's metadata to implement a "smart" deep-cop= y algorithm that understands - which objects should be copied (eg. mutable value types) and w= hich should not (eg. = + which objects should be copied (eg. mutable value types) and w= hich objects that should not (e.g. = immutable value types and, possibly, associated entities). Hibernate exposes metadata via the ClassMetadata and CollectionMetadata interfaces and the Type - hierarchy. Instances of the metadata interfaces may be obtaine= d from the = + hierarchy. Instances of the metadata interfaces can be obtaine= d from the = SessionFactory. = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/toolset_guide.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/toolset_guide.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/toolset_guide.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -30,57 +30,57 @@ = Roundtrip engineering with Hibernate is possible using a set of Ec= lipse plugins, - commandline tools, as well as Ant tasks. + commandline tools, and Ant tasks. = - The Hibernate Tools currently include plugins= for the Eclipse + Hibernate Tools currently include plugins for= the Eclipse IDE as well as Ant tasks for reverse engineering of existing datab= ases: = - Mapping Editor: An editor for Hibernate X= ML mapping files, - supporting auto-completion and syntax highlighting. It also su= pports semantic - auto-completion for class names and property/field names, maki= ng it much more versatile than a normal XML editor. + Mapping Editor: an editor for Hibernate X= ML mapping files that + supports auto-completion and syntax highlighting. It also supp= orts semantic + auto-completion for class names and property/field names, maki= ng it more versatile than a normal XML editor. - Console: The console is a new view in Ecl= ipse. In addition to - a tree overview of your console configurations, you also get a= n interactive view + Console: the console is a new view in Ecl= ipse. In addition to + a tree overview of your console configurations, you are also p= rovided with an interactive view of your persistent classes and their relationships. The consol= e allows you to execute HQL queries against your database and browse the resul= t directly in Eclipse. - Development Wizards: Several wizards are = provided with the - Hibernate Eclipse tools; you can use a wizard to quickly gener= ate Hibernate configuration - (cfg.xml) files, or you may even completely reverse engineer a= n existing database schema + Development Wizards: several wizards are = provided with the + Hibernate Eclipse tools. You can use a wizard to quickly gener= ate Hibernate configuration + (cfg.xml) files, or to reverse engineer an existing database s= chema into POJO source files and Hibernate mapping files. The revers= e engineering wizard supports customizable templates. - Ant Tasks: + = = - Please refer to the Hibernate Tools package a= nd it's documentation + Please refer to the Hibernate Tools package d= ocumentation for more information. = - However, the Hibernate main package comes bundled with an integrat= ed tool (it can even - be used from "inside" Hibernate on-the-fly): SchemaExpor= t aka - hbm2ddl. + However, the Hibernate main package comes bundled with an integrat= ed tool : SchemaExport aka + hbm2ddl.It can even + be used from "inside" Hibernate. = Automatic schema generation = - DDL may be generated from your mapping files by a Hibernate ut= ility. The generated - schema includes referential integrity constraints (primary and= foreign keys) for + DDL can be generated from your mapping files by a Hibernate ut= ility. The generated + schema includes referential integrity constraints, primary and= foreign keys, for entity and collection tables. Tables and sequences are also cr= eated for mapped identifier generators. @@ -88,11 +88,11 @@ You must specify a SQL Dialect via the = hibernate.dialect property when using this = tool, as DDL - is highly vendor specific. + is highly vendor-specific. = - First, customize your mapping files to improve the generated s= chema. + First, you must customize your mapping files to improve the ge= nerated schema. The next section covers schema customization. = = @@ -100,7 +100,7 @@ = Many Hibernate mapping elements define optional attributes= named length, - precision and scale.= You may set the length, precision = + precision and scale.= You can set the length, precision = and scale of a column with this attribute. = = @@ -109,9 +109,9 @@ ]]> = - Some tags also accept a not-null attrib= ute (for generating a = - NOT NULL constraint on table columns) a= nd a unique = - attribute (for generating UNIQUE constr= aint on table columns). + Some tags also accept a not-null attrib= ute for generating a = + NOT NULL constraint on table columns, a= nd a unique = + attribute for generating UNIQUE constra= int on table columns. = ]]> @@ -119,10 +119,10 @@ ]]> = - A unique-key attribute may be used to g= roup columns in - a single unique key constraint. Currently, the specified v= alue of the = + A unique-key attribute can be used to g= roup columns in + a single, unique key constraint. Currently, the specified = value of the = unique-key attribute is not used = - to name the constraint in the generated DDL, only to group= the columns in = + to name the constraint in the generated DDL. It is only us= ed to group the columns in = the mapping file. = @@ -131,15 +131,15 @@ = An index attribute specifies the name o= f an index that - will be created using the mapped column or columns. Multip= le columns may be = - grouped into the same index, simply by specifying the same= index name. = + will be created using the mapped column or columns. Multip= le columns can be = + grouped into the same index by simply specifying the same = index name. = = ]]> = - A foreign-key attribute may be used to = override the name = + A foreign-key attribute can be used to = override the name = of any generated foreign key constraint. = @@ -157,9 +157,9 @@ ]]> = - The default attribute lets you specify = a default value for - a column (you should assign the same value to the mapped p= roperty before - saving a new instance of the mapped class). + The default attribute allows you to spe= cify a default value for + a column.You should assign the same value to the mapped pr= operty before + saving a new instance of the mapped class. = @@ -193,6 +193,8 @@ ]]> = = + The following table summarizes these optional attributes. +
Summary @@ -225,7 +227,7 @@ not-null true|false - specfies that the column should be non-= nullable + specifies that the column should be non= -nullable unique @@ -299,7 +301,7 @@ This results in a comment on table or = comment on column statement in the gene= rated - DDL (where supported). + DDL where supported. = @@ -311,8 +313,10 @@ The SchemaExport tool writes a DDL scri= pt to standard out and/or executes the DDL statements. - - + = + The following table displays the SchemaExport co= mmand line options + = + java -cp hibernate_classpaths= org.hibernate.tool.hbm2ddl.SchemaExport= options mapping_files @@ -331,7 +335,7 @@ --quiet - don't output the script to stdout + do not output the script to stdout --drop @@ -343,7 +347,7 @@ --text - don't export to the database + do not export to the database --output=3Dmy_schema.ddl @@ -374,7 +378,7 @@
= - You may even embed SchemaExport in your= application: + You can even embed SchemaExport in your= application: = Properties = - Database properties may be specified + Database properties can be specified: = @@ -475,7 +479,7 @@ = The SchemaUpdate tool will update an ex= isting schema with "incremental" changes. - Note that SchemaUpdate depends heavily = upon the JDBC metadata API, so it will + The SchemaUpdate depends upon the JDBC = metadata API and, as such, will not work with all JDBC drivers. = @@ -498,11 +502,11 @@ --quiet - don't output the script to stdout + do not output the script to stdout --text - don't export the script to the database= + do not export the script to the databas= e --naming=3Deg.MyNamingStrategy= @@ -521,7 +525,7 @@ = - You may embed SchemaUpdate in your appl= ication: + You can embed SchemaUpdate in your appl= ication: = The SchemaValidator tool will validate = that the existing database schema "matches" - your mapping documents. Note that SchemaValidator= depends heavily upon the JDBC = - metadata API, so it will not work with all JDBC drivers. T= his tool is extremely useful for testing. + your mapping documents. The SchemaValidator depends heavily upon the JDBC = + metadata API and, as such, will not work with all JDBC dri= vers. This tool is extremely useful for testing.
= java -cp hibernate_classpaths= org.hibernate.tool.hbm2ddl.SchemaValidator options mapping_files - +The following table displays the SchemaValidator = command line options: <literal>SchemaValidator</literal> Command Line Opt= ions @@ -595,7 +599,7 @@
= - You may embed SchemaValidator in your a= pplication: + You can embed SchemaValidator in your a= pplication: = = - Transactions And Concurrency + Transactions and Concurrency = - The most important point about Hibernate and concurrency control i= s that it is very + The most important point about Hibernate and concurrency control i= s that it is easy to understand. Hibernate directly uses JDBC connections and J= TA resources without - adding any additional locking behavior. We highly recommend you sp= end some time with the + adding any additional locking behavior. It is recommended that you= spend some time with the JDBC, ANSI, and transaction isolation specification of your databa= se management system. = Hibernate does not lock objects in memory. Your application can ex= pect the behavior as - defined by the isolation level of your database transactions. Note= that thanks to the + defined by the isolation level of your database transactions. Thro= ugh Session, which is also a transaction-scoped cac= he, Hibernate - provides repeatable reads for lookup by identifier and entity quer= ies (not - reporting queries that return scalar values). + provides repeatable reads for lookup by identifier and entity quer= ies and not + reporting queries that return scalar values. = In addition to versioning for automatic optimistic concurrency con= trol, Hibernate also - offers a (minor) API for pessimistic locking of rows, using the - SELECT FOR UPDATE syntax. Optimistic concurrenc= y control and + offers, using the + SELECT FOR UPDATE syntax, a (minor) API for pes= simistic locking of rows. Optimistic concurrency control and this API are discussed later in this chapter. = - We start the discussion of concurrency control in Hibernate with t= he granularity of + The discussion of concurrency control in Hibernate begins with the= granularity of Configuration, SessionFactory, and Session, as well as database transactions and l= ong conversations. @@ -60,61 +60,59 @@ Session and transaction scopes = - A SessionFactory is an expensive-to-create,= threadsafe object = + A SessionFactory is an expensive-to-create,= threadsafe object, = intended to be shared by all application threads. It is create= d once, usually on application startup, from a Configuration i= nstance. = A Session is an inexpensive, non-threadsafe= object that should be - used once, for a single request, a conversation, single unit o= f work, and then discarded. - A Session will not obtain a JDBC C= onnection - (or a Datasource) unless it is needed, henc= e consume no + used once and then discarded for: a single request, a conversa= tion or a single unit of work. + A Session will not obtain a JDBC C= onnection, + or a Datasource, unless it is needed. It wi= ll not consume any resources until used. = - To complete this picture you also have to think about database= transactions. A - database transaction has to be as short as possible, to reduce= lock contention in - the database. Long database transactions will prevent your app= lication from scaling - to highly concurrent load. Hence, it is almost never good desi= gn to hold a - database transaction open during user think time, until the un= it of work is + 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 ho= ld a + database transaction open during user think time until the uni= t of work is complete. = What is the scope of a unit of work? Can a single Hibernate Session - span several database transactions or is this a one-to-one rel= ationship of scopes? When + span several database transactions, or is this a one-to-one re= lationship of scopes? When should you open and close a Session and how= do you demarcate the - database transaction boundaries? + database transaction boundaries? These questions are addressed= in the following sections. = Unit of work = - First, don't use the session-per-operation antipattern, that is, - don't open and close a Session for ever= y simple database call in - a single thread! Of course, the same is true for database = transactions. Database calls - in an application are made using a planned sequence, they = are grouped into atomic - units of work. (Note that this also means that auto-commit= after every single - SQL statement is useless in an application, this mode is i= ntended for ad-hoc SQL - console work. Hibernate disables, or expects the applicati= on server to do so, - auto-commit mode immediately.) Database transactions are n= ever optional, all - communication with a database has to occur inside a transa= ction, no matter if - you read or write data. As explained, auto-commit behavior= for reading data + Do not use the session-per-operation = antipattern: + do not open and close a Session for eve= ry simple database call in + a single thread. The same is true for database transaction= s. Database calls + in an application are made using a planned sequence; they = are grouped into atomic + units of work. This also means that auto-commit after ever= y single + SQL statement is useless in an application as this mode is= intended for ad-hoc SQL + console work. Hibernate disables, or expects the applicati= on server to disable, + auto-commit mode immediately. Database transactions are ne= ver optional. All + communication with a database has to occur inside a transa= ction. Auto-commit behavior for reading data should be avoided, as many small transactions are unlikely= to perform better than - one clearly defined unit of work. The latter is also much = more maintainable + one clearly defined unit of work. The latter is also more = maintainable and extensible. = The most common pattern in a multi-user client/server appl= ication is session-per-request. In this model, a= request from the client - is sent to the server (where the Hibernate persistence lay= er runs), a new Hibernate + is sent to the server, where the Hibernate persistence lay= er runs. A new Hibernate Session is opened, and all database ope= rations are executed in this unit - of work. Once the work has been completed (and the respons= e for the client has been prepared), - the session is flushed and closed. You would also use a si= ngle database transaction to + of work. On completion of the work, and once the response = for the client has been prepared, + the session is flushed and closed. Use a single database t= ransaction to serve the clients request, starting and committing it when= you open and close the Session. The relationship between the t= wo is one-to-one and this model is a perfect fit for many applications. @@ -122,34 +120,33 @@ = The challenge lies in the implementation. Hibernate provid= es built-in management of - the "current session" to simplify this pattern. All you ha= ve to do is start a + the "current session" to simplify this pattern. Start a transaction when a server request has to be processed, and= end the transaction - before the response is sent to the client. You can do this= in any way you - like, common solutions are ServletFilter, AOP interceptor with a + before the response is sent to the client. Common solution= s are ServletFilter, AOP interceptor with a pointcut on the service methods, or a proxy/interception c= ontainer. An EJB container is a standardized way to implement cross-cutting aspects s= uch as transaction - demarcation on EJB session beans, declaratively with CMT. = If you decide to - use programmatic transaction demarcation, prefer the Hiber= nate Transaction - API shown later in this chapter, for ease of use and code = portability. + demarcation on EJB session beans, declaratively with CMT. = If you + use programmatic transaction demarcation, for ease of use = and code portability use the Hibernate Transaction + API shown later in this chapter. = Your application code can access a "current session" to pr= ocess the request - by simply calling sessionFactory.getCurrentSessio= n() anywhere - and as often as needed. You will always get a Ses= sion scoped + by calling sessionFactory.getCurrentSession(). = + You will always get a Session scoped to the current database transaction. This has to be config= ured for either resource-local or JTA environments, see . = - Sometimes it is convenient to extend the scope of a Session and + You can extend the scope of a Session a= nd database transaction until the "view has been rendered". T= his is especially useful in servlet applications that utilize a separate rendering = phase after the request - has been processed. Extending the database transaction unt= il view rendering is - complete is easy to do if you implement your own intercept= or. However, it is not - easily doable if you rely on EJBs with container-managed t= ransactions, as a + has been processed. Extending the database transaction unt= il view rendering, is achieved by implementing + your own interceptor. However, this will be difficult + if you rely on EJBs with container-managed transactions. A transaction will be completed when an EJB method returns, = before rendering of any - view can start. See the Hibernate website and forum for ti= ps and examples around + view can start. See the Hibernate website and forum for ti= ps and examples relating to this Open Session in View pattern. = @@ -159,9 +156,9 @@ Long conversations = - The session-per-request pattern is not the only useful con= cept you can use to design - units of work. Many business processes require a whole ser= ies of interactions with the user - interleaved with database accesses. In web and enterprise = applications it is + The session-per-request pattern is not the only way of des= igning + units of work. Many business processes require a whole ser= ies of interactions with the user that are + interleaved with database accesses. In web and enterprise = applications, it is not acceptable for a database transaction to span a user i= nteraction. Consider the following example: @@ -169,82 +166,82 @@ - The first screen of a dialog opens, the data seen = by the user has been loaded in + The first screen of a dialog opens. The data seen = by the user has been loaded in a particular Session and databa= se transaction. The user is free to modify the objects. - The user clicks "Save" after 5 minutes and expects= his modifications to be made - persistent; he also expects that he was the only p= erson editing this information and - that no conflicting modification can occur. + The user clicks "Save" after 5 minutes and expects= their modifications to be made + persistent. The user also expects that they were t= he only person editing this information and + that no conflicting modification has occurred. = - We call this unit of work, from the point of view of the u= ser, a long running - conversation (or applicatio= n transaction). - There are many ways how you can implement this in your app= lication. + From the point of view of the user, we call this unit of w= ork a long-running + conversation or application= transaction. + There are many ways to implement this in your application. = A first naive implementation might keep the Sessi= on and database transaction open during user think time, with locks held i= n the database to prevent - concurrent modification, and to guarantee isolation and at= omicity. This is of course + concurrent modification and to guarantee isolation and ato= micity. This is = an anti-pattern, since lock contention would not allow the= application to scale with the number of concurrent users. = - Clearly, we have to use several database transactions to i= mplement the conversation. + You have to use several database transactions to implement= the conversation. In this case, maintaining isolation of business processes = becomes the partial responsibility of the application tier. A single c= onversation usually spans several database transactions. It will be at= omic if only one of - these database transactions (the last one) stores the upda= ted data, all others - simply read data (e.g. in a wizard-style dialog spanning s= everal request/response + these database transactions (the last one) stores the upda= ted data. All others + simply read data (for example, in a wizard-style dialog sp= anning several request/response cycles). This is easier to implement than it might sound, = especially if - you use Hibernate's features: + you utilize some of Hibernate's features: = - Automatic Versioning - Hibern= ate can do automatic - optimistic concurrency control for you, it can aut= omatically detect - if a concurrent modification occurred during user = think time. Usually - we only check at the end of the conversation. + Automatic Versioning: Hiberna= te can perform automatic + optimistic concurrency control for you. It can aut= omatically detect + if a concurrent modification occurred during user = think time. Check for this at = + the end of the conversation. - Detached Objects - If you dec= ide to use the already - discussed session-per-request= pattern, all loaded instances - will be in detached state during user think time. = Hibernate allows you to - reattach the objects and persist the modifications= , the pattern is called + Detached Objects: if you deci= de to use the + session-per-request pattern, = all loaded instances + will be in the detached state during user think ti= me. Hibernate allows you to + reattach the objects and persist the modifications= . The pattern is called session-per-request-with-detached-object= s. Automatic versioning is used to isolate concurrent modificat= ions. - Extended (or Long) Session - = The Hibernate - Session may be disconnected fro= m the underlying JDBC - connection after the database transaction has been= committed, and reconnected + Extended (or Long) Session: t= he Hibernate + Session can be disconnected fro= m the underlying JDBC + connection after the database transaction has been= committed and reconnected when a new client request occurs. This pattern is = known as session-per-conversation and = makes even reattachment unnecessary. Automatic versionin= g is used to isolate - concurrent modifications and the Session<= /literal> is usually - not allowed to be flushed automatically, but expli= citly. + concurrent modifications and the Session<= /literal> will not + be allowed to be flushed automatically, but explic= itly. = Both session-per-request-with-detached-objects and - session-per-conversation have advanta= ges and disadvantages, - we discuss them later in this chapter in the context of op= timistic concurrency control. + session-per-conversation have advanta= ges and disadvantages. + These disadvantages are discussed later in this chapter in= the context of optimistic concurrency control. = @@ -253,9 +250,9 @@ Considering object identity = - An application may concurrently access the same persistent= state in two + An application can concurrently access the same persistent= state in two different Sessions. However, an instanc= e of a persistent class - is never shared between two Session ins= tances. Hence there are + is never shared between two Session ins= tances. It is for this reason that there are two different notions of identity: = @@ -279,38 +276,38 @@ = - Then for objects attached to a particular Session - (i.e. in the scope of a Session) the tw= o notions are equivalent, and - JVM identity for database identity is guaranteed by Hibern= ate. However, while the application + For objects attached to a particular = Session + (i.e., in the scope of a Session), the = two notions are equivalent and + JVM identity for database identity is guaranteed by Hibern= ate. 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 (automatic versioning) at flush/commit time= , using an optimistic approach. + resolved using an optimistic approach and automatic versio= ning at flush/commit time. = - This approach leaves Hibernate and the database to worry a= bout concurrency; it also provides - the best scalability, since guaranteeing identity in singl= e-threaded units of work only doesn't - need expensive locking or other means of synchronization. = The application never needs to - synchronize on any business object, as long as it sticks t= o a single thread per - Session. Within a Session the application may safely use + This approach leaves Hibernate and the database to worry a= bout concurrency. It also provides + the best scalability, since guaranteeing identity in singl= e-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 maintain= s a single thread per + Session. Within a Session the application can safely use =3D=3D to compare objects. = - However, an application that uses =3D=3D outside of a Session, - might see unexpected results. This might occur even in som= e unexpected places, for example, - if you put two detached instances into the same S= et. Both might have the same - database identity (i.e. they represent the same row), but = JVM identity is by definition not - guaranteed for instances in detached state. The developer = has to override the equals() + However, an application that uses =3D=3D outside of a Session + might produce unexpected results. This might occur even in= some unexpected places. For example, + if you put two detached instances into the same S= et, both might have the same + database identity (i.e., they represent the same row). JVM= identity, however, is by definition not + guaranteed for instances in a detached state. The develope= r has to override the equals() and hashCode() methods in persistent cl= asses and implement - his own notion of object equality. There is one caveat: Ne= ver use the database - identifier to implement equality, use a business key, a co= mbination of unique, usually + their own notion of object equality. There is one caveat: = never use the database + identifier to implement equality. Use a business key that = is a combination of unique, usually immutable, attributes. The database identifier will change= if a transient object is made persistent. If the transient instance (usually together wi= th detached instances) is held in a Set, changing the hashcode breaks the c= ontract of the Set. - Attributes for business keys don't have to be as stable as= database primary keys, you only + Attributes for business keys do not have to be as stable a= s database primary keys; you only have to guarantee stability as long as the objects are in = the same Set. See - the Hibernate website for a more thorough discussion of th= is issue. Also note that this is not + the Hibernate website for a more thorough discussion of th= is issue. Please note that this is not a Hibernate issue, but simply how Java object identity and= equality has to be implemented. = @@ -320,46 +317,46 @@ Common issues = - Never use the anti-patterns session-per-user-se= ssion or - session-per-application (of course, = there are rare exceptions to - this rule). Note that some of the following issues might = also appear with the recommended - patterns, make sure you understand the implications befor= e making a design decision: + Do not use the anti-patterns session-per-user-s= ession or + session-per-application (there are, = however, rare exceptions to + this rule). Some of the following issues might also arise= within the recommended + patterns, so ensure that you understand the implications = before making a design decision: = - A Session is not thread-safe. T= hings which are supposed to work + A Session is not thread-safe. T= hings that work concurrently, like HTTP requests, session beans, o= r Swing workers, will cause race - conditions if a Session instanc= e would be shared. If you keep your - Hibernate Session in your HttpSession (discussed - later), you should consider synchronizing access t= o your Http session. Otherwise, - a user that clicks reload fast enough may use the = same Session in + conditions if a Session instanc= e is shared. If you keep your + Hibernate Session in your HttpSession (this is discussed + later in the chapter), you should consider synchro= nizing access to your Http session. Otherwise, + a user that clicks reload fast enough can use the = same Session in two concurrently running threads. An exception thrown by Hibernate means you have to= rollback your database transaction - and close the Session immediate= ly (discussed later in more detail). + and close the Session immediate= ly (this is discussed in more detail later in the chapter). If your Session is bound to the= application, you have to stop - the application. Rolling back the database transac= tion doesn't put your business - objects back into the state they were at the start= of the transaction. This means the - database state and the business objects do get out= of sync. Usually this is not a - problem, because exceptions are not recoverable an= d you have to start over after + the application. Rolling back the database transac= tion 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 ou= t of sync. Usually this is not a + problem, because exceptions are not recoverable an= d you will have to start over after rollback anyway. - The Session caches every object= that is in persistent state (watched - and checked for dirty state by Hibernate). This me= ans it grows endlessly until you - get an OutOfMemoryException, if you keep it open f= or a long time or simply load too - much data. One solution for this is to call clear() and evict() - to manage the Session cache, bu= t you most likely should consider a + The Session caches 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 ca= ll clear() and evict() + to manage the Session cache, bu= t you should consider a Stored Procedure if you need mass data operations.= Some solutions are shown in . Keeping a Sess= ion open for the duration - of a user session also means a high probability of= stale data. + of a user session also means a higher probability = of stale data. @@ -372,36 +369,36 @@ Database transaction demarcation = - Database (or system) transaction boundaries are always necessa= ry. No communication with + Database, or system, transaction boundaries are always necessa= ry. No communication with the database can occur outside of a database transaction (this= seems to confuse many developers who are used to the auto-commit mode). Always use clear transa= ction boundaries, even for read-only operations. Depending on your isolation level and da= tabase capabilities this might not - be required but there is no downside if you always demarcate t= ransactions explicitly. Certainly, + be required, but there is no downside if you always demarcate = transactions explicitly. Certainly, a single database transaction is going to perform better than = many small transactions, even for reading data. = - A Hibernate application can run in non-managed (i.e. standalon= e, simple Web- or Swing applications) + A Hibernate application can run in non-managed (i.e., standalo= ne, simple Web- or Swing applications) and managed J2EE environments. In a non-managed environment, H= ibernate is usually responsible for its own database connection pool. The application developer ha= s to manually set transaction - boundaries, in other words, begin, commit, or rollback databas= e transactions himself. A managed environment + boundaries (begin, commit, or rollback database transactions) = themselves. A managed environment usually provides container-managed transactions (CMT), with th= e transaction assembly defined declaratively - in deployment descriptors of EJB session beans, for example. P= rogrammatic transaction demarcation is + (in deployment descriptors of EJB session beans, for example).= Programmatic transaction demarcation is then no longer necessary. = However, it is often desirable to keep your persistence layer = portable between non-managed resource-local environments, and systems that can rely on JTA = but use BMT instead of CMT. - In both cases you'd use programmatic transaction demarcation. = Hibernate offers a wrapper + In both cases use programmatic transaction demarcation. Hibern= ate offers a wrapper API called Transaction that translates into= the native transaction system of your deployment environment. This API is actually optional, bu= t we strongly encourage its use unless you are in a CMT session bean. = - Usually, ending a Session involves four dis= tinct phases: + Ending a Session usually involves four dist= inct phases: = @@ -428,8 +425,8 @@ = - Flushing the session has been discussed earlier, we'll now hav= e a closer look at transaction - demarcation and exception handling in both managed- and non-ma= naged environments. + We discussed Flushing the session earlier, so we will now have= a closer look at transaction + demarcation and exception handling in both managed and non-man= aged environments. = = @@ -438,7 +435,7 @@ = If a Hibernate persistence layer runs in a non-managed env= ironment, database connections - are usually handled by simple (i.e. non-DataSource) connec= tion pools from which + are usually handled by simple (i.e., non-DataSource) conne= ction pools from which Hibernate obtains connections as needed. The session/transact= ion handling idiom looks like this: @@ -463,17 +460,17 @@ }]]> = - You don't have to flush() the = Session explicitly - - the call to commit() automatically trig= gers the synchronization (depending - upon the FlushMode for the session. + You do not have to flush() the Session explicitly: + the call to commit() automatically trig= gers the synchronization depending + on the FlushMode for the session. A call to close() marks the end of a se= ssion. The main implication of close() is that the JDBC connection = will be relinquished by the session. This Java code is portable and runs in both non-m= anaged and JTA environments. = - A much more flexible solution is Hibernate's built-in "cur= rent session" context - management, as described earlier: + As outlined earlier, a much more flexible solution is Hibe= rnate's built-in "current session" context + management: = = - You will very likely never see these code snippets in a re= gular application; + You will not see these code snippets in a regular applicat= ion; fatal (system) exceptions should always be caught at the "= top". In other words, the - code that executes Hibernate calls (in the persistence lay= er) and the code that handles - RuntimeException (and usually can only = clean up and exit) are in + code that executes Hibernate calls in the persistence laye= r, and the code that handles + RuntimeException (and usually can only = clean up and exit), are in different layers. The current context management by Hibern= ate can significantly - simplify this design, as all you need is access to a SessionFactory. + simplify this design by accessing a SessionFactor= y. Exception handling is discussed later in this chapter. = - Note that you should select org.hibernate.transac= tion.JDBCTransactionFactory - (which is the default), and for the second example "thread" as your + You should select org.hibernate.transaction.JDBCT= ransactionFactory, + which is the default, and for the second example select "thread" as your hibernate.current_session_context_class. = @@ -512,15 +509,15 @@ Using JTA = - If your persistence layer runs in an application server (e= .g. behind EJB session beans), + If your persistence layer runs in an application server (f= or example, behind EJB session beans), every datasource connection obtained by Hibernate will aut= omatically be part of the global JTA transaction. You can also install a standalone JTA imp= lementation and use it without EJB. Hibernate offers two strategies for JTA integration. = - If you use bean-managed transactions (BMT) Hibernate will = tell the application server to start - and end a BMT transaction if you use the Transact= ion API. So, the + If you use bean-managed transactions (BMT), Hibernate will= tell the application server to start + and end a BMT transaction if you use the Transact= ion API. The transaction management code is identical to the non-manage= d environment. = @@ -546,7 +543,7 @@ If you want to use a transaction-bound Session, that is, the getCurrentSession() functionality for ea= sy context propagation, - you will have to use the JTA UserTransaction API directly: + use the JTA UserTransaction API directly: = = - With CMT, transaction demarcation is done in session bean = deployment descriptors, not programmatically, - hence, the code is reduced to: + With CMT, transaction demarcation is completed in session = bean deployment descriptors, not programmatically. + The code is reduced to: = = - In a CMT/EJB even rollback happens automatically, since an= unhandled RuntimeException + In a CMT/EJB, even rollback happens automatically. An unha= ndled RuntimeException thrown by a session bean method tells the container to se= t the global transaction to rollback. - This means you do not need to use the Hibernate = Transaction API at + You do not need to use the Hibernate Tr= ansaction API at all with BMT or CMT, and you get automatic propagation of = the "current" Session bound to the transaction. = - Note that you should choose org.hibernate.transac= tion.JTATransactionFactory + When configuring Hibernate's transaction factory, choose <= literal>org.hibernate.transaction.JTATransactionFactory if you use JTA directly (BMT), and org.hibernate.= transaction.CMTTransactionFactory - in a CMT session bean, when you configure Hibernate's tran= saction factory. Remember to also set - hibernate.transaction.manager_lookup_class. Furthermore, make sure + in a CMT session bean. Remember to also set + hibernate.transaction.manager_lookup_class. Ensure that your hibernate.current_session_context_class= is either unset (backwards - compatibility), or set to "jta". + compatibility), or is set to "jta". = The getCurrentSession() operation has o= ne downside in a JTA environment. There is one caveat to the use of after_statement= connection release - mode, which is then used by default. Due to a silly limita= tion of the JTA spec, it is not + mode, which is then used by default. Due to a limitation o= f the JTA spec, it is not possible for Hibernate to automatically clean up any unclo= sed ScrollableResults or Iterator instances returned by scroll() or = iterate(). You must release the underlying database = cursor by calling ScrollableResults.close() or = Hibernate.close(Iterator) explicitly fr= om a finally = - block. (Of course, most applications can easily avoid usin= g scroll() or = - iterate() at all from the JTA or CMT co= de.) + block. Most applications can easily avoid using s= croll() or = + iterate() from the JTA or CMT code.) = @@ -615,8 +612,8 @@ Exception handling = - If the Session throws an exception (inc= luding any - SQLException), you should immediately r= ollback the database + If the Session throws an exception, inc= luding any + SQLException, immediately rollback the = database transaction, call Session.close() and d= iscard the Session instance. Certain methods of Session will not leave the session in a consi= stent state. No @@ -627,14 +624,14 @@ = The HibernateException, which wraps mos= t of the errors that - can occur in a Hibernate persistence layer, is an unchecke= d exception (it wasn't - in older versions of Hibernate). In our opinion, we should= n't force the application + can occur in a Hibernate persistence layer, is an unchecke= d exception. It was not + in older versions of Hibernate. In our opinion, we should = not force the application developer to catch an unrecoverable exception at a low lay= er. In most systems, unchecked and fatal exceptions are handled in one of the first frame= s of the method call - stack (i.e. in higher layers) and an error message is pres= ented to the application - user (or some other appropriate action is taken). Note tha= t Hibernate might also throw - other unchecked exceptions which are not a Hibern= ateException. These = - are, again, not recoverable and appropriate action should = be taken. + stack (i.e., in higher layers) and either an error message= is presented to the application + user or some other appropriate action is taken. Note that = Hibernate might also throw + other unchecked exceptions that are not a Hiberna= teException. These = + are not recoverable and appropriate action should be taken. = @@ -645,40 +642,40 @@ Hibernate converts the SQLException int= o an appropriate = JDBCException subclass using the SQLExceptionConverter = attached to the SessionFactory. By defa= ult, the = - SQLExceptionConverter is defined by the= configured dialect; however, it is - also possible to plug in a custom implementation (see the = javadocs for the - SQLExceptionConverterFactory class for = details). The standard = + SQLExceptionConverter is defined by the= configured dialect. However, it is + also possible to plug in a custom implementation. See the = javadocs for the + SQLExceptionConverterFactory class for = details. The standard = JDBCException subtypes are: = - JDBCConnectionException - indic= ates an error + JDBCConnectionException: indica= tes an error with the underlying JDBC communication. - SQLGrammarException - indicates= a grammar + SQLGrammarException: indicates = a grammar or syntax problem with the issued SQL. - ConstraintViolationException - = indicates some + ConstraintViolationException: i= ndicates some form of integrity constraint violation. - LockAcquisitionException - indi= cates an error + LockAcquisitionException: indic= ates an error acquiring a lock level necessary to perform the re= quested operation. - GenericJDBCException - a generi= c exception + GenericJDBCException: a generic= exception which did not fall into any of the other categorie= s. @@ -690,8 +687,8 @@ Transaction timeout = - One extremely important feature provided by a managed envi= ronment like EJB - that is never provided for non-managed code is transaction= timeout. Transaction + An important feature provided by a managed environment lik= e EJB, + that is never provided for non-managed code, is transactio= n timeout. Transaction timeouts ensure that no misbehaving transaction can indefi= nitely tie up = resources while returning no response to the user. Outside= a managed (JTA) environment, Hibernate cannot fully provide this functiona= lity. However, @@ -723,7 +720,7 @@ }]]> = - Note that setTimeout() may not be calle= d in a CMT bean, + setTimeout() cannot be called in a CMT = bean, where transaction timeouts must be defined declaratively. = @@ -736,11 +733,11 @@ = The only approach that is consistent with high concurrency and= high - scalability is optimistic concurrency control with versioning.= Version + scalability, is optimistic concurrency control with versioning= . Version checking uses version numbers, or timestamps, to detect confli= cting updates - (and to prevent lost updates). Hibernate provides for three po= ssible approaches + and to prevent lost updates. Hibernate provides three possible= approaches to writing application code that uses optimistic concurrency. = The use cases - we show are in the context of long conversations, but version = checking + we discuss are in the context of long conversations, but versi= on checking also has the benefit of preventing lost updates in single data= base transactions. = @@ -751,7 +748,7 @@ In an implementation without much help from Hibernate, eac= h interaction with the database occurs in a new Session and th= e developer is responsible for reloading all persistent instances from the database b= efore manipulating them. - This approach forces the application to carry out its own = version checking to ensure + The application is forced to carry out its own version che= cking to ensure conversation transaction isolation. This approach is the l= east efficient in terms of database access. It is the approach most similar to entity= EJBs. @@ -775,18 +772,18 @@ = - Of course, if you are operating in a low-data-concurrency = environment and don't - require version checking, you may use this approach and ju= st skip the version - check. In that case, last commit wins= will be the default - strategy for your long conversations. Keep in mind that th= is might + If you are operating in a low-data-concurrency environment= , and do not + require version checking, you can use this approach and sk= ip 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 experi= ence lost updates without error messages or a chance to merge conflicting changes. = - Clearly, manual version checking is only feasible in very = trivial circumstances + Manual version checking is only feasible in trivial circum= stances and not practical for most applications. Often not only si= ngle instances, but - complete graphs of modified objects have to be checked. Hi= bernate offers automatic + complete graphs of modified objects, have to be checked. H= ibernate offers automatic version checking with either an extended Session<= /literal> or detached instances as the design paradigm. @@ -797,19 +794,19 @@ Extended session and automatic versioning = - A single Session instance and its persi= stent instances are - used for the whole conversation, known as sessio= n-per-conversation. + A single Session instance and its persi= stent instances that are + used for the whole conversation are known as ses= sion-per-conversation. Hibernate checks instance versions at flush time, throwing= an exception if concurrent - modification is detected. It's up to the developer to catc= h and handle this exception - (common options are the opportunity for the user to merge = changes or to restart the - business conversation with non-stale data). + modification is detected. It is up to the developer to cat= ch and handle this exception. = + Common options are the opportunity for the user to merge c= hanges or to restart the + business conversation with non-stale data. = The Session is disconnected from any un= derlying JDBC connection when waiting for user interaction. This approach is the mo= st efficient in terms - of database access. The application need not concern itsel= f with version checking or - with reattaching detached instances, nor does it have to r= eload instances in every + of database access. The application does not version check= or + reattach detached instances, nor does it have to reload in= stances in every database transaction. = @@ -822,41 +819,43 @@ t.commit(); // Also return JDBC connection session.close(); // Only for last transaction in conversation]]> - The foo object still knows which Session it was + The foo object knows which Ses= sion it was loaded in. Beginning a new database transaction on an old = session obtains a new connection and resumes the session. Committing a database transaction= disconnects a session from the JDBC connection and returns the connection to the= pool. After reconnection, to - force a version check on data you aren't updating, you ma= y call Session.lock() + force a version check on data you are not updating, you ca= n call Session.lock() with LockMode.READ on any objects that = might have been updated by another - transaction. You don't need to lock any data that you are updating. + transaction. You do not need to lock any data that you are updating. Usually you would set FlushMode.MANUAL = on an extended Session, so that only the last database transaction cycle is allowe= d to actually persist all - modifications made in this conversation. Hence, only this = last database transaction - would include the flush() operation, an= d then also + modifications made in this conversation. Only this last da= tabase transaction + will include the flush() operation, and= then close() the session to end the conversa= tion. = This pattern is problematic if the Session is too big to - be stored during user think time, e.g. an HttpSes= sion should - be kept as small as possible. As the Session is also the - (mandatory) first-level cache and contains all loaded obje= cts, we can probably - use this strategy only for a few request/response cycles. = You should use a - Session only for a single conversation,= as it will soon also + be stored during user think time (for example, an HttpSession should + be kept as small as possible). As the Session 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 + Session only for a single conversation = as it will soon have stale data. = - - (Note that earlier Hibernate versions required explicit di= sconnection and reconnection + + Note + Earlier versions of Hibernate required explicit disconnection an= d reconnection of a Session. These methods are depreca= ted, as beginning and - ending a transaction has the same effect.) - + ending a transaction has the same effect. + + = - Also note that you should keep the disconnected S= ession close - to the persistence layer. In other words, use an EJB state= ful session bean to - hold the Session in a three-tier enviro= nment, and don't transfer - it to the web layer (or even serialize it to a separate ti= er) to store it in the + Keep the disconnected Session close + to the persistence layer. Use an EJB stateful session bean= to + hold the Session in a three-tier enviro= nment. Do not transfer + it to the web layer, or even serialize it to a separate ti= er, to store it in the HttpSession. = @@ -864,7 +863,7 @@ The extended session pattern, or session-per-con= versation, is more difficult to implement with automatic current session= context management. You need to supply your own implementation of the CurrentSessionContext - for this, see the Hibernate Wiki for examples. + for this. See the Hibernate Wiki for examples.
= @@ -894,8 +893,8 @@
= - You may also call lock() instead of update() - and use LockMode.READ (performing a ver= sion check, bypassing all + You can also call lock() instead of update(), + and use LockMode.READ (performing a ver= sion check and bypassing all caches) if you are sure that the object has not been modif= ied. = @@ -905,40 +904,41 @@ Customizing automatic versioning = - You may disable Hibernate's automatic version increment fo= r particular properties and = + You can disable Hibernate's automatic version increment fo= r particular properties and = collections by setting the optimistic-lock mapping attribute to = false. Hibernate will then no longer in= crement versions if the = property is dirty. = - Legacy database schemas are often static and can't be modi= fied. Or, other applications - might also access the same database and don't know how to = handle version numbers or - even timestamps. In both cases, versioning can't rely on a= particular column in a table. - To force a version check without a version or timestamp pr= operty mapping, with a - comparison of the state of all fields in a row, turn on optimistic-lock=3D"all" - in the <class> mapping. Note that= this conceptually only works - if Hibernate can compare the old and new state, i.e. if yo= u use a single long - Session and not session-per-request-wit= h-detached-objects. + Legacy database schemas are often static and cannot be mod= ified. Or, other applications + might access the same database and will not know how to ha= ndle version numbers or + even timestamps. In both cases, versioning cannot rely on = a particular column in a table. + To force a version check with a + comparison of the state of all fields in a row but without= a version or timestamp property mapping, = + turn on optimistic-lock=3D"all" + in the <class> mapping. This conc= eptually only works + if Hibernate can compare the old and the new state (i.e., = if you use a single long + Session and not session-per-request-wit= h-detached-objects). = - Sometimes concurrent modification can be permitted as long= as the changes that have been - made don't overlap. If you set optimistic-lock=3D= "dirty" when mapping the + Concurrent modification can be permitted in instances wher= e the changes that have been + made do not overlap. If you set optimistic-lock= =3D"dirty" when mapping the <class>, Hibernate will only comp= are dirty fields during flush. = - In both cases, with dedicated version/timestamp columns or= with full/dirty field - comparison, Hibernate uses a single UPDATE statement (with an - appropriate WHERE clause) per entity to= execute the version check + In both cases, with dedicated version/timestamp columns or= with a full/dirty field + comparison, Hibernate uses a single UPDATE statement, with an + appropriate WHERE clause, per entity to= execute the version check and update the information. If you use transitive persiste= nce to cascade reattachment - to associated entities, Hibernate might execute unnecessar= y updates. This is usually + to associated entities, Hibernate may execute unnecessary = updates. This is usually not a problem, but on update triggers= in the database might be executed even when no changes have been made to detached i= nstances. You can customize this behavior by setting select-before-update=3D= "true" in the <class> mapping, forcing Hibernat= e to SELECT - the instance to ensure that changes did actually occur, be= fore updating the row. + the instance to ensure that changes did occur before updat= ing the row. = @@ -946,22 +946,22 @@ = - Pessimistic Locking + Pessimistic locking = - It is not intended that users spend much time worrying about l= ocking strategies. It's usually + It is not intended that users spend much time worrying about l= ocking strategies. It is usually enough to specify an isolation level for the JDBC connections = and then simply let the - database do all the work. However, advanced users may sometime= s wish to obtain - exclusive pessimistic locks, or re-obtain locks at the start o= f a new transaction. + database do all the work. However, advanced users may wish to = obtain + exclusive pessimistic locks or re-obtain locks at the start of= a new transaction. = - Hibernate will always use the locking mechanism of the databas= e, never lock objects - in memory! + Hibernate will always use the locking mechanism of the databas= e; it never lock objects + in memory. = - The LockMode class defines the different lo= ck levels that may be acquired + The LockMode class defines the different lo= ck levels that can be acquired by Hibernate. A lock is obtained by the following mechanisms: = @@ -974,20 +974,20 @@ - LockMode.UPGRADE may be acquired up= on explicit user request using + LockMode.UPGRADE can be acquired up= on explicit user request using SELECT ... FOR UPDATE on databases = which support that syntax. - LockMode.UPGRADE_NOWAIT may be acqu= ired upon explicit user request using a + LockMode.UPGRADE_NOWAIT can be acqu= ired upon explicit user request using a SELECT ... FOR UPDATE NOWAIT under = Oracle. LockMode.READ is acquired automatic= ally when Hibernate reads data - under Repeatable Read or Serializable isolation level.= May be re-acquired by explicit user + under Repeatable Read or Serializable isolation level.= It can be re-acquired by explicit user request. @@ -1035,29 +1035,29 @@ Session.lock() performs a version number ch= eck if the specified lock mode is READ, UPGRADE or - UPGRADE_NOWAIT. (In the case of UP= GRADE or - UPGRADE_NOWAIT, SELECT ... FOR UPD= ATE is used.) + UPGRADE_NOWAIT. In the case of UPG= RADE or + UPGRADE_NOWAIT, SELECT ... FOR UPD= ATE is used. = - If the database does not support the requested lock mode, Hibe= rnate will use an appropriate - alternate mode (instead of throwing an exception). This ensure= s that applications will - be portable. + If the requested lock mode is not supported by the database, H= ibernate uses an appropriate + alternate mode instead of throwing an exception. This ensures = that applications are + portable. = = - Connection Release Modes + Connection release modes = - The legacy (2.x) behavior of Hibernate in regards to JDBC conn= ection management - was that a Session would obtain a connectio= n when it was first - needed and then hold unto that connection until the session wa= s closed. - Hibernate 3.x introduced the notion of connection release mode= s to tell a session - how to handle its JDBC connections. Note that the following d= iscussion is pertinent - only to connections provided through a configured Con= nectionProvider; - user-supplied connections are outside the breadth of this disc= ussion. The different + One of the legacies of Hibernate 2.x JDBC connection managemen= t = + meant that a Session would obtain a connect= ion when it was first + required and then maintain that connection until the session w= as closed. + Hibernate 3.x introduced the notion of connection release mode= s that would instruct a session + how to handle its JDBC connections. The following discussion = is pertinent + only to connections provided through a configured Con= nectionProvider. + User-supplied connections are outside the breadth of this disc= ussion. The different release modes are identified by the enumerated values of org.hibernate.ConnectionReleaseMode: @@ -1065,23 +1065,23 @@ - ON_CLOSE - is essentially the legac= y behavior described above. The + ON_CLOSE: is the legacy behavior de= scribed above. The Hibernate session obtains a connection when it first n= eeds to perform some JDBC access - and holds unto that connection until the session is cl= osed. + and maintains that connection until the session is clo= sed. - AFTER_TRANSACTION - says to release= connections after a - org.hibernate.Transaction has compl= eted. + AFTER_TRANSACTION: releases connect= ions after a + org.hibernate.Transaction has been = completed. - AFTER_STATEMENT (also referred to a= s aggressive release) - says to - release connections after each and every statement exe= cution. This aggressive releasing - is skipped if that statement leaves open resources ass= ociated with the given session; - currently the only situation where this occurs is thro= ugh the use of + AFTER_STATEMENT (also referred to a= s aggressive release): + releases connections after every statement execution. = This aggressive releasing + is skipped if that statement leaves open resources ass= ociated with the given session. + Currently the only situation where this occurs is thro= ugh the use of org.hibernate.ScrollableResults. @@ -1089,43 +1089,43 @@ = The configuration parameter hibernate.connection.rele= ase_mode is used - to specify which release mode to use. The possible values: + to specify which release mode to use. The possible values are= as follows: = - auto (the default) - this choice de= legates to the release mode + auto (the default): this choice del= egates to the release mode returned by the org.hibernate.transaction.Tra= nsactionFactory.getDefaultReleaseMode() method. For JTATransactionFactory, this returns Conne= ctionReleaseMode.AFTER_STATEMENT; for - JDBCTransactionFactory, this returns ConnectionRelease= Mode.AFTER_TRANSACTION. It is rarely - a good idea to change this default behavior as failure= s due to the value of this setting + JDBCTransactionFactory, this returns ConnectionRelease= Mode.AFTER_TRANSACTION. Do not + change this default behavior as failures due to the va= lue of this setting tend to indicate bugs and/or invalid assumptions in us= er code. - on_close - says to use ConnectionRe= leaseMode.ON_CLOSE. This setting - is left for backwards compatibility, but its use is hi= ghly discouraged. + on_close: uses ConnectionReleaseMod= e.ON_CLOSE. This setting + is left for backwards compatibility, but its use is di= scouraged. - after_transaction - says to use Con= nectionReleaseMode.AFTER_TRANSACTION. + after_transaction: uses ConnectionR= eleaseMode.AFTER_TRANSACTION. This setting should not be 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 mo= de were AFTER_STATEMENT. + mode, connections will be released as if the release m= ode were AFTER_STATEMENT. - after_statement - says to use Conne= ctionReleaseMode.AFTER_STATEMENT. Additionally, + after_statement: uses ConnectionRel= easeMode.AFTER_STATEMENT. Additionally, the configured ConnectionProvider i= s consulted to see if it supports this setting (supportsAggressiveRelease()). If not, the release mode is reset to ConnectionReleaseMode.AFTER_TRANSACTION. This sett= ing is only safe in environments where - we can either re-acquire the same underlying JDBC conn= ection each time we make a call into + we can either re-acquire the same underlying JDBC conn= ection each time you make a call into ConnectionProvider.getConnection() = or in auto-commit environments where - it does not matter whether we get back the same connec= tion. + it does not matter if we re-establish the same connect= ion. Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/tutorial.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/tutorial.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/tutorial.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -27,7 +27,7 @@ ]> = - + = Introduction to Hibernate @@ -36,11 +36,10 @@ Preface = - This chapter is an introduction to Hibernate by way of a tutor= ial, - intended for new users of Hibernate. We start with a simple - application using an in-memory database. We build the - application in small, easy to understand steps. The tutorial = is - based on another, earlier one developed by Michael Gloegl. All + Intended for new users, this chapter provides an introduction = to Hibernate + The chapter provides a step-by-step tutorial, starting with a simple + application using an in-memory database. The tutorial is + based on an earlier tutorial developed by Michael Gloegl. All code is contained in the tutorials/web di= rectory of the project source. @@ -50,10 +49,9 @@ This tutorial expects the user have knowledge of both Java and - SQL. If you are new or uncomfortable with either, it is advis= ed + SQL. If you have a limited knowledge of JAVA or SQL, it is ad= vised that you start with a good introduction to that technology pri= or - to attempting to learn Hibernate. It will save time and effort - in the long run. + to attempting to learn Hibernate. = @@ -61,7 +59,7 @@ There is another tutorial/example application in the /tutorials/eg directory of the project so= urce. - That example is console based and as such would not have the + That example is console-based and, as such, would not have the dependency on a servlet container to execute. The basic setup= is the same as the instructions below. @@ -71,22 +69,21 @@ Part 1 - The first Hibernate Application = - Let's assume we need a small database application that can sto= re + For this example, we will set up a small database application = that can store events we want to attend, and information about the host(s) of - these events. We will use an in-memory, Java database named H= SQLDB + these events. Although you can use whatever database you feel= comfortable using, we will use an in-memory, Java database named HSQLDB to avoid describing installation/setup of any particular datab= ase - servers. Feel free to tweak this tutorial to use whatever dat= abase - you feel comfortable using. + servers. = = - The first thing we need to do is set up our development enviro= nment, - and specifically to setup all the required dependencies to Hib= ernate - as well as other libraries. Hibernate is built using Maven wh= ich = - amongst other features provides dependecy management<= /literal>; + The first thing we need to do is set up the development enviro= nment, + including all the required dependencies to Hibernate, + as well as other libraries. Hibernate is built using Maven wh= ich, = + amongst other features, provides dependency managemen= t; moreover it provides transitive - dependecy management which simply means tha= t to use - Hibernate we can simply define our dependency on Hibernate, Hi= bernate + dependency management, which simply means t= hat by using + Hibernate we can define our dependency on Hibernate. Hibernate itself defines the dependencies it needs which then become tra= nsitive dependencies of our project. @@ -124,20 +121,19 @@ While not strictly necessary, most IDEs have integration w= ith Maven - to read these POM files and automatically set up a project= for you - which can save lots of time and effort. + to read these POM files and automatically set up a project= for you. = - Next we create a class that represents the event we want to st= ore in database. + Next, create a class that represents the event you want to sto= re in the database. = The first class = - Our first persistent class is a simple JavaBean class with= some properties: + The first persistent class is a simple JavaBean class with= some properties: = = - You can see that this class uses standard JavaBean naming = conventions for property - getter and setter methods, as well as private visibility f= or the fields. This is - a recommended design - but not required. Hibernate can als= o access fields directly, + This class uses standard JavaBean naming conventions for p= roperty + getter and setter methods, as well as private visibility f= or the fields. Although this is + a recommended design, it is not required. Hibernate can al= so access fields directly, the benefit of accessor methods is robustness for refactor= ing. The no-argument constructor is required to instantiate an object of this c= lass through reflection. @@ -189,11 +185,11 @@ The id property holds a unique identifi= er value for a particular event. All persistent entity classes (there are less important de= pendent classes as well) will need such an identifier property if we want to use the full fea= ture set of Hibernate. In fact, - most applications (esp. web applications) need to distingu= ish objects by identifier, so you - should consider this a feature rather than a limitation. H= owever, we usually don't manipulate + most applications, especially web applications, need to di= stinguish objects by identifier, so you + should consider this a feature rather than a limitation. H= owever, 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. You can see that Hibe= rnate can access public, private, - and protected accessor methods, as well as (public, privat= e, protected) fields directly. The + 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 appli= cation design. = @@ -205,7 +201,7 @@ = - Place this Java source file in a directory called src in the + Place the Java source file in a directory called = src in the development folder, and in its correct package. The direct= ory should now look like this: = @@ -246,26 +242,26 @@ ]]> = - Note that the Hibernate DTD is very sophisticated. You can= use it for + Hibernate DTD is sophisticated. You can use it for auto-completion of XML mapping elements and attributes in = your editor or - IDE. You also should open up the DTD file in your text edi= tor - it's the - easiest way to get an overview of all elements and attribu= tes and to see - the defaults, as well as some comments. Note that Hibernat= e will not + IDE. Opening up the DTD file in your text editor is the + easiest way to get an overview of all elements and attribu= tes, 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= ibernate3.jar as well as in the src/ directory of the= Hibernate distribution. = - We will omit the DTD declaration in future examples to sho= rten the code. It is - of course not optional. + We will omit the DTD declaration in future examples to sho= rten the code. It is, + of course, not optional. = Between the two hibernate-mapping tags,= include a class element. All persistent entity cl= asses (again, there might be dependent classes later on, which are not first-c= lass entities) need - such a mapping, to a table in the SQL database: + a mapping to a table in the SQL database: = @@ -277,10 +273,10 @@ ]]> = - So far we told Hibernate how to persist and load object of= class Event - to the table EVENTS, each instance repr= esented by a row in that table. - Now we continue with a mapping of the unique identifier pr= operty to the tables primary key. - In addition, as we don't want to care about handling this = identifier, we configure Hibernate's + So far we have told Hibernate how to persist and load obje= ct of class Event + to the table EVENTS. Each instance is n= ow represented by a row in that table. + Now we can continue by mapping the unique identifier prope= rty 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: = @@ -296,19 +292,20 @@ = The id element is the declaration of th= e identifier property, - name=3D"id" declares the name of the Ja= va property - + name=3D"id" declares the name of the Ja= va property. Hibernate will use the getter and setter methods to access= the property. The column attribute tells Hibernate which column of the - EVENTS table we use for this primary ke= y. The nested - generator element specifies the identif= ier generation strategy, - in this case we used native, which pick= s the best strategy depending - on the configured database (dialect). Hibernate supports d= atabase generated, globally - unique, as well as application assigned identifiers (or an= y strategy you have written - an extension for). + EVENTS table to use for this primary ke= y. The nested + generator element specifies the identif= ier generation strategy. + = + In this case you used native, which selects the best = strategy depending + on the configured database dialect. Hibernate supports dat= abase generated, globally + unique, as well as application assigned, identifiers. Hibe= rnate supports any strategy you have written + an extension for. = - Finally we include declarations for the persistent propert= ies of the class in + Finally, include declarations for the persistent propertie= s of the class in the mapping file. By default, no properties of the class a= re considered persistent: @@ -327,42 +324,42 @@ ]]> = - Just as with the id element, the name + Similar to the id element, the name attribute of the property element tells= Hibernate which getter - and setter methods to use. So, in this case, Hibernate wil= l look for + and setter methods to use. In this case, Hibernate will s= earch for getDate()/setDate(), as well as getTitle()/setTitle(). = Why does the date property mapping incl= ude the column attribute, but the titl= e - doesn't? Without the column attribute H= ibernate - by default uses the property name as the column name. This= works fine for - title. However, date= is a reserved - keyword in most database, so we better map it to a differe= nt name. + does not? Without the column attribute,= Hibernate + by default uses the property name as the column name. This= works for + title, however, date= is a reserved + keyword in most databases so you will need to map it to a = different name. = - The next interesting thing is that the title mapping also lacks - a type attribute. The types we declare = and use in the mapping + The title mapping also lacks + a type attribute. The types declared an= d used in the mapping files are not, as you might expect, Java data types. They = are also not SQL - database types. These types are so called Hibern= ate mapping types, + database types. 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 type attribute is not present in th= e mapping. In some cases this - automatic detection (using Reflection on the Java class) m= ight not have the default you - expect or need. This is the case with the date property. Hibernate can't - know if the property (which is of java.util.Date<= /literal>) should map to a + automatic detection using Reflection on the Java class mig= ht not have the default you + expect or need. This is the case with the date property. Hibernate cannot + know if the property, which is of java.util.Date<= /literal>, should map to a SQL date, timestamp,= or time column. - We preserve full date and time information by mapping the = property with a + Full date and time information is preserved by mapping the= property with a timestamp converter. = - This mapping file should be saved as Event.hbm.xm= l, right in + Save the mapping file as Event.hbm.xml = in the directory next to the Event Java cl= ass source file. - The naming of mapping files can be arbitrary, however the = hbm.xml - suffix is a convention in the Hibernate developer communi= ty. The directory structure + The naming of mapping files can be arbitrary, however, the= hbm.xml + suffix is a convention in the Hibernate developer communit= y. The directory structure should now look like this: = @@ -375,7 +372,7 @@ Event.hbm.xml]]> = - We continue with the main configuration of Hibernate. + The next section continues with the main configuration of= Hibernate. = @@ -384,36 +381,36 @@ Hibernate configuration = - We now have a persistent class and its mapping file in pla= ce. It is time to configure - Hibernate. Before we do this, we will need a database. HSQ= L DB, a java-based SQL DBMS, - can be downloaded from the HSQL DB website(http://hsqldb.o= rg/). Actually, you only need the hsqldb.jar + You should have a persistent class and its mapping file in= place. It is now time to configure + Hibernate. Before you do this, you will need a database. H= SQL DB, a java-based SQL DBMS, + can be downloaded from the HSQL DB website(http://hsqldb.o= rg/). You only need the hsqldb.jar from this download. Place this file in the lib/ directory of the development folder. = - Create a directory called data in the r= oot of the development directory - - this is where HSQL DB will store its data files. Now start= the database by running + Create a directory called data in the r= oot of the development directory. + This is where HSQL DB will store its data files. Start the= database by running java -classpath ../lib/hsqldb.jar org.hsqldb.Serv= er in this data directory. - You can see it start up and bind to a TCP/IP socket, this = is where our application + 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 data= base during this tutorial, shutdown HSQL DB (press CTRL + C in the= window), delete all files in the data/ directory, and start HSQL DB agai= n. = - Hibernate is the layer in your application which connects = to this database, so it needs - connection information. The connections are made through a= JDBC connection pool, which we - also have to configure. The Hibernate distribution contain= s several open source JDBC connection - pooling tools, but will use the Hibernate built-in connect= ion pool for this tutorial. Note that - you have to copy the required library into your classpath = and use different + Hibernate is the layer in your application that connects t= o this database, so it needs + connection information. The connections are made through a= JDBC connection pool, which you + will also have to configure. The Hibernate distribution con= tains several open source JDBC connection + pooling tools, but you will use the Hibernate built-in con= nection pool for this tutorial. + You will have to copy the required library into your class= path and use different connection pooling settings if you want to use a productio= n-quality third party JDBC pooling software. = For Hibernate's configuration, we can use a simple hibernate.properties file, a - slightly more sophisticated hibernate.cfg.xml file, or even complete + more sophisticated hibernate.cfg.xml fi= le, or even complete programmatic setup. Most users prefer the XML configuratio= n file: = @@ -457,30 +454,30 @@ ]]> = - Note that this XML configuration uses a different DTD. We = configure - Hibernate's SessionFactory - a global f= actory responsible - for a particular database. If you have several databases, = use several - <session-factory> configurations,= usually in - several configuration files (for easier startup). + This XML configuration uses a different DTD. You configure + Hibernate's SessionFactory. SessionFact= ory is a global factory responsible + for a particular database. If you have several databases, = for easier startup you should use several + <session-factory> configurations = in + several configuration files. = The first four property elements contai= n the necessary configuration for the JDBC connection. The dialect property element specifies the particular SQL variant Hibernate gen= erates. - Hibernate's automatic session management for persistence c= ontexts will - come in handy as you will soon see. + Hibernate's automatic session management for persistence c= ontexts is particularly useful in this context. + The hbm2ddl.auto option turns on automa= tic generation of - database schemas - directly into the database. This can of= course also be turned - off (by removing the config option) or redirected to a fil= e with the help of - the SchemaExport Ant task. Finally, we = add the mapping file(s) + 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 SchemaExport Ant task. Finally, add= the mapping file(s) for persistent classes to the configuration. = - Copy this file into the source directory, so it will end u= p in the - root of the classpath. Hibernate automatically looks for a= file called - hibernate.cfg.xml in the root of the cl= asspath, on startup. + Copy the file into the source directory, so it will end up= in the + root of the classpath. On startup, Hibernate automatically= searches for a file called + hibernate.cfg.xml in the root of the cl= asspath. = @@ -489,11 +486,11 @@ Building with Ant = - We'll now build the tutorial with Ant. You will need to ha= ve Ant installed - get - it from the Ant download page. - How to install Ant will not be covered here. Please refer = to the - Ant= manual. After you - have installed Ant, we can start to create the buildfile. = It will be called + We will now build the tutorial with Ant. You will need to = have Ant installed. + It is available from the Ant download page. + Installation instructions for Ant, however, are not be cov= ered here. Please refer to the + Ant= manual for further information. After you + have installed Ant, you can start to create the buildfile.= It will be called build.xml and placed directly in the de= velopment directory. = @@ -535,10 +532,10 @@ ]]> = - This will tell Ant to add all files in the lib directory e= nding with .jar + This will tell Ant to add all files in the library directo= ry ending with .jar to the classpath used for compilation. It will also copy a= ll non-Java source files to the - target directory, e.g. configuration and Hibernate mapping= files. If you now run Ant, you - should get this output: + target directory, configuration and Hibernate mapping file= s, for example. If you now run Ant, you + will get this output: = ant @@ -559,19 +556,19 @@ Startup and helpers = - It's time to load and store some Event = objects, but first - we have to complete the setup with some infrastructure cod= e. We have to startup - Hibernate. This startup includes building a global SessionFactory - object and to store it somewhere for easy access in applic= ation code. - A SessionFactory can open up new Session's. - A Session represents a single-threaded = unit of work, the - SessionFactory is a thread-safe global = object, instantiated once. + It is time to load and store some Event= objects, but first + you have to complete the setup with some infrastructure co= de. You have to startup + Hibernate by building a global SessionFactory + object and storing it somewhere for easy access in applica= tion code. + A SessionFactory can open up new Sessions. + A Session represents a single-threaded = unit of work. The + SessionFactory is a thread-safe global = object, that is instantiated once. = - We'll create a HibernateUtil helper cla= ss which takes care + Create a HibernateUtil helper class tha= t takes care of startup and makes accessing a SessionFactory convenient. - Let's have a look at the implementation: + The following example illustrates the implementation: = = - This class does not only produce the global Sessi= onFactory in - its static initializer (called once by the JVM when the cl= ass is loaded), but also + This class not only produces the global SessionFa= ctory in + its static initializer that is called once by the JVM when= the class is loaded. It also hides the fact that it uses a static singleton. It might a= s well lookup the SessionFactory from JNDI in an applicat= ion server. = If you give the SessionFactory a name i= n your configuration - file, Hibernate will in fact try to bind it to JNDI after = it has been built. + file, Hibernate will try to bind it to JNDI after it has b= een built. To avoid this code completely you could also use JMX deplo= yment and let the JMX-capable container instantiate and bind a Hibe= rnateService to JNDI. These advanced options are discussed in the Hiber= nate reference @@ -617,7 +614,7 @@ = - Place HibernateUtil.java in the develop= ment source directory, in + Place HibernateUtil.java in the develop= ment source directory in a package next to events: = @@ -635,17 +632,17 @@ build.xml]]> = - This should again compile without problems. We finally nee= d to configure a logging - system - Hibernate uses commons logging and leaves you the= choice between Log4j and + You now need to configure a logging + system. Hibernate uses commons logging and provides two c= hoices: Log4j and JDK 1.4 logging. Most developers prefer Log4j: copy log4j.properties - from the Hibernate distribution (it's in the etc/= directory) to + from the Hibernate distribution in the etc/ directory to your src directory, next to hi= bernate.cfg.xml. - Have a look at the example configuration and change the se= ttings if you like to have - more verbose output. By default, only Hibernate startup me= ssage are shown on stdout. + If you prefer to have + more verbose output than that provided in the example conf= iguration, you can change the settings. By default, only the Hibernate sta= rtup message is shown on stdout. = - The tutorial infrastructure is complete - and we are ready= to do some real work with + The tutorial infrastructure is complete and you are now re= ady to do some real work with Hibernate. = @@ -655,7 +652,7 @@ Loading and storing objects = - Finally, we can use Hibernate to load and store objects. W= e write an + You can use Hibernate to load and store objects. Write an EventManager class with a main= () method: = @@ -696,40 +693,40 @@ }]]> = - We create a new Event object, and hand = it over to Hibernate. - Hibernate now takes care of the SQL and executes = INSERTs - on the database. Let's have a look at the Session= and + You can create a new Event object and h= and it over to Hibernate. + Hibernate takes care of the SQL and executes INSE= RT + on the database. We will explain the Session and Transaction-handling code before we run= this. = - A Session is a single unit of work. For= now we'll keep things + A Session is a single unit of work. For= now we will keep things simple and assume a one-to-one granularity between a Hiber= nate Session and a database transaction. To shield our code from the ac= tual underlying transaction - system (in this case plain JDBC, but it could also run wit= h JTA) we use the - Transaction API that is available on th= e Hibernate Session. + system we use the + Transaction API that is available on th= e Hibernate Session. = + In this case plain JDBC, but it could also run with JTA. = What does sessionFactory.getCurrentSession() do? First, you can call it - as many times and anywhere you like, once you get hold of = your SessionFactory - (easy thanks to HibernateUtil). The getCurrentSession() + as many times and anywhere you like, once you get hold of = your SessionFactory. + This is easy thanks to HibernateUtil). = The getCurrentSession() method always returns the "current" unit of work. Remember= that we switched the configuration - option for this mechanism to "thread" in hibernat= e.cfg.xml? Hence, - the current unit of work is bound to the current Java thre= ad that executes our application. - However, this is not the full picture, you also have to co= nsider scope, when a unit of work + option for this mechanism to "thread" in hibernat= e.cfg.xml? The current unit of work is bound to the current Java = thread that executes the application. + However, you also have to consider when a unit of work begins and when it ends. = - A Session begins when it is first neede= d, when the first call to + A Session begins when the first call to getCurrentSession() is made. It is then= bound by Hibernate to the current thread. When the transaction ends, either through commit o= r rollback, Hibernate automatically unbinds the Session from the thread and= closes it for you. If you call getCurrentSession() again, you get a ne= w Session and can start a new unit of work. This thread-bound programming model is the most - popular way of using Hibernate, as it allows flexible laye= ring of your code (transaction - demarcation code can be separated from data access code, w= e'll do this later in this tutorial). + popular way of using Hibernate, as it allows flexible laye= ring of your code. Transaction + demarcation code can be separated from data access code. T= his will be covered later in this tutorial. = @@ -738,15 +735,15 @@ for one operation. This is pure coincidence, the example i= s just not complex enough to show any other approach. The scope of a Hibernate Session<= /literal> is flexible but you should never design your application to use a new Hibernate Session for - every database operation. So even if = you see it a few more times in - the following (very trivial) examples, consider = session-per-operation - an anti-pattern. A real (web) application is shown later i= n this tutorial. + every database operation. Even though= it is used in + the following examples, consider session-per-ope= ration + an anti-pattern. A real web application is shown later in = the tutorial. = - Have a look at for more i= nformation - about transaction handling and demarcation. We also skippe= d any error handling and - rollback in the previous example. + See for more information + about transaction handling and demarcation. The previous e= xample also skipped any error handling and + rollback. = @@ -768,20 +765,20 @@ ant run -Dactio= n=3Dstore]]> = - You should see, after compilation, Hibernate starting up a= nd, depending on your - configuration, lots of log output. At the end you will fin= d the following line: + After compilation, you should see Hibernate starting up an= d, depending on your + configuration, lots of log output. At the end, the followi= ng line will be displayed: = = - This is the INSERT executed by Hibernat= e, the question marks - represent JDBC bind parameters. To see the values bound as= arguments, or to reduce + This is the INSERT executed by Hibernat= e. The question marks + represent JDBC bind parameters. To view the values bound a= s arguments, or to reduce the verbosity of the log, check your log4j.proper= ties. = - Now we'd like to list stored events as well, so we add an = option to the main method: + To list stored events an option is added to the main metho= d: = = - We also add a new listEvents() method: + A new listEvents() method is also added: = = - What we do here is use an HQL (Hibernate Query Language) q= uery to load all existing + Use an HQL (Hibernate Query Language) query to load all ex= isting Event objects from the database. Hibern= ate will generate the appropriate SQL, send it to the database and populate Event objects - with the data. You can create more complex queries with HQ= L, of course. + with the data. You can create more complex queries with HQ= L. = - Now, to execute and test all of this, follow these steps: + To execute and test all of this, follow these steps: = - Run ant run -Daction=3Dstore to= store something into the database + Run ant run -Daction=3Dstore to= store something in the database and, of course, to generate the database schema be= fore through hbm2ddl. - Now disable hbm2ddl by commenting out the property= in your hibernate.cfg.xml - file. Usually you only leave it turned on in conti= nuous unit testing, but another - run of hbm2ddl would drop eve= rything you have stored - the - create configuration setting ac= tually translates into "drop all - tables from the schema, then re-create all tables,= when the SessionFactory is build". + Disable hbm2ddl by commenting out the property in = your hibernate.cfg.xml + file. It is only turned on in continuous unit test= ing. Another + run of hbm2ddl would drop eve= rything you have stored. The + create configuration setting tr= anslates into "drop all + tables from the schema, then re-create all tables,= when the SessionFactory is built". = - If you now call Ant with -Daction=3Dlist, you should see the events - you have stored so far. You can of course also call the store action a few - times more. + If you can call Ant with -Daction=3Dlist, you will be able to view the events + you have stored so far. You can also call the sto= re action. = - Note: Most new Hibernate users fail at this point and we s= ee questions about - Table not found error messages regula= rly. However, if you follow the + Most new Hibernate users fail at this point and we regular= ly receive questions relating to + Table not found error messages. Howev= er, if you follow the steps outlined above you will not have this problem, as hb= m2ddl creates the database schema on the first run, and subsequent application restar= ts will use this schema. If - you change the mapping and/or database schema, you have to= re-enable hbm2ddl once again. + you change the mapping and/or database schema, you will ha= ve to re-enable hbm2ddl. = @@ -864,15 +860,15 @@ Part 2 - Mapping associations = - We mapped a persistent entity class to a table. Let's build on= this and add some class associations. - First we'll add people to our application, and store a list of= events they participate in. + You have mapped a persistent entity class to a table. You can = now build on this by adding some class associations. + First you will add people to your application, and store a lis= t of events they participate in. = Mapping the Person class = - The first cut of the Person class is si= mple: + The first cut of the Person class looks= like this: = = - Create a new mapping file called Person.hbm.xml (don't forget the - DTD reference at the top): + Create a new mapping file called Person.hbm.xml. Do not forget the + DTD reference at the top: = @@ -916,9 +912,9 @@ ]]> = - We'll now create an association between these two entities= . Obviously, persons + Create an association between these two entities. Persons can participate in events, and events have participants. T= he design questions - we have to deal with are: directionality, multiplicity, an= d collection + you have to deal with are: directionality, multiplicity, a= nd collection behavior. = @@ -928,15 +924,15 @@ A unidirectional Set-based association = - We'll add a collection of events to the Person class. That way we can + By adding a collection of events to the Person class, you can easily navigate to the events for a particular person, wit= hout executing an explicit query - - by calling aPerson.getEvents(). We use = a Java collection, a Set, - because the collection will not contain duplicate elements= and the ordering is not relevant for us. + by calling aPerson.getEvents(). A Java = collection, a Set, is used + because the collection will not contain duplicate elements= and the ordering is not relevant to our examples. = - We need a unidirectional, many-valued associations, implem= ented with a Set. - Let's write the code for this in the Java classes and then= map it: + We need unidirectional, many-valued associations, implemen= ted with a Set. + Write the code for this in the Java classes and then map i= t: = = - Before we map this association, think about the other side= . Clearly, we could just keep this - unidirectional. Or, we could create another collection on = the Event, if we - want to be able to navigate it bi-directional, i.e. anEvent.getParticipants(). - This is not necessary, from a functional perspective. You = could always execute an explicit query + Before you map this association, consider the other side. = You could just keep this + unidirectional. Or, you could create another collection on= the Event, if you + want to be able to navigate it bi-directional, i.e., anEvent.getParticipants(). + 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 a= ssociation: "many" valued on both sides, - we call this a many-to-many associati= on. Hence, we use Hibernate's + is clear from this discussion is the multiplicity of the a= ssociation: "many" valued on both sides + is called a many-to-many association.= Hence, we use Hibernate's many-to-many mapping: = @@ -979,14 +975,14 @@ ]]> = - Hibernate supports all kinds of collection mappings, a <set> being most - common. For a many-to-many association (or n:m entity relationship), an - association table is needed. Each row in this table repres= ents a link between a person and an event. + Hibernate supports a broad range of collection mappings, a= <set> being most + common. For a many-to-many association, or n:m entity relationship, an + association table is required. Each row in this table repr= esents a link between a person and an event. The table name is configured with the table attribute of the set - element. The identifier column name in the association, fo= r the person's side, is defined with the + element. The identifier column name in the association, fo= r the person side, is defined with the <key> element, the column name fo= r the event's side with the column attribute of the <ma= ny-to-many>. You also - have to tell Hibernate the class of the objects in your co= llection (correct: the class on the + have to tell Hibernate the class of the objects in your co= llection (the class on the other side of the collection of references). = @@ -1014,7 +1010,7 @@ Working the association = - Let's bring some people and events together in a new metho= d in EventManager: + Now we will bring some people and events together in a new= method in EventManager: = After loading a Person and an = Event, simply - modify the collection using the normal collection methods.= As you can see, there is no explicit call - to update() or save(), Hibernate automatically + modify the collection using the normal collection methods.= There is no explicit call + to update() or save(); Hibernate automatically detects that the collection has been modified and needs to= be updated. This is called automatic - dirty checking, and you can also try it by modi= fying the name or the date property of + dirty checking. You can also try it by modifyin= g the name or the date property of any of your objects. As long as they are in pers= istent state, that is, bound to a particular Hibernate Session (i.e.= they have been just loaded or saved in a unit of work), Hibernate monitors any changes and execut= es SQL in a write-behind fashion. The process of synchronizing the memory state with the databas= e, 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 - as defined by = the thread configuration + work, is called flushing. In our code= , the unit of work ends with a commit, + or rollback, of the database transaction. This is defined = by the thread configuration option for the CurrentSessionContext cl= ass. = - You might of course load person and event in different uni= ts of work. Or you modify an object + You can load person and event in different units of work. = Or you can modify an object outside of a Session, when it is not in= persistent state (if it was persistent - before, we call this state detached).= You can even modify a collection when + before, this state is called detached= ). You can even modify a collection when it is detached: = @@ -1081,16 +1077,15 @@ }]]> = - The call to update makes a detached obj= ect persistent again, you could - say it binds it to a new unit of work, so any modification= s you made to it while detached + The call to update makes a detached obj= ect persistent again by binding it to a new unit of work, so any modificati= ons you made to it while detached can be saved to the database. This includes any modificati= ons (additions/deletions) you made to a collection of that entity object. = - Well, this is not much use in our current situation, but i= t's an important concept you can - design into your own application. For now, complete this e= xercise by adding a new action - to the EventManager's main method and c= all it from the command line. If + This is not much use in our example, but it is an importan= t concept you can + incorporate into your own application. Complete this exerc= ise by adding a new action + to the main method of the EventManager= and call it from the command line. If you need the identifiers of a person and an event - the save() method returns it (you might have to modify some of the previous = methods to return that identifier): @@ -1103,20 +1098,20 @@ }]]> = - This was an example of an association between two equally = important classes, two entities. + This is an example of an association between two equally i= mportant 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= nt or a String. We call these classes value types, an= d their instances depend - on a particular entity. Instances of these types don't hav= e their own identity, nor are they - shared between entities (two persons don't reference the s= ame firstname - object, even if they have the same first name). Of course,= value types can not only be found in - the JDK (in fact, in a Hibernate application all JDK class= es are considered value types), but - you can also write dependent classes yourself, Ad= dress or MonetaryAmount, - for example. + on a particular entity. Instances of these types do not ha= ve their own identity, nor are they + shared between entities. Two persons do not reference the = same firstname + object, even if they have the same first name. Value types= cannot only be found in + the JDK , but + you can also write dependent classes yourself (Ad= dress or MonetaryAmount, + for example). In fact, in a Hibernate application all JDK = classes are considered value types. = - You can also design a collection of value types. This is c= onceptually very different from a + You can also design a collection of value types. This is c= onceptually different from a collection of references to other entities, but looks almo= st the same in Java. = @@ -1126,8 +1121,8 @@ Collection of values = - We add a collection of value typed objects to the Person entity. We want to - store email addresses, so the type we use is Stri= ng, and the collection is + You can add a collection of value typed objects to the Person entity. If you want to + store email addresses, the type you use is String= , and the collection is again a Set: = - The mapping of this Set: + The mapping of this Set is as follows: = @@ -1150,17 +1145,17 @@ ]]> = - The difference compared with the earlier mapping is the element part, which tells Hibernate that the collection + The difference compared with the earlier mapping is the element part which tells Hibernate that the collection does not contain references to another entity, but a colle= ction of elements of type - String (the lowercase name tells you it= 's a Hibernate mapping type/converter). - Once again, the table attribute of the = set element determines + String. The lowercase name tells you it= is a Hibernate mapping type/converter. + Again the table attribute of the set element determines the table name for the collection. The key element defines the foreign-key column name in the collection table. The column attribute in the element element defines the column name where the String<= /literal> values will actually be stored. = - Have a look at the updated schema: + Here is the updated schema: = = - You can see that the primary key of the collection table i= s in fact a composite key, - using both columns. This also implies that there can't be = duplicate email addresses + You can see that the primary key of the collection table i= s 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 s= et in Java. = - You can now try and add elements to this collection, just = like we did before by - linking persons and events. It's the same code in Java: + You can now try to add elements to this collection, just l= ike we did before by + linking persons and events. It is the same code in Java: = = - This time we didn't use a fetch query= to initialize the collection. + This time we did not use a fetch quer= y to initialize the collection. Hence, the call to its getter method will trigger an addit= ional select to initialize it, so we can add an element to it. Monitor the SQL log an= d try to optimize this with an eager fetch. @@ -1214,11 +1209,11 @@ Bi-directional associations = - Next we are going to map a bi-directional association - ma= king the association between - person and event work from both sides in Java. Of course, = the database schema doesn't - change, we still have many-to-many multiplicity. A relatio= nal database is more flexible - than a network programming language, so it doesn't need an= ything like a navigation - direction - data can be viewed and retrieved in any possib= le way. + Next you will map a bi-directional association. You will m= ake the association between + person and event work from both sides in Java. The databas= e schema does not + change, so you will still have many-to-many multiplicity. = A relational database is more flexible + than a network programming language, so it does not need a= navigation + direction; data can be viewed and retrieved in any possibl= e way. = @@ -1236,7 +1231,7 @@ }]]> = - Now map this side of the association too, in Even= t.hbm.xml. + Now map this side of the association in Event.hbm= .xml. = @@ -1245,17 +1240,17 @@ ]]> = - As you see, these are normal set mappin= gs in both mapping documents. - Notice that the column names in key and= many-to-many are - swapped in both mapping documents. The most important addi= tion here is the + These are normal set mappings in both m= apping documents. + Notice that the column names in key and= many-to-many = + swap in both mapping documents. The most important additio= n here is the inverse=3D"true" attribute in the set element of the Event's collection mapping. = - What this means is that Hibernate should take the other si= de - the Person class - + What this means is that Hibernate should take the other si= de, the Person class, when it needs to find out information about the link betwe= en the two. This will be a lot easier to - understand once you see how the bi-directional link betwee= n our two entities is created . + understand once you see how the bi-directional link betwee= n our two entities is created. = @@ -1266,16 +1261,16 @@ First, keep in mind that Hibernate does not affect normal = Java semantics. How did we create a link between a Person and an E= vent in the unidirectional - example? We added an instance of Event = to the collection of event references, - of an instance of Person. So, obviously= , if we want to make this link working - bi-directional, we have to do the same on the other side -= adding a Person - reference to the collection in an Event= . This "setting the link on both sides" - is absolutely necessary and you should never forget doing = it. + example? You add an instance of Event t= o the collection of event references, + of an instance of Person. If you want = to make this link + bi-directional, you have to do the same on the other side = by adding a Person + reference to the collection in an Event= . This process of "setting the link on both sides" + is absolutely necessary with bi-directional links. = Many developers program defensively and create link manage= ment methods to - correctly set both sides, e.g. in Person: + correctly set both sides (for example, in Person<= /literal>): = = - Notice that 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, b= ut prevents everybody else from messing - with the collections directly (well, almost). You should p= robably do the same with the collection + The get and set methods for the collection are now protect= ed. This allows classes in the + same package and subclasses to still access the methods, b= ut prevents everybody else from altering + the collections directly. Repeat the steps for the collect= ion on the other side. = What about the inverse mapping attribut= e? For you, and for Java, a bi-directional - link is simply a matter of setting the references on both = sides correctly. Hibernate however doesn't + link is simply a matter of setting the references on both = sides correctly. Hibernate, however, does not have enough information to correctly arrange SQL = INSERT and UPDATE - statements (to avoid constraint violations), and needs som= e help to handle bi-directional associations - properly. Making one side of the association inve= rse tells Hibernate to basically - ignore it, to consider it a mirror of= the other side. That's all that is necessary - for Hibernate to work out all of the issues when transform= ation a directional navigation model to - a SQL database schema. The rules you have to remember are = straightforward: All bi-directional associations + statements (to avoid constraint violations). Making one si= de of the association inverse tells Hibernate to conside= r it a mirror of the other side. That is all that is n= ecessary + for Hibernate to resolve any issues that arise when transf= orming a directional navigation model to + a SQL database schema. The rules are straightforward: all = bi-directional associations need one side as inverse. In a one-to-m= any association it has to be the many-side, - in many-to-many association you can pick either side, ther= e is no difference. + and in many-to-many association you can select either side. = + In the next section we will turn this into a small web application.= = @@ -1324,12 +1318,8 @@ Part 3 - The EventManager web application = - Let's turn the following discussion into a small web applicati= on... - - - A Hibernate web application uses Session an= d Transaction - almost like a standalone application. However, some common pat= terns are useful. We now write + almost like a standalone application. However, some common pat= terns are useful. You can now write an EventManagerServlet. This servlet can li= st all events stored in the database, and it provides an HTML form to enter new events. @@ -1338,7 +1328,7 @@ Writing the basic servlet = - Create a new class in your source directory, in the events + Create a new class in your source directory in the events package: = @@ -1352,7 +1342,7 @@ }]]> = - The servlet handles HTTP GET requests o= nly, hence, the method + The servlet handles HTTP GET requests o= nly. It is for this reason that the method we implement is doGet(): = @@ -1382,12 +1372,12 @@ }]]> = - The pattern we are applying here is called sessi= on-per-request. + The pattern applied here is called session-per-r= equest. When a request hits the servlet, a new Hibernate = Session is opened through the first call to getCurrentSessio= n() on the - SessionFactory. Then a database transac= tion is started—all - data access as to occur inside a transaction, no matter if= data is read or written - (we don't use the auto-commit mode in applications). + SessionFactory. A database transaction = is then started. All + data access occurs inside a transaction irrespective of wh= ether the data is read or written. + Do not use the auto-commit mode in applications. = @@ -1399,17 +1389,17 @@ = Next, the possible actions of the request are processed an= d the response HTML - is rendered. We'll get to that part soon. + is rendered. We will get to that part soon. = - Finally, the unit of work ends when processing and renderi= ng is complete. If any - problem occurred during processing or rendering, an except= ion will be thrown + Finally, the unit of work ends when processing and renderi= ng are complete. If any + problems occurred during processing or rendering, an excep= tion will be thrown and the database transaction rolled back. This completes t= he session-per-request pattern. Instead of= the transaction - demarcation code in every servlet you could also write a s= ervlet filter. - See the Hibernate website and Wiki for more information ab= out this pattern, - called Open Session in View—you= 'll need it as soon + demarcation code in every servlet, you could also write a = servlet filter. + See the Hibernate website and Wiki for more information ab= out this pattern + called Open Session in View. You will= need it as soon as you consider rendering your view in JSP, not in a servl= et. = @@ -1419,7 +1409,7 @@ Processing and rendering = - Let's implement the processing of the request and renderin= g of the page. + Now you can implement the processing of the request and th= e rendering of the page. = = - Granted, this coding style with a mix of Java and HTML wou= ld not scale + This coding style, with a mix of Java and HTML, would not = scale in a more complex application—keep in mind that we a= re only illustrating basic Hibernate concepts in this tutorial. The code prints= an HTML header and a footer. Inside this page, an HTML form for ev= ent entry and @@ -1511,12 +1501,12 @@ }]]> = - That's it, the servlet is complete. A request to the servl= et will be processed + The servlet is now complete. A request to the servlet will= be processed in a single Session and Transa= ction. As earlier in the standalone application, Hibernate can autom= atically bind these objects to the current thread of execution. This gives you= the freedom to layer your code and access the SessionFactory= in any way you like. - Usually you'd use a more sophisticated design and move the= data access code + Usually you would use a more sophisticated design and move= the data access code into data access objects (the DAO pattern). See the Hibern= ate Wiki for more examples. @@ -1527,7 +1517,7 @@ Deploying and testing = - To deploy this application you have to create a web archiv= e, a WAR. Add the + To deploy this application you have to create a web archiv= e, or what is known as a WAR. Add the following Ant target to your build.xml: = @@ -1565,9 +1555,9 @@ ]]> = - Before you compile and deploy the web application, note th= at an additional library - is required: jsdk.jar. This is the Java= servlet development kit, - if you don't have this library already, get it from the Su= n website and copy it to + Before you compile and deploy the web application, an addi= tional library + is required: jsdk.jar. This is the Java= servlet development kit. + If you do not have this library already, get it from the S= un website and copy it to your library directory. However, it will be only used for = compilation and excluded from the WAR package. @@ -1575,8 +1565,8 @@ To build and deploy call ant war in you= r project directory and copy the hibernate-tutorial.war fil= e into your Tomcat - webapp directory. If you don't have Tom= cat installed, download - it and follow the installation instructions. You don't hav= e to change any Tomcat + webapp directory. If you do not have To= mcat installed, download + it and follow the installation instructions. You do not ha= ve to change any Tomcat configuration to deploy this application though. = @@ -1602,14 +1592,14 @@ = If you already feel confident with Hibernate, continue browsin= g through the reference - documentation table of contents for topics you find interestin= g - most asked are + documentation table of contents for topics you find interestin= g. The most popular are transactional processing (), f= etch performance (), or the usage of= the API () and the query features (). = - Don't forget to check the Hibernate website for more (speciali= zed) tutorials. + More tutorials are available from the Hibernate website. = Modified: core/branches/Branch_3_3/documentation/manual/src/main/docbook/en= -US/content/xml.xml =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/xml.xml 2009-01-29 05:20:27 UTC (rev 15829) +++ core/branches/Branch_3_3/documentation/manual/src/main/docbook/en-US/co= ntent/xml.xml 2009-01-29 19:56:06 UTC (rev 15830) @@ -29,17 +29,17 @@ XML Mapping = - Note that this is an experimental feature in Hibernate 3.0 and is = under - extremely active development. + XML Mapping is an experimental feature in Hibernate 3.0 and is cur= rently under + active development. = Working with XML data = - Hibernate lets you work with persistent XML data in much the s= ame way + Hibernate allows you to work with persistent XML data in much = the same way you work with persistent POJOs. A parsed XML tree can be thoug= ht of - as just another way to represent the relational data at the ob= ject level, + as another way of representing the relational data at the obje= ct level, instead of POJOs. = @@ -59,9 +59,9 @@ = - A single mapping may be used to simultaneously map properties = of a class + A single mapping can be used to simultaneously map properties = of a class and nodes of an XML document to the database, or, if there is = no class to map, = - it may be used to map just the XML. + it can be used to map just the XML. = @@ -126,8 +126,8 @@ = This mapping allows you to access the data as a dom4j tree= , or as a graph of - property name/value pairs (java Maps). = The property names - are purely logical constructs that may be referred to in H= QL queries. + property name/value pairs or java Maps.= The property names + are purely logical constructs that can be referred to in H= QL queries. = @@ -138,25 +138,25 @@ XML mapping metadata = - Many Hibernate mapping elements accept the node attribute. - This let's you specify the name of an XML attribute or element= that holds the + A range of Hibernate mapping elements accept the node= attribute. + This lets you specify the name of an XML attribute or element = that holds the property or entity data. The format of the node attribute must be one of the following: = - "element-name" - map to the named XML= element + "element-name": map to the named XML = element - "@attribute-name" - map to the named = XML attribute + "@attribute-name": map to the named X= ML attribute - "." - map to the parent element + ".": map to the parent element - "element-name/@attribute-name" - = + "element-name/@attribute-name": map to the named attribute of the named element @@ -169,12 +169,12 @@ will be embedded directly in the XML tree for the entity that = owns the association. Otherwise, if embed-xml=3D"false", then onl= y the referenced = identifier value will appear in the XML for single point assoc= iations and = - collections will simply not appear at all. + collections will not appear at all. = - You should be careful not to leave embed-xml=3D"true"= for - too many associations, since XML does not deal well with circu= larity! + Do not leave embed-xml=3D"true" for + too many associations, since XML does not deal well with circu= larity. = ]]> = - in this case, we have decided to embed the collection of accou= nt ids, but not + In this case, the collection of account ids is embedded, but n= ot the actual account data. The following HQL query: = = - Would return datasets such as this: + would return datasets such as this: = @@ -263,7 +263,7 @@ Manipulating XML data = - Let's rearead and update XML documents in the application. We = do this by + You can also re-read and update XML documents in the applicati= on. You can do this by obtaining a dom4j session: = @@ -303,8 +303,8 @@ session.close();]]> = - It is extremely useful to combine this feature with Hibernate'= s replicate() - operation to implement XML-based data import/export. + When implementing XML-based data import/export, it is useful t= o combine this feature with Hibernate's replicate() + operation. = --===============2081375298519546727==--