From hibernate-commits at lists.jboss.org Thu Jun 10 12:21:23 2010 Content-Type: multipart/mixed; boundary="===============8978130858146101067==" MIME-Version: 1.0 From: hibernate-commits at lists.jboss.org To: hibernate-commits at lists.jboss.org Subject: [hibernate-commits] Hibernate SVN: r19711 - core/trunk/documentation/manual/src/main/docbook/en-US/content. Date: Thu, 10 Jun 2010 12:21:23 -0400 Message-ID: <201006101621.o5AGLNKb004437@svn01.web.mwc.hst.phx2.redhat.com> --===============8978130858146101067== Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Author: epbernard Date: 2010-06-10 12:21:22 -0400 (Thu, 10 Jun 2010) New Revision: 19711 Modified: core/trunk/documentation/manual/src/main/docbook/en-US/content/basic_map= ping.xml Log: HHH-5149 Add documentation for to one associations with foreign key Describe foreign key and association table options. Describe various configurations like fetch lazy and co. Modified: core/trunk/documentation/manual/src/main/docbook/en-US/content/ba= sic_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/trunk/documentation/manual/src/main/docbook/en-US/content/basic_ma= pping.xml 2010-06-10 16:20:43 UTC (rev 19710) +++ core/trunk/documentation/manual/src/main/docbook/en-US/content/basic_ma= pping.xml 2010-06-10 16:21:22 UTC (rev 19711) @@ -2323,7 +2323,7 @@ exhausted your in-memory value group. This is the role of the pluggable optimizers. Currently only the two enhanced generators ( support th= is - operation. + operation. = @@ -4182,52 +4182,300 @@ = -
- Many-to-one +
+ Mapping a to-one association = - An ordinary association to another persistent class is declared - using a many-to-one element. The relational model= is - a many-to-one association; a foreign key in one table is referencing= the - primary key column(s) of the target table. + To link one entity to an other, you need to map the association + property as a to one association. In the relational model, you can + either use a foreign key or an association table, or (a bit less com= mon) + share the same primary key value between the two entities. = - - - + To mark an association, use either + @ManyToOne or + @OnetoOne. = - +
+ Using a foreign key or an association table = - + An ordinary association to another persistent class is decla= red + using a = - + + + @ManyToOne if several entities can + point to the the target entity + = - + + @OneToOne if only a single entity= can + point to the the target entity + + = - - + and a foreign key in one table is referencing the primary key + column(s) of the target table. = - - + @Entity +public class Flight implements Serializable { + @ManyToOne( cascade =3D {CascadeType.PERSIST, CascadeType.MERGE} ) + @JoinColumn(name=3D"COMP_ID") + public Company getCompany() { + return company; + } + ... +} = - + The @JoinColumn attribute is optional, the + default value(s) is the concatenation of the name of the relations= hip + in the owner side, _ (underscore), and the name of + the primary key column in the owned side. In this example + company_id because the property name is + company and the column id of Company is + id. = - + @ManyToOne has a parameter named + targetEntity which describes the target entity + name. You usually don't need this parameter since the default value + (the type of the property that stores the association) is good in + almost all cases. However this is useful when you want to use + interfaces as the return type instead of the regular entity. = - + @Entity +public class Flight implements Serializable { + @ManyToOne( cascade =3D {CascadeType.PERSIST, CascadeType.MERGE}, targ= etEntity=3DCompanyImpl.class ) + @JoinColumn(name=3D"COMP_ID") + public Company getCompany() { + return company; + } + ... +} = - +public interface Company { + ... +} = - + You can also map a to one association through an association + table. This association table described by the + @JoinTable annotation will contains a foreign k= ey + referencing back the entity table (through + @JoinTable.joinColumns) and a a foreign key + referencing the target entity table (through + @JoinTable.inverseJoinColumns). = - + @Entity +public class Flight implements Serializable { + @ManyToOne( cascade =3D {CascadeType.PERSIST, CascadeType.MERGE} ) + @JoinTable(name=3D"Flight_Company", + joinColumns =3D @JoinColumn(name=3D"FLIGHT_ID"), + inverseJoinColumns =3D @JoinColumn(name=3D"COMP_ID") + ) + public Company getCompany() { + return company; + } + ... +} = - + + You can use a SQL fragment to simulate a physical join col= umn + using the @JoinColumnOrFormula / + @JoinColumnOrformulas annotations (just l= ike + you can use a SQL fragment to simulate a property column via the + @Formula annotation). = - + @Entity +public class Ticket implements Serializable { + @ManyToOne + @JoinColumnOrFormula(formula=3D"(firstname + ' ' + lastname)") + public Person getOwner() { + return person; + } + ... +} + = - - + You can mark an association as mandatory by using the + optional=3Dfalse attribute. We recommend to use= Bean + Validation's @NotNull annotation as a better + alternative however. As a consequence, the foreign key column(s) w= ill + be marked as not nullable (if possible). = - <many-to-one + Setting a value of the cascade attribute = to + any meaningful value other than nothing will propagate certain + operations to the associated object. The meaningful values are div= ided + into three categories. + + + + basic operations, which include: persist, merge, + delete, save-update, evict, replicate, lock and + refresh; + + + + special values: delete-orphan or + all ; + + + + comma-separated combinations of operation names: + cascade=3D"persist,merge,evict" or + cascade=3D"all,delete-orphan". See for a full explanation. = Note + that single valued many-to-one associations do not support orp= han + delete. + + + + By default, single point associations are eagerly fetched in= JPA + 2. You can mark it as lazily fetched by using + @ManyToOne(fetch=3DFetchType.LAZY) in which= case + Hibernate will proxy the association and load it when the state of= the + associated entity is reached. You can force Hibernate not to use a + proxy by using @LazyToOne(NO_PROXY). In this + case, the property is fetched lazily when the instance variable is + first accessed. This requires build-time bytecode instrumentation. + lazy=3D"false" specifies that the association will always be eager= ly + fetched. + + With the default JPA options, single-ended associations are + loaded with a subsequent select if set to LAZY,= or + a SQL JOIN is used for EAGER associations. You = can + however adjust the fetching strategy, ie how data is fetched by us= ing + @Fetch. FetchMode can be + SELECT (a select is triggered when the associat= ion + needs to be loaded) or JOIN (use a SQL JOIN to = load + the association while loading the owner entity). + JOIN overrides any lazy attribute (an associati= on + loaded through a JOIN strategy cannot be + lazy). + + When Hibernate cannot resolve the association because the + expected associated element is not in database (wrong id on the + association column), an exception is raised. This might be + inconvenient for legacy and badly maintained schemas. You can ask + Hibernate to ignore such elements instead of raising an exception + using the @NotFound annotation. + + + @NotFound annotation + + @Entity +public class Child { + ... + @ManyToOne + @NotFound(action=3DNotFoundAction.IGNORE) + public Parent getParent() { ... } + ... +} + + + Sometimes you want to delegate to your database the deletion= of + cascade when a given entity is deleted. In this case Hibernate + generates a cascade delete constraint at the database level. + + + @OnDelete annotation + + @Entity +public class Child { + ... + @ManyToOne + @OnDelete(action=3DOnDeleteAction.CASCADE) + public Parent getParent() { ... } + ... +} + + + Foreign key constraints, while generated by Hibernate, have a + fairly unreadable name. You can override the constraint name using + @ForeignKey. + + + @ForeignKey annotation + + @Entity +public class Child { + ... + @ManyToOne + @ForeignKey(name=3D"FK_PARENT") + public Parent getParent() { ... } + ... +} + +alter table Child add constraint FK_PARENT foreign key (parent_id) referen= ces Parent + + + Sometimes, you want to link one entity to an other not by the + target entity primary key but by a different unique key. You can + achieve that by referencing the unique key column(s) in + @JoinColumn.referenceColumnName. + + @Entity +class Person { + @Id Integer personNumber; + String firstName; + @Column(name=3D"I") + String initial; + String lastName; +} + +(a)Entity +class Home { + @ManyToOne + @JoinColumns({ + @JoinColumn(name=3D"first_name", referencedColumnName=3D"firstName"), + @JoinColumn(name=3D"init", referencedColumnName=3D"I"), + @JoinColumn(name=3D"last_name", referencedColumnName=3D"lastName"), + }) + Person owner +} + + This is not encouraged however and should be reserved to leg= acy + mappings. + + In hbm.xml, mapping an association is similar. The main + difference is that a @OneToOne is mapped as + <many-to-one unique=3D"true"/>, let's div= e into + the subject. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <many-to-one name=3D"propertyName" column=3D"column_name" class=3D"ClassName" @@ -4251,186 +4499,187 @@ foreign-key=3D"foreign_key_name" /> = - - - name: the name of the property. - + + + name: the name of the property. + = - - column (optional): the name of the - foreign key column. This can also be specified by nested - <column> element(s). - + + 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 - associated class. - + + class (optional - defaults to the + property type determined by reflection): the name of the + associated class. + = - - cascade (optional): specifies which - operations should be cascaded from the parent object to the - associated object. - + + cascade (optional): specifies which + operations should be cascaded from the parent object to the + associated object. + = - - fetch (optional - defaults to - select): chooses between outer-join fetchin= g or - sequential select fetching. - + + fetch (optional - defaults to + select): chooses between outer-join fetch= ing + or sequential select fetching. + = - - update, insert (optional - defaults to - true): specifies that the mapped columns sh= ould - be included in SQL UPDATE and/or - INSERT statements. Setting both to - false allows a pure "derived" association w= hose - value is initialized from another property that maps to the sa= me - column(s), or by a trigger or other application. - + + update, insert (optional - defaults= to + true): specifies that the mapped columns + should be included in SQL UPDATE and/or + INSERT statements. Setting both to + false allows a pure "derived" association + whose value is initialized from another property that maps to + the same column(s), or by a trigger or other application. + = - - property-ref (optional): the name of a - property of the associated class that is joined to this foreign - key. If not specified, the primary key of the associated class= is - used. - + + property-ref (optional): the name o= f a + property of the associated class that is joined to this fore= ign + key. If not specified, the primary key of the associated cla= ss + is used. + = - - access (optional - defaults to - property): the strategy Hibernate uses for - accessing the property value. - + + access (optional - defaults to + property): the strategy Hibernate uses for + accessing the property value. + = - - unique (optional): enables the DDL - generation of a unique constraint for the foreign-key column. = By - allowing this to be the target of a - property-ref, you can make the association - multiplicity one-to-one. - + + unique (optional): enables the DDL + generation of a unique constraint for the foreign-key column= . By + allowing this to be the target of a + property-ref, you can make the association + multiplicity one-to-one. + = - - not-null (optional): enables the DDL - generation of a nullability constraint for the foreign key - columns. - + + not-null (optional): enables the DDL + generation of a nullability constraint for the foreign key + columns. + = - - optimistic-lock (optional - defaults = to - true): specifies that updates to this prope= rty - do or do not require acquisition of the optimistic lock. In ot= her - words, it determines if a version increment should occur when = this - property is dirty. - + + optimistic-lock (optional - default= s to + true): 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 to - proxy): by default, single point associatio= ns - are proxied. lazy=3D"no-proxy" specifies th= at the - property should be fetched lazily when the instance variable is - first accessed. This requires build-time bytecode instrumentat= ion. - lazy=3D"false" specifies that the associati= on - will always be eagerly fetched. - + + lazy (optional - defaults to + proxy): by default, single point associat= ions + are proxied. lazy=3D"no-proxy" specifies = that + the property should be fetched lazily when the instance vari= able + is first accessed. This requires build-time bytecode + instrumentation. lazy=3D"false" specifies= that + the association will always be eagerly fetched. + = - - not-found (optional - defaults to - exception): specifies how foreign keys that - reference missing rows will be handled. ignore - will treat a missing row as a null association. - + + not-found (optional - defaults to + exception): specifies how foreign keys th= at + reference missing rows will be handled. + ignore will treat a missing row as a null + association. + = - - entity-name (optional): the entity na= me - of the associated class. - + + entity-name (optional): the entity = name + of the associated class. + = - - formula (optional): an SQL expression - that defines the value for a computed for= eign - key. - - - + + formula (optional): an SQL expressi= on + that defines the value for a computed + foreign key. + + + = - Setting a value of the cascade attribute to= any - meaningful value other than none will propagate - certain operations to the associated object. The meaningful values a= re - divided into three categories. First, basic operations, which includ= e: - persist, merge, delete, save-update, evict, replicate, lock= and - refresh; second, special values: - delete-orphan; and third,all - comma-separated combinations of operation names: - cascade=3D"persist,merge,evict" or - cascade=3D"all,delete-orphan". See for a full explanation. Note t= hat - single valued, many-to-one and one-to-one, associations do not suppo= rt - orphan delete. + Setting a value of the cascade attribute = to + any meaningful value other than none will propa= gate + certain operations to the associated object. The meaningful values= are + divided into three categories. First, basic operations, which incl= ude: + persist, merge, delete, save-update, evict, replicate, lo= ck + and refresh; second, special values: + delete-orphan; and third,all + comma-separated combinations of operation names: + cascade=3D"persist,merge,evict" or + cascade=3D"all,delete-orphan". See for a full explanation. Note= that + single valued, many-to-one and one-to-one, associations do not sup= port + orphan delete. = - Here is an example of a typical many-to-one - declaration: + Here is an example of a typical many-to-one + declaration: = - <many-to-one name=3D"product" class= =3D"Product" column=3D"PRODUCT_ID"/> + <many-to-one name=3D"product" clas= s=3D"Product" column=3D"PRODUCT_ID"/> = - The property-ref attribute should only be u= sed - for mapping legacy data where a foreign key refers to a unique key of - the associated table other than the primary key. This is a complicat= ed - and confusing relational model. For example, if the - Product class had a unique serial number that is = not - the primary key. The unique attribute controls - Hibernate's DDL generation with the SchemaExport tool. + The property-ref attribute should only be + used for mapping legacy data where a foreign key refers to a unique + key of the associated table other than the primary key. This is a + complicated and confusing relational model. For example, if the + Product class had a unique serial number that is + not the primary key. The unique attribute contr= ols + Hibernate's DDL generation with the SchemaExport tool. = - <property name=3D"serialNumber" uniq= ue=3D"true" type=3D"string" column=3D"SERIAL_NUMBER"/> + <property name=3D"serialNumber" un= ique=3D"true" type=3D"string" column=3D"SERIAL_NUMBER"/> = - Then the mapping for OrderItem might - use: + Then the mapping for OrderItem might + use: = - <many-to-one name=3D"product" proper= ty-ref=3D"serialNumber" column=3D"PRODUCT_SERIAL_NUMBER"/> + <many-to-one name=3D"product" prop= erty-ref=3D"serialNumber" column=3D"PRODUCT_SERIAL_NUMBER"/> = - This is not encouraged, however. + This is not encouraged, however. = - If the referenced unique key comprises multiple properties of = the - associated entity, you should map the referenced properties inside a - named <properties> element. + If the referenced unique key comprises multiple properties of + the associated entity, you should map the referenced properties in= side + a named <properties> element. = - If the referenced unique key is the property of a component, y= ou - can specify a property path: + If the referenced unique key is the property of a component,= you + can specify a property path: = - <many-to-one name=3D"owner" property= -ref=3D"identity.ssn" column=3D"OWNER_SSN"/> -
+ <many-to-one name=3D"owner" proper= ty-ref=3D"identity.ssn" column=3D"OWNER_SSN"/> +
= -
- One-to-one +
+ One-to-one = - A one-to-one association to another persistent class is declar= ed - using a one-to-one element. + A one-to-one association to another persistent class is decl= ared + using a one-to-one element. = - - - + + + = - + = - + = - + = - + = - + = - + = - + = - + = - - + + = - <one-to-one + <one-to-one name=3D"propertyName" class=3D"ClassName" cascade=3D"cascade_style" @@ -4446,111 +4695,112 @@ foreign-key=3D"foreign_key_name" /> = - - - name: the name of the property. - + + + name: the name of the property. + = - - class (optional - defaults to the - property type determined by reflection): the name of the - associated class. - + + class (optional - defaults to the + property type determined by reflection): the name of the + associated class. + = - - cascade (optional): specifies which - operations should be cascaded from the parent object to the - associated object. - + + cascade (optional): specifies which + operations should be cascaded from the parent object to the + associated object. + = - - constrained (optional): specifies tha= t a - foreign key constraint on the primary key of the mapped table = and - references the table of the associated class. This option affe= cts - the order in which save() and - delete() are cascaded, and determines wheth= er - the association can be proxied. It is also used by the schema - export tool. - + + constrained (optional): specifies t= hat + a foreign key constraint on the primary key of the mapped ta= ble + and references the table of the associated class. This option + affects the order in which save() and + delete() are cascaded, and determines whe= ther + the association can be proxied. It is also used by the schema + export tool. + = - - fetch (optional - defaults to - select): chooses between outer-join fetchin= g or - sequential select fetching. - + + fetch (optional - defaults to + select): chooses between outer-join fetch= ing + or sequential select fetching. + = - - property-ref (optional): the name of a - property of the associated class that is joined to the primary= key - of this class. If not specified, the primary key of the associ= ated - class is used. - + + property-ref (optional): the name o= f a + property of the associated class that is joined to the prima= ry + key of this class. If not specified, the primary key of the + associated class is used. + = - - access (optional - defaults to - property): the strategy Hibernate uses for - accessing the property value. - + + access (optional - defaults to + property): the strategy Hibernate uses for + accessing the property value. + = - - formula (optional): almost all one-to= -one - associations map to the primary key of the owning entity. If t= his - is not 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. - + + formula (optional): almost all + one-to-one associations map to the primary key of the owning + entity. If this is not the case, you can specify another col= umn, + columns or expression to join on using an SQL formula. See + org.hibernate.test.onetooneformula for an + example. + = - - lazy (optional - defaults to - proxy): by default, single point associatio= ns - are proxied. lazy=3D"no-proxy" specifies th= at the - property should be fetched lazily when the instance variable is - first accessed. It requires build-time bytecode instrumentatio= n. - lazy=3D"false" specifies that the associati= on - will always be eagerly fetched. Note that if - constrained=3D"false", proxying is impossib= le and - Hibernate will eagerly fetch the association. - + + lazy (optional - defaults to + proxy): by default, single point associat= ions + are proxied. lazy=3D"no-proxy" specifies = that + the property should be fetched lazily when the instance vari= able + is first accessed. It requires build-time bytecode + instrumentation. lazy=3D"false" specifies= that + the association will always be eagerly fetched. No= te + that if constrained=3D"false", proxying is + impossible and Hibernate will eagerly fetch the + association. + = - - entity-name (optional): the entity na= me - of the associated class. - - - + + entity-name (optional): the entity = name + of the associated class. + + + = - There are two varieties of one-to-one associations: + There are two varieties of one-to-one associations: = - - - primary key associations - + + + primary key associations + = - - unique foreign key associations - - + + unique foreign key associations + + = - Primary key associations do not need an extra table column. If= two - rows are related by the association, then the two table rows share t= he - same primary key value. To relate two objects by a primary key - association, ensure 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 s= hare + the same primary key value. To relate two objects by a primary key + association, ensure that they are assigned the same identifier + value. = - For a primary key association, add the following mappings to - Employee and Person - respectively: + For a primary key association, add the following mappings to + Employee and Person + respectively: = - <one-to-one name=3D"person" class=3D= "Person"/> + <one-to-one name=3D"person" class= =3D"Person"/> = - <one-to-one name=3D"employee" class= =3D"Employee" constrained=3D"true"/> + <one-to-one name=3D"employee" clas= s=3D"Employee" constrained=3D"true"/> = - Ensure that the primary keys of the related rows in the PERSON= and - EMPLOYEE tables are equal. You use a special Hibernate identifier - generation strategy called foreign: + Ensure that the primary keys of the related rows in the PERS= ON + and EMPLOYEE tables are equal. You use a special Hibernate identif= ier + generation strategy called foreign: = - <class name=3D"person" table=3D"PERS= ON"> + <class name=3D"person" table=3D"PE= RSON"> <id name=3D"id" column=3D"PERSON_ID"> <generator class=3D"foreign"> <param name=3D"property">employee</param> @@ -4562,21 +4812,22 @@ constrained=3D"true"/> </class> = - A newly saved instance of Person is assigned - the same primary key value as the Employee instan= ce - referred with the employee property of that - Person. + A newly saved instance of Person is assig= ned + the same primary key value as the Employee inst= ance + referred with the employee property of that + Person. = - Alternatively, a foreign key with a unique constraint, from - Employee to Person, can be - expressed as: + Alternatively, a foreign key with a unique constraint, from + Employee to Person, can be + expressed as: = - <many-to-one name=3D"person" class= =3D"Person" column=3D"PERSON_ID" unique=3D"true"/> + <many-to-one name=3D"person" class= =3D"Person" column=3D"PERSON_ID" unique=3D"true"/> = - This association can be made bidirectional by adding the follo= wing - to the Person mapping: + This association can be made bidirectional by adding the + following to the Person mapping: = - <one-to-one name=3D"employee" class= =3D"Employee" property-ref=3D"person"/> + <one-to-one name=3D"employee" clas= s=3D"Employee" property-ref=3D"person"/> +
=
--===============8978130858146101067==--