From bf2dab5479ec1b98ca4a2fd956bdbc65650c1935 Mon Sep 17 00:00:00 2001 From: Emmanuel Bernard Date: Thu, 22 Apr 2010 17:20:04 +0000 Subject: [PATCH] HHH-5149 start injecting annotations in mapping section git-svn-id: https://svn.jboss.org/repos/hibernate/core/trunk@19283 1b8cb986-b30d-0410-93ca-fae66ebed9b2 --- .../docbook/en-US/content/basic_mapping.xml | 5977 +++++++++-------- 1 file changed, 3025 insertions(+), 2952 deletions(-) diff --git a/documentation/manual/src/main/docbook/en-US/content/basic_mapping.xml b/documentation/manual/src/main/docbook/en-US/content/basic_mapping.xml index 37e0c236bf..09dc108865 100644 --- a/documentation/manual/src/main/docbook/en-US/content/basic_mapping.xml +++ b/documentation/manual/src/main/docbook/en-US/content/basic_mapping.xml @@ -1,4 +1,4 @@ - + - - %BOOK_ENTITIES; - ]> - - Basic O/R Mapping + Basic O/R Mapping -
- Mapping declaration +
+ Mapping declaration - - Object/relational mappings are usually defined in an XML document. The mapping - document is designed to be readable and hand-editable. The mapping language is - Java-centric, meaning that mappings are constructed around persistent class - declarations and not table declarations. - + Object/relational mappings can be defined in three + approaches: - - Please note that even though many Hibernate users choose to write the XML by hand, - a number of tools exist to generate the mapping document. These include XDoclet, - Middlegen and AndroMDA. - + + + using Java 5 annotations (via the Java Persistence 2 + annotations) + - - Here is an example mapping: - + + using JPA 2 XML deployment descriptors (described in chapter + XXX) + + + using the Hibernate legacy XML files approach known as + hbm.xml + + - -Annotations are split in two categories, the logical mapping + annotations (describing the object model, the association between two + entities etc.) and the physical mapping annotations (describing the + physical schema, tables, columns, indexes, etc). We will mix annotations + from both categories in the following code examples. + + JPA annotations are in the javax.persistence.* + package. Hibernate specific extensions are in + org.hibernate.annotations.*. You favorite IDE can + auto-complete annotations and their attributes for you (even without a + specific "JPA" plugin, since JPA annotations are plain Java 5 + annotations). + + Here is an example of mapping + + package eg; + +@Entity +@Table(name="cats") @Inheritance(strategy=SINGLE_TABLE) +@DiscriminatorValue("C") @DiscriminatorColumn(name="subclass", discriminatorType=CHAR) +public class Cat { + + @Id @GeneratedValue + public Integer getId() { return id; } + public void setId(Integer id) { this.id = id; } + private Integer id; + + public BigDecimal getWeight() { return weight; } + public void setWeight(BigDecimal weight) { this.weight = weight; } + private BigDecimal weight; + + @Temporal(DATE) @NotNull @Column(updatable=false) + public Date getBirthdate() { return birthdate; } + public void setBirthdate(Date birthdate) { this.birthdate = birthdate; } + private Date birthdate; + + @org.hibernate.annotations.Type(type="eg.types.ColorUserType") + @NotNull @Column(updatable=false) + public ColorType getColor() { return color; } + public void setColor(ColorType color) { this.color = color; } + private ColorType color; + + @NotNull @Column(updatable=false) + public String getSex() { return sex; } + public void setSex(String sex) { this.sex = sex; } + private String sex; + + @NotNull @Column(updatable=false) + public Integer getLitterId() { return litterId; } + public void setLitterId(Integer litterId) { this.litterId = litterId; } + private Integer litterId; + + @ManyToOne @JoinColumn(name="mother_id", updatable=false) + public Cat getMother() { return mother; } + public void setMother(Cat mother) { this.mother = mother; } + private Cat mother; + + @OneToMany(mappedBy="mother") @OrderBy("litterId") + public Set<Cat> getKittens() { return kittens; } + public void setKittens(Set<Cat> kittens) { this.kittens = kittens; } + private Set<Cat> kittens = new HashSet<Cat>(); +} + +@Entity @DiscriminatorValue("D") +public class DomesticCat extends Cat { + + public String getName() { return name; } + public void setName(String name) { this.name = name } + private String name; +} + +@Entity +public class Dog { ... } + + The legacy hbm.xml approach uses an XML schema designed to be + readable and hand-editable. The mapping language is Java-centric, meaning + that mappings are constructed around persistent class declarations and not + table declarations. + + Please note that even though many Hibernate users choose to write + the XML by hand, a number of tools exist to generate the mapping document. + These include XDoclet, Middlegen and AndroMDA. + + Here is an example mapping: + + <?xml version="1.0"?> +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> + "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> - +<hibernate-mapping package="eg"> - + discriminator-value="C"> - - - + <id name="id"> + <generator class="native"/> + </id> - + <discriminator column="subclass" + type="character"/> - + <property name="weight"/> - + update="false"/> - + update="false"/> - + update="false"/> - + update="false"/> - + update="false"/> - - - - + order-by="litter_id"> + <key column="mother_id"/> + <one-to-many class="Cat"/> + </set> - + <subclass name="DomesticCat" + discriminator-value="D"> - + <property name="name" + type="string"/> - + </subclass> - + </class> - - - + <class name="Dog"> + <!-- mapping for Dog could go here --> + </class> -]]> +</hibernate-mapping> - - We will now discuss the content of the mapping document. We will only describe, however, the - document elements and attributes that are used by Hibernate at runtime. The mapping - document also contains some extra optional attributes and elements that affect the - database schemas exported by the schema export tool (for example, the - not-null attribute). - + We will now discuss the concepts of the mapping documents (both + annotations and XML). We will only describe, however, the document + elements and attributes that are used by Hibernate at runtime. The mapping + document also contains some extra optional attributes and elements that + affect the database schemas exported by the schema export tool (for + example, the not-null attribute). +
+ Some hbm.xml specificities + The hbm.xml structure has some specificities naturally not present + when using annotations, let's describe them briefly. -
- Doctype +
+ Doctype - - All XML mappings should declare the doctype shown. The actual DTD can be found - at the URL above, in the directory hibernate-x.x.x/src/org/hibernate - , or in hibernate3.jar. Hibernate will always look for - the DTD in its classpath first. If you experience lookups of the DTD using an - Internet connection, check the DTD declaration against the contents of your - classpath. - + All XML mappings should declare the doctype shown. The actual + DTD can be found at the URL above, in the directory + hibernate-x.x.x/src/org/hibernate , or in + hibernate3.jar. Hibernate will always look for the + DTD in its classpath first. If you experience lookups of the DTD using + an Internet connection, check the DTD declaration against the contents + of your classpath. -
- EntityResolver - - Hibernate will first attempt to resolve DTDs in its classpath. - It does this is by registering a custom org.xml.sax.EntityResolver - implementation with the SAXReader it uses to read in the xml files. This custom - EntityResolver recognizes two different systemId namespaces: - - - - - a hibernate namespace is recognized whenever the - resolver encounters a systemId starting with - http://hibernate.sourceforge.net/. The resolver - attempts to resolve these entities via the classloader which loaded - the Hibernate classes. - - - - - a user namespace is recognized whenever the - resolver encounters a systemId using a classpath:// - URL protocol. The resolver will attempt to resolve these entities - via (1) the current thread context classloader and (2) the - classloader which loaded the Hibernate classes. - - - - - The following is an example of utilizing user namespacing: - - - +
+ EntityResolver + + Hibernate will first attempt to resolve DTDs in its classpath. + It does this is by registering a custom + org.xml.sax.EntityResolver implementation with + the SAXReader it uses to read in the xml files. This custom + EntityResolver recognizes two different systemId + namespaces: + + + + a hibernate namespace is recognized + whenever the resolver encounters a systemId starting with + http://hibernate.sourceforge.net/. The + resolver attempts to resolve these entities via the classloader + which loaded the Hibernate classes. + + + + a user namespace is recognized whenever + the resolver encounters a systemId using a + classpath:// URL protocol. The resolver will + attempt to resolve these entities via (1) the current thread + context classloader and (2) the classloader which loaded the + Hibernate classes. + + + + The following is an example of utilizing user + namespacing: + + + - - Where types.xml is a resource in the your.domain - package and contains a custom typedef. - -
+ + Where types.xml is a resource in the + your.domain package and contains a custom typedef.
+
-
- 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 they are specified, 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 that do not specify a - cascade attribute. By default, the auto-import attribute allows you - to use unqualified class names in the query language. - + 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 they are specified, 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 that do not specify a + cascade attribute. By default, the + auto-import attribute allows you to use unqualified + class names in the query language. - - - - - - - - - - - + + + + + + + + + + + + + + + + + <hibernate-mapping schema="schemaName" catalog="catalogName" default-cascade="cascade_style" @@ -213,104 +310,121 @@ default-lazy="true|false" auto-import="true|false" package="package.name" - />]]> - - - - schema (optional): the name of a database schema. - - - - - catalog (optional): the name of a database catalog. - - - - - default-cascade (optional - defaults to none): - a default cascade style. - - - - - default-access (optional - defaults to property): - the strategy Hibernate should use for accessing all properties. It can be a custom - implementation of PropertyAccessor. - - - - - default-lazy (optional - defaults to true): - the default value for unspecified lazy attributes of class and - collection mappings. - - - - - auto-import (optional - defaults to true): - specifies whether we can use unqualified class names of classes in this mapping - in the query language. - - - - - package (optional): specifies a package prefix to use for - unqualified class names in the mapping document. - - - - + /> - - If you have two persistent classes with the same unqualified name, you should set - auto-import="false". An exception will result if you attempt - to assign two classes to the same "imported" name. - + + + schema (optional): the name of a + database schema. + - - The hibernate-mapping element allows you to nest - several persistent <class> mappings, as shown above. - It is, however, good practice (and expected by some tools) to map only a single - persistent class, or a single class hierarchy, in one mapping file and name - it after the persistent superclass. For example, Cat.hbm.xml, - Dog.hbm.xml, or if using inheritance, - Animal.hbm.xml. - + + catalog (optional): the name of a + database catalog. + -
+ + default-cascade (optional - defaults to + none): a default cascade style. + -
- Class + + default-access (optional - defaults to + property): the strategy Hibernate should use + for accessing all properties. It can be a custom implementation + of PropertyAccessor. + - - You can declare a persistent class using the class element. For example: - + + default-lazy (optional - defaults to + true): the default value for unspecified + lazy attributes of class and collection + mappings. + - - - - - - - - - - - - - - - - - - - - - - - - - + auto-import (optional - defaults to + true): specifies whether we can use + unqualified class names of classes in this mapping in the query + language. + + + + package (optional): specifies a package + prefix to use for unqualified class names in the mapping + document. + + + + + If you have two persistent classes with the same unqualified + name, you should set auto-import="false". An + exception will result if you attempt to assign two classes to the same + "imported" name. + + The hibernate-mapping element allows you to + nest several persistent <class> mappings, as + shown above. It is, however, good practice (and expected by some + tools) to map only a single persistent class, or a single class + hierarchy, in one mapping file and name it after the persistent + superclass. For example, Cat.hbm.xml, + Dog.hbm.xml, or if using inheritance, + Animal.hbm.xml. +
+
+ +
+ Class + + You can declare a persistent class using the + class element. For example: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <class name="ClassName" table="tableName" discriminator-value="discriminator_value" @@ -333,1000 +447,1003 @@ subselect="SQL expression" abstract="true|false" node="element-name" -/>]]> - - - - name (optional): the fully qualified Java class name of the - persistent class or interface. If this attribute is missing, it is assumed - that the mapping is for a non-POJO entity. - - - - - table (optional - defaults to the unqualified class name): the - name of its database table. - - - - - discriminator-value (optional - 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 - that instances of the class are (not) mutable. - - - - - schema (optional): overrides the schema name specified by - the root <hibernate-mapping> element. - - - - - catalog (optional): overrides the catalog name specified by - the root <hibernate-mapping> element. - - - - - proxy (optional): specifies an interface to use for lazy - initializing proxies. You can specify the name of the class itself. - - - - - dynamic-update (optional - defaults to false): - specifies that UPDATE SQL should be generated at runtime and - can contain only those columns whose values have changed. - - - - - dynamic-insert (optional - defaults to false): - specifies that INSERT SQL should be generated at runtime and - contain only the columns whose values are not null. - - - - - select-before-update (optional - defaults to false): - specifies that Hibernate should never perform an SQL UPDATE - unless it is certain that an object is actually modified. Only - when a transient object has been associated with a new session using update(), - will Hibernate perform an extra SQL SELECT to determine - if an UPDATE is actually required. - - - - - polymorphism (optional - defaults to implicit): - determines whether implicit or explicit query polymorphism is used. - - - - - where (optional): specifies an arbitrary SQL WHERE - condition to be used when retrieving objects of this class. - - - - - persister (optional): specifies a custom ClassPersister. - - - - - batch-size (optional - defaults to 1): specifies a "batch size" - for fetching instances of this class by identifier. - - - - - optimistic-lock (optional - defaults to version): - determines the optimistic locking strategy. - - - - - lazy (optional): lazy fetching can be disabled by setting - lazy="false". - - - - - entity-name (optional - defaults to the class name): Hibernate3 - allows a class to be mapped multiple times, potentially to different tables. - It also allows entity mappings that are represented by Maps or XML at the Java level. - In these cases, you should provide an explicit arbitrary name for the entity. See - and - for more information. - - - - - check (optional): an SQL expression used to generate a multi-row - check constraint for automatic schema generation. - - - - - 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 been 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. This is useful if you want to have a view instead of a base table. - See below for more information. - - - - - abstract (optional): is used to mark abstract superclasses in - <union-subclass> hierarchies. - - - - +/> - - It is acceptable for the named persistent class to be an interface. You can - declare implementing classes of that interface using the <subclass> - element. You can persist any static inner class. Specify the - class name using the standard form i.e. e.g.Foo$Bar. - + + + name (optional): the fully qualified Java + class name of the persistent class or interface. If this attribute + is missing, it is assumed that the mapping is for a non-POJO + entity. + - - Immutable classes, mutable="false", cannot be updated or deleted by the - application. This allows Hibernate to make some minor performance optimizations. - + + table (optional - defaults to the + unqualified class name): the name of its database table. + - - The optional proxy attribute enables lazy initialization of persistent - instances of the class. Hibernate will initially return CGLIB proxies that implement - the named interface. The persistent object will load when a method of the - proxy is invoked. See "Initializing collections and proxies" below. - + + discriminator-value (optional - defaults + to the class name): a value that distinguishes individual + subclasses that is used for polymorphic behavior. Acceptable + values include null and not + null. + - Implicit polymorphism means that instances of the class will be returned - by a query that names any superclass or implemented interface or class, and that instances - of any subclass of the class will be returned by a query that names the class itself. - Explicit polymorphism means that class instances will be returned only - by queries that explicitly name that class. Queries that name the class will return - only instances of subclasses mapped inside this <class> declaration - as a <subclass> or <joined-subclass>. For - most purposes, the default polymorphism="implicit" 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. - + + mutable (optional - defaults to + true): specifies that instances of the class + are (not) mutable. + - - The persister attribute lets you customize the persistence strategy used for - 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, for example, persistence via - stored procedure calls, serialization to flat files or LDAP. See - org.hibernate.test.CustomPersister for a simple example of "persistence" - to a Hashtable. - + + schema (optional): overrides the schema + name specified by the root + <hibernate-mapping> element. + - - 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. - Although these settings can increase performance in some cases, they can actually decrease - performance in others. - + + catalog (optional): overrides the catalog + name specified by the root + <hibernate-mapping> element. + - - Use of select-before-update will usually decrease performance. It is - useful to prevent a database update trigger being called unnecessarily if you reattach a - graph of detached instances to a Session. - + + proxy (optional): specifies an interface + to use for lazy initializing proxies. You can specify the name of + the class itself. + - - If you enable dynamic-update, you will have a choice of optimistic - locking strategies: - - - - - version: check the version/timestamp columns - - - - - all: check all columns - - - - - dirty: check the changed columns, allowing some concurrent updates - - - - - none: do not use optimistic locking - - - - - It is strongly recommended that you use version/timestamp - columns for optimistic locking with Hibernate. - This strategy optimizes performance and correctly handles modifications - made to detached instances (i.e. when Session.merge() is used). - + + dynamic-update (optional - defaults to + false): specifies that + UPDATE SQL should be generated at runtime and + can contain only those columns whose values have changed. + - - There is no difference between a view and a base table for a Hibernate mapping. - This is transparent at the database level, although some DBMS do not support - views properly, especially with updates. Sometimes you want 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 expression: - + + dynamic-insert (optional - defaults to + false): specifies that + INSERT SQL should be generated at runtime and + contain only the columns whose values are not null. + - - + + select-before-update (optional - defaults + to false): specifies that Hibernate should + never perform an SQL + UPDATE unless it is certain that an object is + actually modified. Only when a transient object has been + associated with a new session using update(), + will Hibernate perform an extra SQL SELECT to + determine if an UPDATE is actually + required. + + + + polymorphism (optional - defaults to + implicit): determines whether implicit or + explicit query polymorphism is used. + + + + where (optional): specifies an arbitrary + SQL WHERE condition to be used when retrieving + objects of this class. + + + + persister (optional): specifies a custom + ClassPersister. + + + + batch-size (optional - defaults to + 1): specifies a "batch size" for fetching + instances of this class by identifier. + + + + optimistic-lock (optional - defaults to + version): determines the optimistic locking + strategy. + + + + lazy (optional): lazy fetching can be + disabled by setting lazy="false". + + + + entity-name (optional - defaults to the + class name): Hibernate3 allows a class to be mapped multiple + times, potentially to different tables. It also allows entity + mappings that are represented by Maps or XML at the Java level. In + these cases, you should provide an explicit arbitrary name for the + entity. See + and for more information. + + + + check (optional): an SQL expression used + to generate a multi-row check constraint for + automatic schema generation. + + + + 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 been 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. This is useful if + you want to have a view instead of a base table. See below for + more information. + + + + abstract (optional): is used to mark + abstract superclasses in <union-subclass> + hierarchies. + + + + + It is acceptable for the named persistent class to be an + interface. You can declare implementing classes of that interface using + the <subclass> element. You can persist any + static inner class. Specify the class name using + the standard form i.e. e.g.Foo$Bar. + + Immutable classes, mutable="false", cannot be + updated or deleted by the application. This allows Hibernate to make + some minor performance optimizations. + + The optional proxy attribute enables lazy + initialization of persistent instances of the class. Hibernate will + initially return CGLIB proxies that implement the named interface. The + persistent object will load when a method of the proxy is invoked. See + "Initializing collections and proxies" below. + + Implicit polymorphism means that instances of + the class will be returned by a query that names any superclass or + implemented interface or class, and that instances of any subclass of + the class will be returned by a query that names the class itself. + Explicit polymorphism means that class instances + will be returned only by queries that explicitly name that class. + Queries that name the class will return only instances of subclasses + mapped inside this <class> declaration as a + <subclass> or + <joined-subclass>. For most purposes, the + default polymorphism="implicit" 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. + + The persister attribute lets you customize the + persistence strategy used for 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, for example, persistence via stored procedure calls, + serialization to flat files or LDAP. See + org.hibernate.test.CustomPersister for a simple + example of "persistence" to a Hashtable. + + 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. Although these + settings can increase performance in some cases, they can actually + decrease performance in others. + + Use of select-before-update will usually + decrease performance. It is useful to prevent a database update trigger + being called unnecessarily if you reattach a graph of detached instances + to a Session. + + If you enable dynamic-update, you will have a + choice of optimistic locking strategies: + + + + version: check the version/timestamp + columns + + + + all: check all columns + + + + dirty: check the changed columns, allowing + some concurrent updates + + + + none: do not use optimistic locking + + + + It is strongly recommended that you use + version/timestamp columns for optimistic locking with Hibernate. This + strategy optimizes performance and correctly handles modifications made + to detached instances (i.e. when Session.merge() is + used). + + There is no difference between a view and a base table for a + Hibernate mapping. This is transparent at the database level, although + some DBMS do not support views properly, especially with updates. + Sometimes you want 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 + expression: + + <class name="Summary"> + <subselect> select item.name, max(bid.amount), count(*) from item join bid on bid.item_id = item.id group by item.name - - - - + </subselect> + <synchronize table="item"/> + <synchronize table="bid"/> + <id name="name"/> ... -]]> +</class> - - Declare the tables to synchronize this entity with, ensuring that auto-flush happens - correctly and that queries against the derived entity do not return stale data. - The <subselect> is available both as an attribute and - a nested mapping element. - + Declare the tables to synchronize this entity with, ensuring that + auto-flush happens correctly and that queries against the derived entity + do not return stale data. The <subselect> is + available both as an attribute and a nested mapping element. +
-
+
+ id -
- id + Mapped classes must declare the primary key + column of the database table. Most classes will also have a + JavaBeans-style property holding the unique identifier of an instance. + The <id> element defines the mapping from that + property to the primary key column. - - Mapped classes must declare the primary key column of the database - table. Most classes will also have a JavaBeans-style property holding the unique identifier - of an instance. The <id> element defines the mapping from that - property to the primary key column. - + + + - - - - - - - - - + + + + + + + + + <id name="propertyName" type="typename" column="column_name" unsaved-value="null|any|none|undefined|id_value" - access="field|property|ClassName"> + access="field|property|ClassName"> node="element-name|@attribute-name|element/@attribute|." - -]]> - - - - name (optional): the name of the identifier property. - - - - - type (optional): a name that indicates the Hibernate type. - - - - - column (optional - defaults to the property name): the - name of the primary key column. - - - - - unsaved-value (optional - defaults to a "sensible" value): - an identifier property value that indicates an instance is newly instantiated - (unsaved), distinguishing it from detached instances that were saved or loaded - in a previous session. - - - - - access (optional - defaults to property): the - strategy Hibernate should use for accessing the property value. - - - - + <generator class="generatorClass"/> +</id> - - If the name attribute is missing, it is assumed that the class has no - identifier property. - + + + name (optional): the name of the + identifier property. + - - The unsaved-value attribute is almost never needed in Hibernate3. - + + type (optional): a name that indicates + the Hibernate type. + - - There is an alternative <composite-id> declaration that allows access to - legacy data with composite keys. Its use is strongly discouraged for anything else. - + + column (optional - defaults to the + property name): the name of the primary key column. + -
- Generator + + unsaved-value (optional - defaults to a + "sensible" value): an identifier property value that indicates an + instance is newly instantiated (unsaved), distinguishing it from + detached instances that were saved or loaded in a previous + session. + - - The optional <generator> child element names a Java class used - to generate unique identifiers for instances of the persistent class. If any parameters - are required to configure or initialize the generator instance, they are passed using the - <param> element. - + + access (optional - defaults to + property): the strategy Hibernate should use + for accessing the property value. + + + - - - uid_table - next_hi_value_column - -]]> + If the name attribute is missing, it is assumed + that the class has no identifier property. - - All generators implement the interface org.hibernate.id.IdentifierGenerator. - This is a very simple interface. Some applications can choose to provide their own specialized - implementations, however, Hibernate provides a range of built-in implementations. The shortcut - names for the built-in generators are as follows: + The unsaved-value attribute is almost never + needed in Hibernate3. - - - increment - - - generates identifiers of type long, short or - int that are unique only when no other process is inserting data - into the same table. - Do not use in a cluster. - - - - - identity - - - supports identity columns in DB2, MySQL, MS SQL Server, Sybase and - HypersonicSQL. The returned identifier is of type long, - short or int. - - - - - sequence - - - uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator - in Interbase. The returned identifier is of type long, - short or int - - - - - hilo - - - uses a hi/lo algorithm to efficiently generate identifiers of - type long, short or int, - given a table and column (by default hibernate_unique_key and - next_hi respectively) as a source of hi values. The hi/lo - algorithm generates identifiers that are unique only for a particular database. - - - - - seqhilo - - - uses a hi/lo algorithm to efficiently generate identifiers of type - long, short or int, - given a named database sequence. - - - - - uuid - - - 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 32 hexadecimal digits in length. - - - - - guid - - - uses a database-generated GUID string on MS SQL Server and MySQL. - - - - - native - - - selects identity, sequence or - hilo depending upon the capabilities of the - underlying database. - - - - - assigned - - - lets the application assign an identifier to the object before - save() is called. This is the default strategy - if no <generator> element is specified. - - - - - select - - - retrieves a primary key, assigned by a database trigger, by selecting - the row by some unique key and retrieving the primary key value. - - - - - foreign - - - uses the identifier of another associated object. It is usually used in conjunction - with a <one-to-one> primary key association. - - - - - sequence-identity - - - a specialized sequence generation strategy that utilizes a - database sequence for the actual value generation, but combines - this with JDBC3 getGeneratedKeys to return the generated - identifier value as part of the insert statement execution. This - strategy is only supported on Oracle 10g drivers - targeted for JDK 1.4. Comments on these insert statements - are disabled due to a bug in the Oracle drivers. - - - - + There is an alternative <composite-id> + declaration that allows access to legacy data with composite keys. Its + use is strongly discouraged for anything else. - -
+
+ Generator -
- Hi/lo algorithm - - The hilo and seqhilo generators provide two alternate - implementations of the hi/lo algorithm. The - first implementation requires a "special" database table to hold the next available "hi" value. - Where supported, the second uses an Oracle-style sequence. - + The optional <generator> child element + names a Java class used to generate unique identifiers for instances + of the persistent class. If any parameters are required to configure + or initialize the generator instance, they are passed using the + <param> element. - - - hi_value - next_value - 100 - -]]> + <id name="id" type="long" column="cat_id"> + <generator class="org.hibernate.id.TableHiLoGenerator"> + <param name="table">uid_table</param> + <param name="column">next_hi_value_column</param> + </generator> +</id> - - - hi_value - 100 - -]]> + All generators implement the interface + org.hibernate.id.IdentifierGenerator. This is a + very simple interface. Some applications can choose to provide their + own specialized implementations, however, Hibernate provides a range + of built-in implementations. The shortcut names for the built-in + generators are as follows: + + increment - - Unfortunately, you cannot use hilo when supplying your own - Connection to Hibernate. When Hibernate uses an application - server datasource to obtain connections enlisted with JTA, you must configure - the hibernate.transaction.manager_lookup_class. - -
+ + generates identifiers of type long, + short or int that are + unique only when no other process is inserting data into the + same table. Do not use in a + cluster. + + -
- UUID algorithm - - The UUID contains: IP address, startup time of the JVM that is accurate to a quarter - second, system time and a counter value that is unique within the JVM. It is not - possible to obtain a MAC address or memory address from Java code, so this is - the best option without using JNI. - -
+ + identity -
- Identity columns and sequences - - For databases that support identity columns (DB2, MySQL, Sybase, MS SQL), you - can use identity key generation. For 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: - + + supports identity columns in DB2, MySQL, MS SQL Server, + Sybase and HypersonicSQL. The returned identifier is of type + long, short or + int. + + - - - person_id_sequence - -]]> + + sequence - - -]]> + + uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, + McKoi or a generator in Interbase. The returned identifier is + of type long, short or + int + + - - For cross-platform development, the native strategy will, depending on the capabilities of the underlying database, - choose from the identity, sequence and - hilo strategies. - -
+ + hilo -
- Assigned identifiers - - If you want the application to assign identifiers, as opposed to having - Hibernate generate them, you can use the assigned generator. - This special generator uses the identifier value already assigned to the - object's identifier property. The generator is used when the primary key - is a natural key instead of a surrogate key. This is the default behavior - if you do not specify a <generator> element. - + + uses a hi/lo algorithm to efficiently generate + identifiers of type long, + short or int, given a + table and column (by default + hibernate_unique_key and + next_hi respectively) as a source of hi + values. The hi/lo algorithm generates identifiers that are + unique only for a particular database. + + - - The assigned generator makes Hibernate use - unsaved-value="undefined". This forces Hibernate to go to - the database to determine if an instance is transient or detached, unless - there is a version or timestamp property, or you define - Interceptor.isUnsaved(). - -
+ + seqhilo -
- Primary keys assigned by triggers - - Hibernate does not generate DDL with triggers. It is for legacy schemas only. - + + uses a hi/lo algorithm to efficiently generate + identifiers of type long, + short or int, given a + named database sequence. + + - - - socialSecurityNumber - -]]> + + uuid - - In the above example, there is a unique valued property named - 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. - + + 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 32 hexadecimal + digits in length. + + -
+ + guid -
+ + uses a database-generated GUID string on MS SQL Server + and MySQL. + + -
- Enhanced identifier generators + + native - - Starting with release 3.2.3, there are 2 new generators which represent a re-thinking of 2 different - aspects of identifier generation. The first aspect is database portability; the second is optimization - Optimization means that you do not have 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 named generators described above, starting - in 3.3.x. However, they are included in the current releases and can be referenced by FQN. - + + selects identity, + sequence or hilo + depending upon the capabilities of the underlying + database. + + - - The first of these new generators is org.hibernate.id.enhanced.SequenceStyleGenerator - 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 in applications eyeing portability. - org.hibernate.id.enhanced.SequenceStyleGenerator, however, achieves portability in - a different manner. It chooses between a table or a sequence 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 sequence-based storage have the same exact - semantic. In fact, sequences are exactly what Hibernate tries to emulate with its table-based - generators. This generator has a number of configuration parameters: - - - - sequence_name (optional, defaults to hibernate_sequence): - the name of the sequence or table to be used. - - - - - initial_value (optional, defaults to 1): the initial - value to be retrieved from the sequence/table. In sequence creation terms, this is analogous - to the clause typically named "STARTS WITH". - - - - - increment_size (optional - defaults to 1): the value by - which subsequent calls to the sequence/table should differ. In sequence creation terms, this - is analogous to the clause typically named "INCREMENT BY". - - - - - force_table_use (optional - defaults to false): should - we force the use of a table as the backing structure even though the dialect might support - sequence? - - - - - value_column (optional - defaults 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 - defaults to none): - See - - - - - - The second of these new generators is org.hibernate.id.enhanced.TableGenerator, which - is intended, firstly, as a replacement for the table generator, even though it actually - functions much more like org.hibernate.id.MultipleHiLoPerTableGenerator, and secondly, - as a re-implementation of org.hibernate.id.MultipleHiLoPerTableGenerator that utilizes the - notion of pluggable optimizers. Essentially this generator defines a table capable of holding - a number of different increment values simultaneously by using multiple distinctly keyed rows. This - generator has a number of configuration parameters: - - - - table_name (optional - defaults 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 that is used to hold the value. - - - - - segment_column_name (optional - defaults to sequence_name): - the name of the column on the table that is used to hold the "segment key". This is the - value which identifies which increment value to use. - - - - - segment_value (optional - defaults to default): - The "segment key" value for the segment from which we want to pull increment values for - this generator. - - - - - segment_value_length (optional - defaults to 255): - Used for schema generation; the column size to create this segment key column. - - - - - initial_value (optional - defaults to 1): - The initial value to be retrieved from the table. - - - - - increment_size (optional - defaults to 1): - The value by which subsequent calls to the table should differ. - - - - - optimizer (optional - defaults to ): - See - - - - -
+ + assigned -
- Identifier generator optimization - - For identifier generators that store values in the database, it is inefficient for them to hit the - database on each and every call to generate a new identifier value. Instead, you can - group a bunch of them in memory and only hit the database when you have exhausted your in-memory - value group. This is the role of the pluggable optimizers. Currently only the two enhanced generators - ( support this operation. - - - - 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 algorithm around the database retrieved values. The - values from the database for this optimizer are expected to be sequential. The values - retrieved from the database structure for this optimizer indicates the "group number". The - increment_size is multiplied by that value in memory to define a group - "hi value". - - - - - 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 the database structure rather than a sequential - value in combination with an in-memory grouping algorithm. Here, increment_size - refers to the values coming from the database. - - - - -
+ + lets the application assign an identifier to the object + before save() is called. This is the + default strategy if no <generator> + element is specified. + +
-
- composite-id + + select - + retrieves a primary key, assigned by a database trigger, + by selecting the row by some unique key and retrieving the + primary key value. + + + + + foreign + + + uses the identifier of another associated object. It is + usually used in conjunction with a + <one-to-one> primary key + association. + + + + + sequence-identity + + + a specialized sequence generation strategy that utilizes + a database sequence for the actual value generation, but + combines this with JDBC3 getGeneratedKeys to return the + generated identifier value as part of the insert statement + execution. This strategy is only supported on Oracle 10g + drivers targeted for JDK 1.4. Comments on these insert + statements are disabled due to a bug in the Oracle + drivers. + + + +
+ +
+ Hi/lo algorithm + + The hilo and seqhilo + generators provide two alternate implementations of the hi/lo + algorithm. The first implementation requires a "special" database + table to hold the next available "hi" value. Where supported, the + second uses an Oracle-style sequence. + + <id name="id" type="long" column="cat_id"> + <generator class="hilo"> + <param name="table">hi_value</param> + <param name="column">next_value</param> + <param name="max_lo">100</param> + </generator> +</id> + + <id name="id" type="long" column="cat_id"> + <generator class="seqhilo"> + <param name="sequence">hi_value</param> + <param name="max_lo">100</param> + </generator> +</id> + + Unfortunately, you cannot use hilo when + supplying your own Connection to Hibernate. When + Hibernate uses an application server datasource to obtain connections + enlisted with JTA, you must configure the + hibernate.transaction.manager_lookup_class. +
+ +
+ UUID algorithm + + The UUID contains: IP address, startup time of the JVM that is + accurate to a quarter second, system time and a counter value that is + unique within the JVM. It is not possible to obtain a MAC address or + memory address from Java code, so this is the best option without + using JNI. +
+ +
+ Identity columns and sequences + + For databases that support identity columns (DB2, MySQL, Sybase, + MS SQL), you can use identity key generation. For + 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: + + <id name="id" type="long" column="person_id"> + <generator class="sequence"> + <param name="sequence">person_id_sequence</param> + </generator> +</id> + + <id name="id" type="long" column="person_id" unsaved-value="0"> + <generator class="identity"/> +</id> + + For cross-platform development, the native + strategy will, depending on the capabilities of the underlying + database, choose from the identity, + sequence and hilo + strategies. +
+ +
+ Assigned identifiers + + If you want the application to assign identifiers, as opposed to + having Hibernate generate them, you can use the + assigned generator. This special generator uses the + identifier value already assigned to the object's identifier property. + The generator is used when the primary key is a natural key instead of + a surrogate key. This is the default behavior if you do not specify a + <generator> element. + + The assigned generator makes Hibernate use + unsaved-value="undefined". This forces Hibernate to + go to the database to determine if an instance is transient or + detached, unless there is a version or timestamp property, or you + define Interceptor.isUnsaved(). +
+ +
+ Primary keys assigned by triggers + + Hibernate does not generate DDL with triggers. It is for legacy + schemas only. + + <id name="id" type="long" column="person_id"> + <generator class="select"> + <param name="key">socialSecurityNumber</param> + </generator> +</id> + + In the above example, there is a unique valued property named + 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. +
+
+ +
+ Enhanced identifier generators + + Starting with release 3.2.3, there are 2 new generators which + represent a re-thinking of 2 different aspects of identifier generation. + The first aspect is database portability; the second is optimization + Optimization means that you do not have 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 named generators described + above, starting in 3.3.x. However, they are included in the current + releases and can be referenced by FQN. + + The first of these new generators is + org.hibernate.id.enhanced.SequenceStyleGenerator + 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 in applications + eyeing portability. + org.hibernate.id.enhanced.SequenceStyleGenerator, + however, achieves portability in a different manner. It chooses between + a table or a sequence 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 + sequence-based storage have the same exact semantic. In fact, sequences + are exactly what Hibernate tries to emulate with its table-based + generators. This generator has a number of configuration parameters: + + + sequence_name (optional, defaults to + hibernate_sequence): the name of the sequence + or table to be used. + + + + initial_value (optional, defaults to + 1): the initial value to be retrieved from the + sequence/table. In sequence creation terms, this is analogous to + the clause typically named "STARTS WITH". + + + + increment_size (optional - defaults to + 1): the value by which subsequent calls to the + sequence/table should differ. In sequence creation terms, this is + analogous to the clause typically named "INCREMENT BY". + + + + force_table_use (optional - defaults to + false): should we force the use of a table as + the backing structure even though the dialect might support + sequence? + + + + value_column (optional - defaults 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 - defaults to + none): See + + + + The second of these new generators is + org.hibernate.id.enhanced.TableGenerator, which is + intended, firstly, as a replacement for the table + generator, even though it actually functions much more like + org.hibernate.id.MultipleHiLoPerTableGenerator, and + secondly, as a re-implementation of + org.hibernate.id.MultipleHiLoPerTableGenerator that + utilizes the notion of pluggable optimizers. Essentially this generator + defines a table capable of holding a number of different increment + values simultaneously by using multiple distinctly keyed rows. This + generator has a number of configuration parameters: + + table_name (optional - defaults 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 + that is used to hold the value. + + + + segment_column_name (optional - defaults + to sequence_name): the name of the column on + the table that is used to hold the "segment key". This is the + value which identifies which increment value to use. + + + + segment_value (optional - defaults to + default): The "segment key" value for the + segment from which we want to pull increment values for this + generator. + + + + segment_value_length (optional - defaults + to 255): Used for schema generation; the column + size to create this segment key column. + + + + initial_value (optional - defaults to + 1): The initial value to be retrieved from the + table. + + + + increment_size (optional - defaults to + 1): The value by which subsequent calls to the + table should differ. + + + + optimizer (optional - defaults to + ): See + + +
+ +
+ Identifier generator optimization + + For identifier generators that store values in the database, it is + inefficient for them to hit the database on each and every call to + generate a new identifier value. Instead, you can group a bunch of them + in memory and only hit the database when you have exhausted your + in-memory value group. This is the role of the pluggable optimizers. + Currently only the two enhanced generators ( support this operation. + + + 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 algorithm around + the database retrieved values. The values from the database for + this optimizer are expected to be sequential. The values retrieved + from the database structure for this optimizer indicates the + "group number". The increment_size is + multiplied by that value in memory to define a group "hi + value". + + + + 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 the database structure + rather than a sequential value in combination with an in-memory + grouping algorithm. Here, increment_size refers + to the values coming from the database. + + +
+ +
+ composite-id + + <composite-id name="propertyName" class="ClassName" mapped="true|false" - access="field|property|ClassName"> + access="field|property|ClassName"> node="element-name|." - - + <key-property name="propertyName" type="typename" column="column_name"/> + <key-many-to-one name="propertyName class="ClassName" column="column_name"/> ...... -]]> +</composite-id> - - A table with a composite key can be mapped with multiple properties of the class - as identifier properties. The <composite-id> element - accepts <key-property> property mappings and - <key-many-to-one> mappings as child elements. - + A table with a composite key can be mapped with multiple + properties of the class as identifier properties. The + <composite-id> element accepts + <key-property> property mappings and + <key-many-to-one> mappings as child + elements. - - - -]]> + <composite-id> + <key-property name="medicareNumber"/> + <key-property name="dependent"/> +</composite-id> - - The persistent class must override equals() - and hashCode() to implement composite identifier equality. It must - also implement Serializable. - + The persistent class must override + equals() and hashCode() to + implement composite identifier equality. It must also implement + Serializable. - - Unfortunately, this approach means that a persistent object - is its own identifier. There is no convenient "handle" other than the object itself. - You must instantiate an instance of the persistent class itself and populate its - identifier properties before you can load() the persistent state - associated with a composite key. We call this approach an embedded - composite identifier, and discourage it for serious applications. - + Unfortunately, this approach means that a persistent object is its + own identifier. There is no convenient "handle" other than the object + itself. You must instantiate an instance of the persistent class itself + and populate its identifier properties before you can + load() the persistent state associated with a + composite key. We call this approach an embedded + composite identifier, and discourage it for serious applications. - - A second approach is what we call a mapped composite identifier, - where the identifier properties named inside the <composite-id> - element are duplicated on both the persistent class and a separate identifier class. - + A second approach is what we call a mapped + composite identifier, where the identifier properties named inside the + <composite-id> element are duplicated on both + the persistent class and a separate identifier class. - - - -]]> + <composite-id class="MedicareId" mapped="true"> + <key-property name="medicareNumber"/> + <key-property name="dependent"/> +</composite-id> - - In this example, both the composite identifier class, MedicareId, - and the entity class itself have properties named medicareNumber - and dependent. The identifier class must override - equals() and hashCode() and implement - Serializable. The main disadvantage of this approach is - code duplication. - + In this example, both the composite identifier class, + MedicareId, and the entity class itself have + properties named medicareNumber and + dependent. The identifier class must override + equals() and hashCode() and + implement Serializable. The main disadvantage of this + approach is code duplication. - - The following attributes are used to specify a mapped composite identifier: - + The following attributes are used to specify a mapped composite + identifier: - - - - mapped (optional - defaults to false): - indicates that a mapped composite identifier is used, and that the contained - property mappings refer to both the entity class and the composite identifier - class. - - - - - class (optional - but required for a mapped composite identifier): - the class used as a composite identifier. - - - + + + mapped (optional - defaults to + false): indicates that a mapped composite + identifier is used, and that the contained property mappings refer + to both the entity class and the composite identifier class. + - - We will describe a third, even more convenient approach, where the composite identifier - is implemented as a component class in . The - attributes described below apply only to this alternative approach: - + + class (optional - but required for a mapped + composite identifier): the class used as a composite + identifier. + + - - - - name (optional - required for this 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 uses for accessing the property value. - - - - - class (optional - defaults to the property type determined by - reflection): the component class used as a composite identifier. Please see the next section for more information. - - - + We will describe a third, even more convenient approach, where the + composite identifier is implemented as a component class in . The attributes described below + apply only to this alternative approach: - - The third approach, an identifier component, is recommended - for almost all applications. - + + + name (optional - required for this + 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 uses for + accessing the property value. + -
- Discriminator + + class (optional - defaults to the property + type determined by reflection): the component class used as a + composite identifier. Please see the next section for more + information. + + - - The <discriminator> element is required for polymorphic persistence - using the table-per-class-hierarchy mapping strategy. It declares a discriminator column of the - table. The discriminator column contains marker values that tell the persistence layer what - subclass to instantiate for a particular row. A restricted set of types can be used: - string, character, integer, - byte, short, boolean, - yes_no, true_false. - + The third approach, an identifier component, + is recommended for almost all applications. +
- - - - - - - - - + Discriminator + + The <discriminator> element is required + for polymorphic persistence using the table-per-class-hierarchy mapping + strategy. It declares a discriminator column of the table. The + discriminator column contains marker values that tell the persistence + layer what subclass to instantiate for a particular row. A restricted + set of types can be used: string, + character, integer, + byte, short, + boolean, yes_no, + true_false. + + + + + + + + + + + + + + + <discriminator column="discriminator_column" type="discriminator_type" force="true|false" insert="true|false" formula="arbitrary sql expression" -/>]]> - - - - column (optional - defaults to class): the - name of the discriminator column. - - - - - type (optional - defaults to string): a - name that indicates the Hibernate type - - - - - force (optional - defaults to false): - "forces" Hibernate to specify the allowed discriminator values, even when retrieving - all instances of the root class. - - - - - insert (optional - defaults to true): - set this to false if your discriminator column is also part - of a mapped composite identifier. It tells Hibernate not to include the column - in SQL INSERTs. - - - - - formula (optional): an arbitrary SQL expression that is - executed when a type has to be evaluated. It allows content-based discrimination. - - - - +/> - - Actual values of the discriminator column are specified by the - discriminator-value attribute of the <class> and - <subclass> elements. - + + + column (optional - defaults to + class): the name of the discriminator + column. + - - The force attribute is only useful if the table contains rows with - "extra" discriminator values that are not mapped to a persistent class. This will not - usually be the case. - + + type (optional - defaults to + string): a name that indicates the Hibernate + type + - - The formula attribute allows you to declare an arbitrary SQL expression - that will be used to evaluate the type of a row. For example: - + + force (optional - defaults to + false): "forces" Hibernate to specify the + allowed discriminator values, even when retrieving all instances + of the root class. + - + insert (optional - defaults to + true): set this to false if + your discriminator column is also part of a mapped composite + identifier. It tells Hibernate not to include the column in SQL + INSERTs. + + + + formula (optional): an arbitrary SQL + expression that is executed when a type has to be evaluated. It + allows content-based discrimination. + + + + + Actual values of the discriminator column are specified by the + discriminator-value attribute of the + <class> and <subclass> + elements. + + The force attribute is only useful if the table + contains rows with "extra" discriminator values that are not mapped to a + persistent class. This will not usually be the case. + + The formula attribute allows you to declare an + arbitrary SQL expression that will be used to evaluate the type of a + row. For example: + + <discriminator formula="case when CLASS_TYPE in ('a', 'b', 'c') then 0 else 1 end" - type="integer"/>]]> + type="integer"/> +
-
+
+ Version (optional) -
- Version (optional) + The <version> element is optional and + indicates that the table contains versioned data. This is particularly + useful if you plan to use long transactions. See + below for more information: - - The <version> element is optional and indicates that - the table contains versioned data. This is particularly useful if you plan to - use long transactions. See below for more information: - + + + - - - - - - - - - - - + + + + + + + + + + + + + <version column="version_column" name="propertyName" type="typename" @@ -1335,93 +1452,99 @@ generated="never|always" insert="true|false" node="element-name|@attribute-name|element/@attribute|." -/>]]> - - - - column (optional - defaults to the property name): the name - of the column holding the version number. - - - - - name: the name of a property of the persistent class. - - - - - type (optional - defaults to integer): - the type of the version number. - - - - - access (optional - defaults to property): the - strategy Hibernate uses to access the property value. - - - - - unsaved-value (optional - defaults to undefined): - a version property value that indicates that an instance is newly instantiated - (unsaved), distinguishing it from detached instances that were saved or loaded - in a previous session. Undefined specifies that the identifier - property value should be used. - - - - - generated (optional - defaults to never): - 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. - It can be set to false if the database column - is defined with a default value of 0. - - - - +/> - - Version numbers can be of Hibernate type long, integer, - short, timestamp or calendar. - + + + column (optional - defaults to the + property name): the name of the column holding the version + number. + - - 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 transient, - irrespective of what other unsaved-value strategies are specified. - Declaring a nullable version or timestamp property is an easy way to avoid - problems with transitive reattachment in Hibernate. It is especially useful for people - using assigned identifiers or composite keys. - -
+ + name: the name of a property of the + persistent class. + -
- Timestamp (optional) + + type (optional - defaults to + integer): the type of the version + number. + - - The optional <timestamp> element indicates that the table contains - timestamped data. This provides an alternative to versioning. Timestamps are - a less safe implementation of optimistic locking. However, sometimes the application might - use the timestamps in other ways. - + + access (optional - defaults to + property): the strategy Hibernate uses to + access the property value. + - - - - - - - - - - + unsaved-value (optional - defaults to + undefined): a version property value that + indicates that an instance is newly instantiated (unsaved), + distinguishing it from detached instances that were saved or + loaded in a previous session. Undefined + specifies that the identifier property value should be + used. + + + + generated (optional - defaults to + never): 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. It can be set to + false if the database column is defined with a + default value of 0. + + + + + 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. Hibernate will detect any instance with a null + version or timestamp as transient, irrespective of what other + unsaved-value strategies are specified. + Declaring a nullable version or timestamp property is an easy + way to avoid problems with transitive reattachment in Hibernate. It is + especially useful for people using assigned identifiers or composite + keys. +
+ +
+ Timestamp (optional) + + The optional <timestamp> element + indicates that the table contains timestamped data. This provides an + alternative to versioning. Timestamps are a less safe implementation of + optimistic locking. However, sometimes the application might use the + timestamps in other ways. + + + + + + + + + + + + + + + + + <timestamp column="timestamp_column" name="propertyName" access="field|property|ClassName" @@ -1429,98 +1552,104 @@ source="vm|db" generated="never|always" node="element-name|@attribute-name|element/@attribute|." -/>]]> - - - - column (optional - defaults to the property name): the name - of a column holding the timestamp. - - - - - name: the name of a JavaBeans style property of - Java type Date or Timestamp of the - persistent class. - - - - - access (optional - defaults to property): the - strategy Hibernate uses for accessing the property value. - - - - - unsaved-value (optional - defaults to null): - a version property value that indicates that an instance is newly instantiated - (unsaved), distinguishing it from detached instances that were saved or loaded - in a previous session. Undefined specifies that the identifier - property value should be used. - - - - - source (optional - defaults to vm): - Where should Hibernate retrieve the timestamp value from? From the database, - or from the current JVM? Database-based timestamps incur an overhead because - Hibernate must hit the database in order to determine the "next value". - It is safer to use in clustered environments. Not - all Dialects are known to support the retrieval of the - database's current timestamp. Others may also be unsafe for usage - in locking due to lack of precision (Oracle 8, for example). - - - - - generated (optional - defaults to never): - specifies that this timestamp property value is actually generated by the database. - See the discussion of generated properties for more information. - - - - +/> - - - Note - - <Timestamp> is equivalent to - <version type="timestamp">. And - <timestamp source="db"> is equivalent to - <version type="dbtimestamp"> - - - -
+ + + column (optional - defaults to the + property name): the name of a column holding the timestamp. + + + name: the name of a JavaBeans style + property of Java type Date or + Timestamp of the persistent class. + -
- Property + + access (optional - defaults to + property): the strategy Hibernate uses for + accessing the property value. + - - The <property> element declares a persistent JavaBean style - property of the class. - + + unsaved-value (optional - defaults to + null): a version property value that indicates + that an instance is newly instantiated (unsaved), distinguishing + it from detached instances that were saved or loaded in a previous + session. Undefined specifies that the + identifier property value should be used. + - - - - - - - - - - - - - - - - - - + source (optional - defaults to + vm): Where should Hibernate retrieve the + timestamp value from? From the database, or from the current JVM? + Database-based timestamps incur an overhead because Hibernate must + hit the database in order to determine the "next value". It is + safer to use in clustered environments. Not all + Dialects are known to support the retrieval of + the database's current timestamp. Others may also be unsafe for + usage in locking due to lack of precision (Oracle 8, for + example). + + + + generated (optional - defaults to + never): specifies that this timestamp property + value is actually generated by the database. See the discussion of + generated properties for + more information. + + + + + + Note + + <Timestamp> is equivalent to + <version type="timestamp">. And + <timestamp source="db"> is equivalent to + <version type="dbtimestamp"> + +
+ +
+ Property + + The <property> element declares a + persistent JavaBean style property of the class. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <property name="propertyName" column="column_name" type="typename" @@ -1539,189 +1668,194 @@ length="L" precision="P" scale="S" -/>]]> - - - - name: the name of the property, with an initial lowercase - letter. - - - - - column (optional - defaults to the property name): the name - of the mapped database table column. This can also be specified by nested - <column> element(s). - - - - - type (optional): a name that indicates the Hibernate type. - - - - - 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" property whose value is initialized from some other - property that maps to the same column(s), or by a trigger or other application. - - - - - formula (optional): an SQL expression that defines the value for a - computed property. Computed properties do not have a column - mapping of their own. - - - - - access (optional - defaults to property): the - strategy Hibernate uses for accessing the property value. - - - - - lazy (optional - defaults to false): specifies - that this property should be fetched lazily when the instance variable is first - accessed. It requires build-time bytecode instrumentation. - - - - - unique (optional): enables the DDL generation of a unique - constraint for the columns. Also, allow this to be the target of - a property-ref. - - - - - not-null (optional): enables 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, it determines if a version increment should occur when - this property is dirty. - - - - - generated (optional - defaults to never): - specifies that this property value is actually generated by the database. - See the discussion of generated properties for more information. - - - - +/> - - typename could be: - + + + name: the name of the property, with an + initial lowercase letter. + - - - - The name of a Hibernate basic type: integer, string, character, - date, timestamp, float, binary, serializable, object, blob etc. - - - - - 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. - - - - - The name of a serializable Java class. - - - - - The class name of a custom type: com.illflow.type.MyCustomType etc. - - - + + column (optional - defaults to the + property name): the name of the mapped database table column. This + can also be specified by nested <column> + element(s). + - - If you do not specify a type, Hibernate will use reflection upon the named - property and guess the correct Hibernate type. Hibernate will attempt to - interpret the name of the return class of the property getter using, in order, rules 2, 3, - and 4. - In certain cases you will need the type - attribute. For example, to distinguish between Hibernate.DATE and - Hibernate.TIMESTAMP, or to specify a custom type. - + + type (optional): a name that indicates + the Hibernate type. + - - The access attribute allows you to control how Hibernate accesses - the property at runtime. By default, Hibernate will call the property get/set pair. - If you specify access="field", Hibernate will bypass the get/set - pair and access the field directly using reflection. You can specify your own - strategy for property access by naming a class that implements the interface - org.hibernate.property.PropertyAccessor. - + + 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" property whose + value is initialized from some other property that maps to the + same column(s), or by a trigger or other application. + - - A powerful feature is derived properties. These properties are by - definition read-only. The property value is computed at load 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: - + + formula (optional): an SQL expression + that defines the value for a computed + property. Computed properties do not have a column mapping of + their own. + - + access (optional - defaults to + property): the strategy Hibernate uses for + accessing the property value. + + + + lazy (optional - defaults to + false): specifies that this property should be + fetched lazily when the instance variable is first accessed. It + requires build-time bytecode instrumentation. + + + + unique (optional): enables the DDL + generation of a unique constraint for the columns. Also, allow + this to be the target of a property-ref. + + + + not-null (optional): enables 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, it determines if a version increment should occur when this + property is dirty. + + + + generated (optional - defaults to + never): specifies that this property value is + actually generated by the database. See the discussion of generated properties for more + information. + + + + + typename could be: + + + + The name of a Hibernate basic type: integer, string, + character, date, timestamp, float, binary, serializable, object, + blob etc. + + + + 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. + + + + The name of a serializable Java class. + + + + The class name of a custom type: + com.illflow.type.MyCustomType etc. + + + + If you do not specify a type, Hibernate will use reflection upon + the named property and guess the correct Hibernate type. Hibernate will + attempt to interpret the name of the return class of the property getter + using, in order, rules 2, 3, and 4. In certain cases you will need the + type attribute. For example, to distinguish between + Hibernate.DATE and + Hibernate.TIMESTAMP, or to specify a custom + type. + + The access attribute allows you to control how + Hibernate accesses the property at runtime. By default, Hibernate will + call the property get/set pair. If you specify + access="field", Hibernate will bypass the get/set + pair and access the field directly using reflection. You can specify + your own strategy for property access by naming a class that implements + the interface + org.hibernate.property.PropertyAccessor. + + A powerful feature is derived properties. These properties are by + definition read-only. The property value is computed at load 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: + + +<property name="totalPrice" formula="( SELECT SUM (li.quantity*p.price) FROM LineItem li, Product p WHERE li.productId = p.productId AND li.customerId = customerId - AND li.orderNumber = orderNumber )"/>]]> + AND li.orderNumber = orderNumber )"/> - - You can reference the entity table by not declaring an alias 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. - + You can reference the entity table by not declaring an alias 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 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. - - 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. - + + + - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <many-to-one name="propertyName" column="column_name" class="ClassName" @@ -1743,188 +1877,188 @@ index="index_name" unique_key="unique_key_id" foreign-key="foreign_key_name" -/>]]> - - - - 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). - - - - - 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. - - - - - fetch (optional - defaults to select): - chooses between outer-join fetching or sequential select fetching. - - - - - 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. - - - - - 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. - - - - - 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 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 associations are proxied. lazy="no-proxy" - specifies that the property should be fetched lazily when the instance variable - is first accessed. This requires build-time bytecode instrumentation. - lazy="false" specifies that the association will always - be eagerly fetched. - - - - - 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. - - - - - entity-name (optional): the entity name of the associated class. - - - - - formula (optional): an SQL expression 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 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 combinations of operation - names: cascade="persist,merge,evict" or - cascade="all,delete-orphan". See - for a full explanation. Note that single valued, many-to-one and - one-to-one, associations do not support orphan delete. - + + + name: the name of the property. + - - Here is an example of a typical many-to-one declaration: - + + 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. + - - 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 controls Hibernate's DDL generation with - the SchemaExport tool. - + + 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 fetching or + sequential select fetching. + - - Then the mapping for OrderItem might use: - + + 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. + - - This is not encouraged, however. - + + access (optional - defaults to + property): the strategy Hibernate uses for + accessing the property value. + - - If the referenced unique key comprises multiple properties of the associated entity, you should - map the referenced properties inside a named <properties> element. - + + 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. + - - If the referenced unique key is the property of a component, you can specify a property path: - + + 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 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 associations + are proxied. lazy="no-proxy" specifies that the + property should be fetched lazily when the instance variable is + first accessed. This requires build-time bytecode instrumentation. + lazy="false" specifies that the association + will always be eagerly fetched. + -
- One-to-one + + 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. + - - A one-to-one association to another persistent class is declared using a - one-to-one element. - + + entity-name (optional): the entity name + of the associated class. + - - - - - - - - - - - - - - + formula (optional): an SQL expression + 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 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 combinations of operation names: + cascade="persist,merge,evict" or + cascade="all,delete-orphan". See for a full explanation. Note that + single valued, many-to-one and one-to-one, associations do not support + orphan delete. + + Here is an example of a typical many-to-one + declaration: + + <many-to-one name="product" class="Product" column="PRODUCT_ID"/> + + The property-ref attribute should only be used + for mapping legacy data where a foreign key refers to a unique key of + the associated table other than the primary key. 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 controls + Hibernate's DDL generation with the SchemaExport tool. + + <property name="serialNumber" unique="true" type="string" column="SERIAL_NUMBER"/> + + Then the mapping for OrderItem might + use: + + <many-to-one name="product" property-ref="serialNumber" column="PRODUCT_SERIAL_NUMBER"/> + + This is 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 is the property of a component, you + can specify a property path: + + <many-to-one name="owner" property-ref="identity.ssn" column="OWNER_SSN"/> +
+ +
+ One-to-one + + A one-to-one association to another persistent class is declared + using a one-to-one element. + + + + + + + + + + + + + + + + + + + + + + + + + <one-to-one name="propertyName" class="ClassName" cascade="cascade_style" @@ -1938,207 +2072,202 @@ node="element-name|@attribute-name|element/@attribute|." embed-xml="true|false" foreign-key="foreign_key_name" -/>]]> - - - - name: the name of the property. - - - - - 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. - - - - - constrained (optional): specifies that a foreign key constraint - on the primary key of the mapped table and references the table of the associated - class. This option affects the order in which save() and - delete() are cascaded, and determines whether the association - can be proxied. It is also used by the schema export tool. - - - - - fetch (optional - defaults to select): - chooses between outer-join fetching 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 associated class is used. - - - - - 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 this 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. - - - - - lazy (optional - defaults to proxy): - by default, single point associations are proxied. lazy="no-proxy" - specifies that the property should be fetched lazily when the instance variable - is first accessed. It requires build-time bytecode instrumentation. - lazy="false" specifies that the association will always - be eagerly fetched. Note that if constrained="false", - proxying is impossible and Hibernate will eagerly fetch the association. - - - - - entity-name (optional): the entity name of the associated class. - - - - +/> - - There are two varieties of one-to-one associations: - - - - primary key associations - - - unique foreign key associations - - + + + name: the name of the property. + - - Primary key associations do not need an extra table column. If two rows are related by - the association, then the two table rows share the same primary key value. - To relate two objects by a primary key association, ensure that they - are assigned the same identifier value. - + + class (optional - defaults to the + property type determined by reflection): the name of the + associated class. + - - For a primary key association, add the following mappings to Employee and - Person respectively: - + + cascade (optional): specifies which + operations should be cascaded from the parent object to the + associated object. + - ]]> - ]]> + + constrained (optional): specifies that a + foreign key constraint on the primary key of the mapped table and + references the table of the associated class. This option affects + the order in which save() and + delete() are cascaded, and determines whether + the association can be proxied. It is also used by the schema + export tool. + - - 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: - + + fetch (optional - defaults to + select): chooses between outer-join fetching or + sequential select fetching. + - - - - employee - - + + 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 associated + class is used. + + + + 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 this + 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. + + + + lazy (optional - defaults to + proxy): by default, single point associations + are proxied. lazy="no-proxy" specifies that the + property should be fetched lazily when the instance variable is + first accessed. It requires build-time bytecode instrumentation. + lazy="false" specifies that the association + will always be eagerly fetched. Note that if + constrained="false", proxying is impossible and + Hibernate will eagerly fetch the association. + + + + entity-name (optional): the entity name + of the associated class. + + + + + There are two varieties of one-to-one associations: + + + + primary 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 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: + + <one-to-one name="person" class="Person"/> + + <one-to-one name="employee" class="Employee" constrained="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: + + <class name="person" table="PERSON"> + <id name="id" column="PERSON_ID"> + <generator class="foreign"> + <param name="property">employee</param> + </generator> + </id> ... - -]]> + constrained="true"/> +</class> - - A newly saved instance of Person is assigned the same primary - key value as the Employee instance referred with the employee - property of that Person. - + A newly saved instance of Person is assigned + the same primary key value as the Employee instance + 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="person" class="Person" column="PERSON_ID" unique="true"/> - - This association can be made bidirectional by adding the following to the - Person mapping: - + This association can be made bidirectional by adding the following + to the Person mapping: - ]]> + <one-to-one name="employee" class="Employee" property-ref="person"/> +
-
+
+ Natural-id -
- Natural-id - - - - + <natural-id mutable="true|false"/> + <property ... /> + <many-to-one ... /> ...... -]]> +</natural-id> - - Although we recommend the use of surrogate keys as primary keys, you should try - to identify natural keys for all entities. A natural key is a property or combination of - properties that is unique and non-null. It is also immutable. Map the - properties of the natural key inside the <natural-id> element. - Hibernate will generate the necessary unique key and nullability constraints and, as a result, your - mapping will be more self-documenting. - + Although we recommend the use of surrogate keys as primary keys, + you should try to identify natural keys for all entities. A natural key + is a property or combination of properties that is unique and non-null. + It is also immutable. Map the properties of the natural key inside the + <natural-id> element. Hibernate will generate + the necessary unique key and nullability constraints and, as a result, + your mapping will be more self-documenting. - - It is recommended that you implement equals() and - hashCode() to compare the natural key properties of the entity. - + It is recommended that you implement equals() + and hashCode() to compare the natural key properties + of the entity. - - This mapping is not intended for use with entities that have natural primary keys. - + This mapping is not intended for use with entities that have + natural primary keys. - - - - mutable (optional - defaults to false): - by default, natural identifier properties are assumed to be immutable (constant). - - - + + + mutable (optional - defaults to + false): by default, natural identifier properties + are assumed to be immutable (constant). + + +
-
+
+ Component and dynamic-component -
- Component and dynamic-component + The <component> element maps properties + of a child object to columns of the table of a parent class. Components + can, in turn, declare their own properties, components or collections. + See the "Component" examples below: - - The <component> element maps properties of a - child object to columns of the table of a parent class. Components can, in - turn, declare their own properties, components or collections. See - the "Component" examples below: - + + + - - - - - - - - - - - - + + + + + + + + + + + + + + + <component name="propertyName" class="className" insert="true|false" @@ -2148,206 +2277,194 @@ optimistic-lock="true|false" unique="true|false" node="element-name|." -> +> - - + <property ...../> + <many-to-one .... /> ........ -]]> - - - - name: the name of the property. - - - - - class (optional - defaults to the property type - determined by reflection): the name of the component (child) class. - - - - - insert: do the mapped columns appear in SQL - INSERTs? - - - - - update: do the mapped columns appear in SQL - UPDATEs? - - - - - access (optional - defaults to property): the - strategy Hibernate uses for accessing the property value. - - - - - lazy (optional - defaults to false): specifies - that this component should be fetched lazily when the instance variable is first - accessed. It requires build-time bytecode instrumentation. - - - - - optimistic-lock (optional - defaults to true): - specifies that updates to this component either do or do not require acquisition of the - optimistic lock. It determines if a version increment should occur when - this property is dirty. - - - - - unique (optional - defaults to false): - specifies that a unique constraint exists upon all mapped columns of the - component. - - - - +</component> - - The child <property> tags map properties of the - child class to table columns. - + + + name: the name of the property. + - - The <component> element allows a <parent> - subelement that maps a property of the component class as a reference back to the - containing entity. - + + class (optional - defaults to the + property type determined by reflection): the name of the component + (child) class. + - - The <dynamic-component> element allows a Map - to be mapped as a component, where the property names refer to keys of the map. See - for more information. - + + insert: do the mapped columns appear in + SQL INSERTs? + -
+ + update: do the mapped columns appear in + SQL UPDATEs? + -
- Properties + + access (optional - defaults to + property): the strategy Hibernate uses for + accessing the property value. + - - The <properties> element allows the definition of a named, - logical grouping of the properties of a class. The most important use of the construct - is that it allows a combination of properties to be the target of a - property-ref. It is also a convenient way to define a multi-column - unique constraint. For example: - + + lazy (optional - defaults to + false): specifies that this component should be + fetched lazily when the instance variable is first accessed. It + requires build-time bytecode instrumentation. + - - - - - - - - - + optimistic-lock (optional - defaults to + true): specifies that updates to this component + either do or do not require acquisition of the optimistic lock. It + determines if a version increment should occur when this property + is dirty. + + + + unique (optional - defaults to + false): specifies that a unique constraint + exists upon all mapped columns of the component. + + + + + The child <property> tags map properties + of the child class to table columns. + + The <component> element allows a + <parent> subelement that maps a property of the + component class as a reference back to the containing entity. + + The <dynamic-component> element allows a + Map to be mapped as a component, where the property + names refer to keys of the map. See for more information. +
+ +
+ Properties + + The <properties> element allows the + definition of a named, logical grouping of the properties of a class. + The most important use of the construct is that it allows a combination + of properties to be the target of a property-ref. It + is also a convenient way to define a multi-column unique constraint. For + example: + + + + + + + + + + + + + + + <properties name="logicalName" insert="true|false" update="true|false" optimistic-lock="true|false" unique="true|false" -> +> - - + <property ...../> + <many-to-one .... /> ........ -]]> - - - - name: the logical name of the grouping. It is - not an actual property name. - - - - - insert: do the mapped columns appear in SQL - INSERTs? - - - - - update: do the mapped columns appear in SQL - UPDATEs? - - - - - optimistic-lock (optional - defaults to true): - specifies that updates to these properties either do or do not require acquisition of the - optimistic lock. It determines if a version increment should occur when - these properties are dirty. - - - - - unique (optional - defaults to false): - specifies that a unique constraint exists upon all mapped columns of the - component. - - - - +</properties> - - For example, if we have the following <properties> mapping: - + + + name: the logical name of the grouping. + It is not an actual property name. + - - + + insert: do the mapped columns appear in + SQL INSERTs? + + + + update: do the mapped columns appear in + SQL UPDATEs? + + + + optimistic-lock (optional - defaults to + true): specifies that updates to these + properties either do or do not require acquisition of the + optimistic lock. It determines if a version increment should occur + when these properties are dirty. + + + + unique (optional - defaults to + false): specifies that a unique constraint + exists upon all mapped columns of the component. + + + + + For example, if we have the following + <properties> mapping: + + <class name="Person"> + <id name="personNumber"/> ... - - - - - -]]> + <properties name="name" + unique="true" update="false"> + <property name="firstName"/> + <property name="initial"/> + <property name="lastName"/> + </properties> +</class> - - You might have some legacy data association that refers to this unique key of - the Person table, instead of to the primary key: - + You might have some legacy data association that refers to this + unique key of the Person table, instead of to the + primary key: - - - - -]]> + <many-to-one name="person" + class="Person" property-ref="name"> + <column name="firstName"/> + <column name="initial"/> + <column name="lastName"/> +</many-to-one> - - The use of this outside the context of mapping - legacy data is not recommended. - + The use of this outside the context of mapping legacy data is not + recommended. +
-
+
+ Subclass -
- Subclass + Polymorphic persistence requires the declaration of each subclass + of the root persistent class. For the table-per-class-hierarchy mapping + strategy, the <subclass> declaration is used. + For example: - - Polymorphic persistence requires the declaration of each subclass of - the root persistent class. For the table-per-class-hierarchy - mapping strategy, the <subclass> declaration is used. For example: - + + + - - - - - - - - + + + + + + + <subclass name="ClassName" discriminator-value="discriminator_value" proxy="ProxyInterface" @@ -2356,69 +2473,68 @@ dynamic-insert="true|false" entity-name="EntityName" node="element-name" - extends="SuperclassName"> + extends="SuperclassName"> - + <property .... /> ..... -]]> - - - - name: the fully qualified class name of the subclass. - - - - - discriminator-value (optional - defaults to the class name): a - value that distinguishes individual subclasses. - - - - - proxy (optional): specifies a class or interface used for - lazy initializing proxies. - - - - - lazy (optional - defaults to true): setting - lazy="false" disables the use of lazy fetching. - - - - +</subclass> - - Each subclass declares its own persistent properties and subclasses. - <version> and <id> properties - are assumed to be inherited from the root class. Each subclass in a hierarchy must - define a unique discriminator-value. If this is not specified, the - fully qualified Java class name is used. - + + + name: the fully qualified class name of + the subclass. + - - For information about inheritance mappings see . - + + discriminator-value (optional - defaults + to the class name): a value that distinguishes individual + subclasses. + -
+ + proxy (optional): specifies a class or + interface used for lazy initializing proxies. + -
- Joined-subclass + + lazy (optional - defaults to + true): setting lazy="false" + disables the use of lazy fetching. + + + - - 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 joining with the table of the - superclass. To do this you use the <joined-subclass> element. For example: - + Each subclass declares its own persistent properties and + subclasses. <version> and + <id> properties are assumed to be inherited + from the root class. Each subclass 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 . +
+ +
+ Joined-subclass + + 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 joining with the table of the superclass. To do this you use the + <joined-subclass> element. For example: + + + + + + + + + + + + + <joined-subclass name="ClassName" table="tablename" proxy="ProxyInterface" @@ -2431,106 +2547,104 @@ persister="ClassName" subselect="SQL expression" entity-name="EntityName" - node="element-name"> + node="element-name"> - + <key .... > - + <property .... /> ..... -]]> - - - - name: the fully qualified class name of the subclass. - - - - - table: the name of the subclass table. - - - - - proxy (optional): specifies a class or interface to use - for lazy initializing proxies. - - - - - lazy (optional, defaults to true): setting - lazy="false" disables the use of lazy fetching. - - - - +</joined-subclass> - - A discriminator column is not required for this mapping strategy. Each subclass must, - however, declare a table column holding the object identifier using the - <key> element. The mapping at the start of the chapter - would then be re-written as: - + + + name: the fully qualified class name of + the subclass. + - - + table: the name of the subclass + table. + + + + proxy (optional): specifies a class or + interface to use for lazy initializing proxies. + + + + lazy (optional, defaults to + true): setting lazy="false" + disables the use of lazy fetching. + + + + + A discriminator column is not required for this mapping strategy. + Each subclass must, however, declare a table column holding the object + identifier using the <key> element. The mapping + at the start of the chapter would then be re-written as: + + <?xml version="1.0"?> +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> + "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> - +<hibernate-mapping package="eg"> - - - - - - - - - - - - - - - - - - + <class name="Cat" table="CATS"> + <id name="id" column="uid" type="long"> + <generator class="hilo"/> + </id> + <property name="birthdate" type="date"/> + <property name="color" not-null="true"/> + <property name="sex" not-null="true"/> + <property name="weight"/> + <many-to-one name="mate"/> + <set name="kittens"> + <key column="MOTHER"/> + <one-to-many class="Cat"/> + </set> + <joined-subclass name="DomesticCat" table="DOMESTIC_CATS"> + <key column="CAT"/> + <property name="name" type="string"/> + </joined-subclass> + </class> - - - + <class name="eg.Dog"> + <!-- mapping for Dog could go here --> + </class> -]]> +</hibernate-mapping> - - 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 + inheritance hierarchy to tables. This is called the + table-per-concrete-class strategy. Each table defines all persistent + states of the class, including the inherited state. In Hibernate, it is + not necessary to explicitly map such inheritance hierarchies. You can + map each class with a separate <class> + declaration. However, if you wish use polymorphic associations (e.g. an + association to the superclass of your hierarchy), you need to use the + <union-subclass> mapping. For example: - - A third option is to map only the concrete classes of an inheritance hierarchy - to tables. This is called the table-per-concrete-class strategy. Each table defines all - persistent states of the class, including the inherited state. In Hibernate, it is - not necessary to explicitly map such inheritance hierarchies. You - can map each class with a separate <class> - declaration. However, if you wish use polymorphic associations (e.g. an association - to the superclass of your hierarchy), you need to - use the <union-subclass> mapping. For example: - + + + - - - - - - - - + + + + + + + <union-subclass name="ClassName" table="tablename" proxy="ProxyInterface" @@ -2544,252 +2658,246 @@ persister="ClassName" subselect="SQL expression" entity-name="EntityName" - node="element-name"> + node="element-name"> - + <property .... /> ..... -]]> - - - - name: the fully qualified class name of the subclass. - - - - - table: the name of the subclass table. - - - - - proxy (optional): specifies a class or interface to use - for lazy initializing proxies. - - - - - lazy (optional, defaults to true): setting - lazy="false" disables the use of lazy fetching. - - - - +</union-subclass> - - No discriminator column or key column is required for this mapping strategy. - + + + name: the fully qualified class name of + the subclass. + - - For information about inheritance mappings see . - + + table: the name of the subclass + table. + -
+ + proxy (optional): specifies a class or + interface to use for lazy initializing proxies. + -
- Join + + lazy (optional, defaults to + true): setting lazy="false" + disables the use of lazy fetching. + + + - - Using the <join> element, it is possible to map - properties of one class to several tables that have a one-to-one relationship. For example: - + No discriminator column or key column is required for this mapping + strategy. - - - - - - - - - - For information about inheritance mappings see . +
+ +
+ Join + + Using the <join> element, it is possible + to map properties of one class to several tables that have a one-to-one + relationship. For example: + + + + + + + + + + + + + + + + + <join table="tablename" schema="owner" catalog="catalog" fetch="join|select" inverse="true|false" - optional="true|false"> + optional="true|false"> - + <key ... /> - + <property ... /> ... -]]> +</join> - - - - table: the name of the joined table. - - - - - schema (optional): overrides the schema name specified by - the root <hibernate-mapping> element. - - - - - catalog (optional): overrides 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. It will use - an outer join for a <join> defined by a subclass. - If set to select then Hibernate will use a sequential select for - a <join> defined on a subclass. This will be issued only - if a row represents an instance of the subclass. Inner joins will still - be used to retrieve a <join> defined by the class and its - superclasses. - - - - - inverse (optional - defaults to false): - if enabled, Hibernate will not insert or update the properties defined - by this join. - - - - - optional (optional - defaults to false): - if enabled, Hibernate will insert a row only if the properties defined by this - join are non-null. It will always use an outer join to retrieve the properties. - - - - + + + table: the name of the joined + table. + - - For example, address information for a person can be mapped to a separate - table while preserving value type semantics for all properties: - + + schema (optional): overrides the schema + name specified by the root + <hibernate-mapping> element. + - + + catalog (optional): overrides 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. It will use an outer join for a + <join> defined by a subclass. If set to + select then Hibernate will use a sequential + select for a <join> defined on a + subclass. This will be issued only if a row represents an instance + of the subclass. Inner joins will still be used to retrieve a + <join> defined by the class and its + superclasses. + - - - - - - - ...]]> + + inverse (optional - defaults to + false): if enabled, Hibernate will not insert + or update the properties defined by this join. + - - This feature is often only useful for legacy data models. We recommend fewer - tables than classes and a fine-grained domain model. However, it is useful - for switching between inheritance mapping strategies in a single hierarchy, as - explained later. - + + optional (optional - defaults to + false): if enabled, Hibernate will insert a row + only if the properties defined by this join are non-null. It will + always use an outer join to retrieve the properties. + + + -
+ For example, address information for a person can be mapped to a + separate table while preserving value type semantics for all + properties: -
- Key + <class name="Person" + table="PERSON"> - - The <key> element has featured a few times within this guide. - It appears anywhere the parent mapping element defines a join to - a new table that references - the primary key of the original table. It also defines the foreign key in the joined table: - + <id name="id" column="PERSON_ID">...</id> - - - - - - - - - - + + This feature is often only useful for legacy data models. We + recommend fewer tables than classes and a fine-grained domain model. + However, it is useful for switching between inheritance mapping + strategies in a single hierarchy, as explained later. +
+ +
+ Key + + The <key> element has featured a few + times within this guide. It appears anywhere the parent mapping element + defines a join to a new table that references the primary key of the + original table. It also defines the foreign key in the joined + table: + + + + + + + + + + + + + + + + + <key column="columnname" on-delete="noaction|cascade" property-ref="propertyName" not-null="true|false" update="true|false" unique="true|false" -/>]]> +/> - - - - column (optional): the name of the foreign key column. - This can also be specified by nested <column> - element(s). - - - - - on-delete (optional - defaults to noaction): - specifies whether the foreign key constraint has database-level cascade delete - enabled. - - - - - property-ref (optional): specifies 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): specifies that the foreign key columns - are not nullable. This is implied whenever the foreign key is also part of the - primary key. - - - - - update (optional): specifies that the foreign key should never - be updated. This is implied whenever the foreign key is also part of the primary - key. - - - - - unique (optional): specifies that the foreign key should have - a unique constraint. This is implied whenever the foreign key is also the primary key. - - - - + + + column (optional): the name of the + foreign key column. This can also be specified by nested + <column> element(s). + - - For systems where delete performance is important, we recommend that all keys should be - defined on-delete="cascade". Hibernate uses a database-level - ON CASCADE DELETE constraint, instead of many individual - DELETE statements. Be aware that this feature bypasses Hibernate's - usual optimistic locking strategy for versioned data. - + + on-delete (optional - defaults to + noaction): specifies whether the foreign key + constraint has database-level cascade delete enabled. + - - The not-null and update attributes are useful when - mapping a unidirectional one-to-many association. If you map a unidirectional one-to-many association - to a non-nullable foreign key, you must declare the key column using - <key not-null="true">. - + + property-ref (optional): specifies 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): specifies that the + foreign key columns are not nullable. This is implied whenever the + foreign key is also part of the primary key. + -
- Column and formula elements - - Mapping elements which accept a column attribute will alternatively - accept a <column> subelement. Likewise, <formula> - is an alternative to the formula attribute. For example: - + + update (optional): specifies that the + foreign key should never be updated. This is implied whenever the + foreign key is also part of the primary key. + - + unique (optional): specifies that the + foreign key should have a unique constraint. This is implied + whenever the foreign key is also the primary key. + + + + + For systems where delete performance is important, we recommend + that all keys should be defined on-delete="cascade". + Hibernate uses a database-level ON CASCADE DELETE + constraint, instead of many individual DELETE + statements. Be aware that this feature bypasses Hibernate's usual + optimistic locking strategy for versioned data. + + The not-null and update + attributes are useful when mapping a unidirectional one-to-many + association. If you map a unidirectional one-to-many association to a + non-nullable foreign key, you must declare the key + column using <key not-null="true">. +
+ +
+ Column and formula elements + + Mapping elements which accept a column + attribute will alternatively accept a <column> + subelement. Likewise, <formula> is an + alternative to the formula attribute. For + example: + + <column name="column_name" length="N" precision="N" @@ -2802,553 +2910,528 @@ check="SQL expression" default="SQL expression" read="SQL expression" - write="SQL expression"/>]]> + write="SQL expression"/> - SQL expression]]> + <formula>SQL expression</formula> - - Most of the attributes on column provide a means of tailoring the - DDL during automatic schema generation. The read and write - attributes allow you to specify custom SQL that Hibernate will use to access the column's value. - For more on this, see the discussion of - column read and write expressions. - + Most of the attributes on column provide a + means of tailoring the DDL during automatic schema generation. The + read and write attributes allow + you to specify custom SQL that Hibernate will use to access the column's + value. For more on this, see the discussion of column read and write + expressions. - - The column and formula elements can even be combined - within the same property or association mapping to express, for example, exotic join - conditions. - - - - - 'MAILING' -]]> + The column and formula + elements can even be combined within the same property or association + mapping to express, for example, exotic join conditions. + <many-to-one name="homeAddress" class="Address" + insert="false" update="false"> + <column name="person_id" not-null="true" length="10"/> + <formula>'MAILING'</formula> +</many-to-one>
-
- Import +
+ Import - - If your application has two persistent classes with the same name, and you do not want to - specify the fully qualified package name in Hibernate queries, classes can be "imported" - explicitly, rather than relying upon auto-import="true". You can also import - classes and interfaces that are not explicitly mapped: - + If your application has two persistent classes with the same name, + and you do not want to specify the fully qualified package name in + Hibernate queries, classes can be "imported" explicitly, rather than + relying upon auto-import="true". You can also import + classes and interfaces that are not explicitly mapped: - ]]> + <import class="java.lang.Object" rename="Universe"/> - - - - - - + + + + + + + <import class="ClassName" rename="ShortName" -/>]]> - - - - class: the fully qualified class name of any Java class. - - - - - rename (optional - defaults to the unqualified class name): - a name that can be used in the query language. - - - - +/> -
+ + + class: the fully qualified class name of + any Java class. + -
- Any + + rename (optional - defaults to the + unqualified class name): a name that can be used in the query + language. + + + +
- - There is one more type of property mapping. The <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 the type of the associated entity. - The remaining columns contain the identifier. It is impossible 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 special cases. For example, for audit logs, - user session data, etc. - +
+ Any - - The meta-type attribute allows the application to specify a custom type that - maps database column values to persistent classes that have identifier properties of the - type specified by id-type. You must specify the mapping from values of - the meta-type to class names. - + There is one more type of property mapping. The + <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 the type of the + associated entity. The remaining columns contain the identifier. It is + impossible 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 special cases. For example, + for audit logs, user session data, etc. - - - - - - -]]> + The meta-type attribute allows the application + to specify a custom type that maps database column values to persistent + classes that have identifier properties of the type specified by + id-type. You must specify the mapping from values of + the meta-type to class names. - - - - - - - - - - <any name="being" id-type="long" meta-type="string"> + <meta-value value="TBL_ANIMAL" class="Animal"/> + <meta-value value="TBL_HUMAN" class="Human"/> + <meta-value value="TBL_ALIEN" class="Alien"/> + <column name="table_name"/> + <column name="id"/> +</any> + + + + + + + + + + + + + + + + + <any name="propertyName" id-type="idtypename" meta-type="metatypename" cascade="cascade_style" access="field|property|ClassName" optimistic-lock="true|false" -> - - +> + <meta-value ... /> + <meta-value ... /> ..... - - + <column .... /> + <column .... /> ..... -]]> - - - - name: the property name. - - - - - id-type: the identifier type. - - - - - meta-type (optional - defaults to string): - any type that is allowed for a discriminator mapping. - - - - - cascade (optional- defaults to none): - the cascade style. - - - - - access (optional - defaults to property): the - strategy Hibernate uses for accessing the property value. - - - - - optimistic-lock (optional - defaults to true): - 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. - - - - +</any> -
+ + + name: the property name. + + + id-type: the identifier type. + + + + meta-type (optional - defaults to + string): any type that is allowed for a + discriminator mapping. + + + + cascade (optional- defaults to + none): the cascade style. + + + + access (optional - defaults to + property): the strategy Hibernate uses for + accessing the property value. + + + + optimistic-lock (optional - defaults to + true): 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. + + + +
+
+ +
+ Hibernate types + +
+ Entities and values + + In relation to the persistence service, Java language-level + objects are classified into two groups: + + An entity exists independently of any other + objects holding references to the entity. Contrast this with the usual + Java model, where an unreferenced object is garbage collected. Entities + must be explicitly saved and deleted. Saves and deletions, however, can + be cascaded from a parent entity to its children. + This is different from the ODMG model of object persistence by + reachability and corresponds more closely to how application objects are + usually used in large systems. Entities support circular and shared + references. They can also be versioned. + + An entity's persistent state consists of references to other + entities and 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 reachability. Since value objects and primitives are + persisted and deleted along with their containing entity, they cannot be + independently versioned. Values have no independent identity, so they + cannot be shared by two entities or collections. + + 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 with value + semantics. A Java property of type java.lang.String + also has value semantics. Given this definition, all types (classes) + provided by the JDK have value type semantics in Java, while + user-defined types can be mapped with entity or value type semantics. + This decision is up to the application developer. An entity class in a + domain model will normally have shared references to a single instance + of that class, while composition or aggregation usually translates to a + value type. + + We will revisit both concepts throughout this reference + guide. + + The challenge is to map the Java type system, and the developers' + 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., that usually have a + type attribute. The value of this attribute is the + name of a Hibernate mapping type. Hibernate + provides a range of mappings for standard JDK value types out of the + box. You can write your own mapping types and implement your own custom + conversion strategies. + + With the exception of collections, all built-in Hibernate types + support null semantics.
-
- Hibernate types +
+ Basic value types -
- Entities and values + The built-in basic mapping types can be + roughly categorized into the following: + + integer, long, short, float, double, character, + byte, boolean, yes_no, true_false - - In relation to the persistence service, Java language-level objects are classified - into two groups: - + + Type mappings from Java primitives or wrapper classes to + appropriate (vendor-specific) SQL column types. + boolean, yes_no and + true_false are all alternative encodings for + a Java boolean or + java.lang.Boolean. + + - - An entity exists independently of any other objects holding - references to the entity. Contrast this with the usual Java model, where an - unreferenced object is garbage collected. Entities must be explicitly saved and - deleted. Saves and deletions, however, can be cascaded - from a parent entity to its children. This is different from the ODMG model of - object persistence by reachability and corresponds more closely to how - application objects are usually used in large systems. Entities support - circular and shared references. They can also be versioned. - + + string - - An entity's persistent state consists of references to other entities and - 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 reachability. Since value - objects and primitives are persisted and deleted along with their containing - entity, they cannot be independently versioned. Values have no independent - identity, so they cannot be shared by two entities or collections. - + + A type mapping from java.lang.String to + VARCHAR (or Oracle + VARCHAR2). + + - - 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 with value semantics. - A Java property of type java.lang.String also has value - semantics. Given this definition, all types (classes) provided - by the JDK have value type semantics in Java, while user-defined types can - be mapped with entity or value type semantics. This decision is up to the - application developer. An entity class in a domain model will normally have - shared references to a single instance of that class, while composition or - aggregation usually translates to a value type. - + + date, time, timestamp - - We will revisit both concepts throughout this reference guide. - + + Type mappings from java.util.Date and + its subclasses to SQL types DATE, + TIME and TIMESTAMP (or + equivalent). + + - - The challenge is to map the Java type system, and the developers' 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., that usually have a type - attribute. The value of this attribute is the name of a Hibernate - mapping type. Hibernate provides a range of mappings for standard - JDK value types out of the box. You can write your own mapping types and implement your own - custom conversion strategies. - + + calendar, calendar_date - - With the exception of collections, all built-in Hibernate types support null semantics. - + + Type mappings from java.util.Calendar + to SQL types TIMESTAMP and + DATE (or equivalent). + + -
+ + big_decimal, big_integer -
- Basic value types + + Type mappings from java.math.BigDecimal + and java.math.BigInteger to + NUMERIC (or Oracle + NUMBER). + + - - The built-in basic mapping types can be roughly categorized into the following: + + locale, timezone, currency - - - integer, long, short, float, double, character, byte, - boolean, yes_no, true_false - - - Type mappings from Java primitives or wrapper classes to appropriate - (vendor-specific) SQL column types. boolean, yes_no - and true_false are all alternative encodings for - a Java boolean or java.lang.Boolean. - - - - - string - - - A type mapping from java.lang.String to - VARCHAR (or Oracle VARCHAR2). - - - - - date, time, timestamp - - - Type mappings from java.util.Date and its subclasses - to SQL types DATE, TIME and - TIMESTAMP (or equivalent). - - - - - calendar, calendar_date - - - Type mappings from java.util.Calendar to - SQL types TIMESTAMP and DATE - (or equivalent). - - - - - big_decimal, big_integer - - - Type mappings from java.math.BigDecimal and - java.math.BigInteger to NUMERIC - (or Oracle NUMBER). - - - - - locale, timezone, currency - - - Type mappings from java.util.Locale, - java.util.TimeZone and - java.util.Currency - to VARCHAR (or Oracle VARCHAR2). - Instances of Locale and Currency are - mapped to their ISO codes. Instances of TimeZone are - mapped to their ID. - - - - - class - - - A type mapping from java.lang.Class to - VARCHAR (or Oracle VARCHAR2). - A Class is mapped to its fully qualified name. - - - - - binary - - - Maps byte arrays to an appropriate SQL binary type. - - - - - text - - - Maps long Java strings to a SQL CLOB or - TEXT type. - - - - - serializable - - - Maps serializable Java types to an appropriate SQL binary type. You - can also indicate the Hibernate type serializable with - the name of a serializable Java class or interface that does not default - to a basic type. - - - - - clob, blob - - - Type mappings for the JDBC classes java.sql.Clob and - java.sql.Blob. These types can be inconvenient for some - applications, since the blob or clob object cannot be reused outside of - a transaction. Driver support is patchy and inconsistent. - - - - - - imm_date, imm_time, imm_timestamp, imm_calendar, imm_calendar_date, - imm_serializable, imm_binary - - - - Type mappings for what are considered mutable Java types. This is where - Hibernate makes certain optimizations appropriate only for immutable - Java types, and the application treats the object as immutable. For - example, you should not call Date.setTime() for an - instance mapped as imm_timestamp. To change the - value of the property, and have that change made persistent, the - application must assign a new, nonidentical, object to the property. - - - - + + Type mappings from java.util.Locale, + java.util.TimeZone and + java.util.Currency to + VARCHAR (or Oracle + VARCHAR2). Instances of + Locale and Currency are + mapped to their ISO codes. Instances of + TimeZone are mapped to their + ID. + + - + + class - - Unique identifiers of entities and collections can be of any basic type except - binary, blob and clob. - Composite identifiers are also allowed. See below for more information. - + + A type mapping from java.lang.Class to + VARCHAR (or Oracle + VARCHAR2). A Class is + mapped to its fully qualified name. + + - - The basic value types have corresponding Type constants defined on - org.hibernate.Hibernate. For example, Hibernate.STRING - represents the string type. - + + binary -
+ + Maps byte arrays to an appropriate SQL binary type. + +
-
- Custom value types + + text - - It is relatively easy for developers to create their own value 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. Custom types are not limited to mapping a property, 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 the columns - FIRST_NAME, INITIAL, SURNAME. - + + Maps long Java strings to a SQL CLOB or + TEXT type. + + - - 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. View - org.hibernate.test.DoubleStringType to see the kind of things that - are possible. - + + serializable - - - -]]> + + Maps serializable Java types to an appropriate SQL binary + type. You can also indicate the Hibernate type + serializable with the name of a serializable + Java class or interface that does not default to a basic + type. + + - - Notice the use of <column> tags to map a property to multiple - columns. - + + clob, blob - - The CompositeUserType, EnhancedUserType, - UserCollectionType, and UserVersionType - interfaces provide support for more specialized uses. - + + Type mappings for the JDBC classes + java.sql.Clob and + java.sql.Blob. These types can be + inconvenient for some applications, since the blob or clob + object cannot be reused outside of a transaction. Driver support + is patchy and inconsistent. + + - - You can even supply parameters to a UserType in the mapping file. To - do this, your UserType must implement the - org.hibernate.usertype.ParameterizedType interface. To supply parameters - to your custom type, you can use the <type> element in your mapping - files. - + + imm_date, imm_time, imm_timestamp, imm_calendar, + imm_calendar_date, imm_serializable, imm_binary - - - 0 - -]]> + + Type mappings for what are considered mutable Java types. + This is where Hibernate makes certain optimizations appropriate + only for immutable Java types, and the application treats the + object as immutable. For example, you should not call + Date.setTime() for an instance mapped as + imm_timestamp. To change the value of the + property, and have that change made persistent, the application + must assign a new, nonidentical, object to the property. + + + - - The UserType can now retrieve the value for the parameter named - default from the Properties object passed to it. - - - - If you regularly use a certain UserType, it is useful to define a - shorter name for it. You can do this using the <typedef> element. - Typedefs assign a name to a custom type, and can also contain a list of default - parameter values if the type is parameterized. - - - - 0 -]]> - - ]]> - - - It is also possible to override the parameters supplied in a typedef on a case-by-case basis - by using type parameters on the property mapping. - - - - Even though Hibernate's rich range of built-in types and support for components means you - will rarely need to use a custom type, it is - considered good practice to use custom types for non-entity classes that occur frequently - in your application. For example, a MonetaryAmount class is a good - 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. - - -
+ Unique identifiers of entities and collections can be of any basic + type except binary, blob and + clob. Composite identifiers are also allowed. See + below for more information. + The basic value types have corresponding Type + constants defined on org.hibernate.Hibernate. For + example, Hibernate.STRING represents the + string type.
-
- Mapping a class more than once - - It is possible to provide more than one mapping for a particular persistent class. In this - case, you must specify an entity name 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 persistent objects, when writing - queries, or when mapping associations to the named entity. - +
+ Custom value types - - ... - - - - - + It is relatively easy for developers to create their own value + 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. Custom + types are not limited to mapping a property, 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 the columns + FIRST_NAME, INITIAL, + SURNAME. - + 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. View + org.hibernate.test.DoubleStringType to see the kind + of things that are possible. + + <property name="twoStrings" type="org.hibernate.test.DoubleStringType"> + <column name="first_string"/> + <column name="second_string"/> +</property> + + Notice the use of <column> tags to map a + property to multiple columns. + + The CompositeUserType, + EnhancedUserType, + UserCollectionType, and + UserVersionType interfaces provide support for more + specialized uses. + + You can even supply parameters to a UserType in + the mapping file. To do this, your UserType must + implement the + org.hibernate.usertype.ParameterizedType interface. + To supply parameters to your custom type, you can use the + <type> element in your mapping files. + + <property name="priority"> + <type name="com.mycompany.usertypes.DefaultValueIntegerType"> + <param name="default">0</param> + </type> +</property> + + The UserType can now retrieve the value for the + parameter named default from the + Properties object passed to it. + + If you regularly use a certain UserType, it is + useful to define a shorter name for it. You can do this using the + <typedef> element. Typedefs assign a name to a + custom type, and can also contain a list of default parameter values if + the type is parameterized. + + <typedef class="com.mycompany.usertypes.DefaultValueIntegerType" name="default_zero"> + <param name="default">0</param> +</typedef> + + <property name="priority" type="default_zero"/> + + It is also possible to override the parameters supplied in a + typedef on a case-by-case basis by using type parameters on the property + mapping. + + Even though Hibernate's rich range of built-in types and support + for components means you will rarely need to use a custom type, it is + considered good practice to use custom types for non-entity classes that + occur frequently in your application. For example, a + MonetaryAmount class is a good 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. +
+
+ +
+ Mapping a class more than once + + It is possible to provide more than one mapping for a particular + persistent class. In this case, you must specify an entity + name 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 persistent + objects, when writing queries, or when mapping associations to the named + entity. + + <class name="Contract" table="Contracts" + entity-name="CurrentContract"> ... - -]]> + entity-name="CurrentContract"/> +</class> - - Associations are now specified using entity-name instead of - class. - + Associations are now specified using entity-name + instead of class. +
-
+
+ SQL quoted identifiers -
- SQL quoted identifiers - - You can force Hibernate to quote an identifier in the generated SQL by enclosing the table or - column name in backticks in the mapping document. Hibernate will use the correct quotation - style for the SQL Dialect. This is usually double quotes, but the SQL - Server uses brackets and MySQL uses backticks. - + You can force Hibernate to quote an identifier in the generated SQL + by enclosing the table or column name in backticks in the mapping + document. Hibernate will use the correct quotation style for the SQL + Dialect. This is usually double quotes, but the SQL + Server uses brackets and MySQL uses backticks. - - - + <class name="LineItem" table="`Line Item`"> + <id name="id" column="`Item Id`"/><generator class="assigned"/></id> + <property name="itemNumber" column="`Item #`"/> ... -]]> +</class> +
-
+
+ Metadata alternatives - -
- Metadata alternatives - - - XML does not suit all users 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.
- Using XDoclet markup + Using XDoclet markup - - Many Hibernate users prefer to embed mapping information directly in sourcecode using - XDoclet @hibernate.tags. We do not cover this approach in this - reference guide since it is considered part of XDoclet. However, we include the - following example of the Cat class with XDoclet mappings: - + Many Hibernate users prefer to embed mapping information directly + in sourcecode using XDoclet @hibernate.tags. We do + not cover this approach in this reference guide since it is considered + part of XDoclet. However, we include the following example of the + Cat class with XDoclet mappings: - package eg; import java.util.Set; import java.util.Date; @@ -3451,33 +3534,31 @@ public class Cat { void setSex(char sex) { this.sex=sex; } -}]]> - - - See the Hibernate website for more examples of XDoclet and Hibernate. - +} + See the Hibernate website for more examples of XDoclet and + Hibernate.
- Using JDK 5.0 Annotations + Using JDK 5.0 Annotations - - JDK 5.0 introduced XDoclet-style annotations at the language level 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 revision of the EJB specification - (JSR-220) uses JDK 5.0 annotations as the primary metadata mechanism for entity beans. - Hibernate3 implements the EntityManager of JSR-220 (the persistence API). - Support for mapping metadata is available via the Hibernate Annotations - package as a separate download. Both EJB3 (JSR-220) and Hibernate3 metadata is supported. - + JDK 5.0 introduced XDoclet-style annotations at the language level + 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 revision of the EJB + specification (JSR-220) uses JDK 5.0 annotations as the primary metadata + mechanism for entity beans. Hibernate3 implements the + EntityManager of JSR-220 (the persistence API). + Support for mapping metadata is available via the Hibernate + Annotations package as a separate download. Both EJB3 + (JSR-220) and Hibernate3 metadata is supported. - - This is an example of a POJO class annotated as an EJB entity bean: - + This is an example of a POJO class annotated as an EJB entity + bean: - @Entity(access = AccessType.FIELD) public class Customer implements Serializable { @Id; @@ -3495,141 +3576,133 @@ public class Customer implements Serializable { @OneToMany(cascade=CascadeType.ALL) @JoinColumn(name="CUSTOMER_ID") - Set orders; + Set<Order> orders; // Getter/setter and business methods -}]]> +} - - Note - - Support for JDK 5.0 Annotations (and JSR-220) is currently under development. - Please refer to the Hibernate Annotations module for more details. - - + + Note + Support for JDK 5.0 Annotations (and JSR-220) is currently under + development. Please refer to the Hibernate Annotations module for more + details. +
-
+
-
- Generated properties - - Generated properties are properties that have their values generated by the - database. Typically, Hibernate applications needed to refresh - 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. When Hibernate issues an SQL INSERT - 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-insertable and non-updateable. - Only versions, - timestamps, and - simple properties, can be marked as - generated. - - - never (the default): the given property value - is not generated within the database. - - - insert: the given property value is generated on - insert, but is not regenerated on subsequent updates. Properties like created-date - fall into this category. Even though - version and - timestamp properties can - be marked as generated, this option is not available. - - - always: the property value is generated both - on insert and on update. - -
+
+ Generated properties -
- Column read and write expressions - - Hibernate allows you to customize the SQL it uses to read and write the values - of columns mapped to simple properties. - For example, if your database provides a set of data encryption functions, you can - invoke them for individual columns like this: - - Generated properties are properties that have their values generated + by the database. Typically, Hibernate applications needed to + refresh 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. + When Hibernate issues an SQL INSERT 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-insertable + and non-updateable. Only versions, timestamps, and simple properties, can be + marked as generated. + + never (the default): the given property value is + not generated within the database. + + insert: the given property value is generated on + insert, but is not regenerated on subsequent updates. Properties like + created-date fall into this category. Even though version and timestamp properties can be + marked as generated, this option is not available. + + always: the property value is generated both on + insert and on update. +
+ +
+ Column read and write expressions + + Hibernate allows you to customize the SQL it uses to read and write + the values of columns mapped to simple properties. For + example, if your database provides a set of data encryption functions, you + can invoke them for individual columns like this: <property name="creditCardNumber"> + <column name="credit_card_num" read="decrypt(credit_card_num)" - write="encrypt(?)"/> -]]> - - - Hibernate applies the custom expressions automatically whenever the property is - referenced in a query. This functionality is similar to a derived-property - formula with two differences: - - - - The property is backed by one or more columns that are exported as part of automatic - schema generation. - - - - - The property is read-write, not read-only. - - - - - - The write expression, if specified, must contain exactly one '?' placeholder - for the value. - -
+ write="encrypt(?)"/> +</property> -
- Auxiliary database objects - - Auxiliary database objects allow for the CREATE and DROP of arbitrary database objects. In conjunction with - Hibernate's schema evolution tools, they have the ability to fully define - a user schema within the Hibernate mapping files. Although designed specifically - for creating and dropping things like triggers or stored procedures, any - SQL command that can be run via a java.sql.Statement.execute() - method is valid (for example, ALTERs, INSERTS, etc.). There are essentially two modes for - defining auxiliary database objects: - - - The first mode is to explicitly list the CREATE and DROP commands in the mapping - file: - - + Hibernate applies the custom expressions automatically whenever the + property is referenced in a query. This functionality is similar to a + derived-property formula with two differences: + + + The property is backed by one or more columns that are + exported as part of automatic schema generation. + + + + The property is read-write, not read-only. + + + + The write expression, if specified, must contain + exactly one '?' placeholder for the value. +
+ +
+ Auxiliary database objects + + Auxiliary database objects allow for the CREATE and DROP of + arbitrary database objects. In conjunction with Hibernate's schema + evolution tools, they have the ability to fully define a user schema + within the Hibernate mapping files. Although designed specifically for + creating and dropping things like triggers or stored procedures, any SQL + command that can be run via a + java.sql.Statement.execute() method is valid (for + example, ALTERs, INSERTS, etc.). There are essentially two modes for + defining auxiliary database objects: + + The first mode is to explicitly list the CREATE and DROP commands in + the mapping file: + + <hibernate-mapping> ... - - CREATE TRIGGER my_trigger ... - DROP TRIGGER my_trigger - -]]> - - 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. - - + <database-object> + <create>CREATE TRIGGER my_trigger ...</create> + <drop>DROP TRIGGER my_trigger</drop> + </database-object> +</hibernate-mapping> + + 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. + + <hibernate-mapping> ... - - - -]]> - - Additionally, these database objects can be optionally scoped so that they only - apply when certain dialects are used. - - + <database-object> + <definition class="MyTriggerDefinition"/> + </database-object> +</hibernate-mapping> + + Additionally, these database objects can be optionally scoped so + that they only apply when certain dialects are used. + + <hibernate-mapping> ... - - - - - -]]> -
+ <database-object> + <definition class="MyTriggerDefinition"/> + <dialect-scope name="org.hibernate.dialect.Oracle9iDialect"/> + <dialect-scope name="org.hibernate.dialect.Oracle10gDialect"/> + </database-object> +</hibernate-mapping> +
-