How to use Hibernate Annotations in Spring

how to configure hibernate annotation in spring and hibernate annotations tutorial and hibernate annotations interview questions, hibernate annotations description
LexiWills Profile Pic
LexiWills,United Kingdom,Professional
Published Date:31-07-2017
Your Website URL(Optional)
Comment
Hibernate Annotations Reference Guide Version: 3.1 beta 9Table of Contents Preface ............................................................................................................................................ iv 1. Setting up an annotations project ................................................................................................ 1 1.1. Requirements ..................................................................................................................... 1 1.2. Configuration ..................................................................................................................... 1 2. Entity Beans ................................................................................................................................ 3 2.1. Intro .................................................................................................................................. 3 2.2. Mapping with EJB3 Annotations ......................................................................................... 3 2.2.1. Declaring an entity bean .......................................................................................... 3 2.2.1.1. Defining the table ......................................................................................... 3 2.2.1.2. Versioning for optimistic locking ................................................................... 4 2.2.2. Mapping simple properties ....................................................................................... 4 2.2.2.1. Declaring basic property mappings ................................................................ 4 2.2.2.2. Declaring column attributes ........................................................................... 5 2.2.2.3. Embedded objects (aka components) .............................................................. 6 2.2.2.4. Non-annotated property defaults .................................................................... 8 2.2.. Mapping identifier properties ..................................................................................... 8 2.2.4. Mapping inheritance .............................................................................................. 11 2.2.4.1. Table per class ............................................................................................ 11 2.2.4.2. Single table per class hierarchy .................................................................... 11 2.2.4.3. Joined subclasses ........................................................................................ 12 2.2.4.4. Inherit properties from superclasses ............................................................. 12 2.2.5. Mapping entity bean associations/relationships ........................................................ 14 2.2.5.1. One-to-one ................................................................................................. 14 2.2.5.2. Many-to-one ............................................................................................... 15 2.2.5.3. Collections ................................................................................................. 15 2.2.5.4. Transitive persistence with cascading ........................................................... 21 2.2.5.5. Association fetching ................................................................................... 21 2.2.6. Mapping composite primary and foreign keys ......................................................... 21 2.2.7. Mapping secondary tables ...................................................................................... 23 2.3. Mapping Queries .............................................................................................................. 23 2.3.1. Mapping EJBQL/HQL queries ............................................................................... 23 2.3.2. Mapping native queries .......................................................................................... 24 2.4. Hibernate Annotation Extensions ...................................................................................... 27 2.4.1. Entity ................................................................................................................... 28 2.4.2. Identifier ............................................................................................................... 29 2.4.3. Property ................................................................................................................ 29 2.4.3.1. Access type ................................................................................................ 29 2.4.3.2. Formula ..................................................................................................... 31 2.4.3.3. Type .......................................................................................................... 31 2.4.3.4. Index ......................................................................................................... 32 2.4.4. Inheritance ............................................................................................................ 32 2.4.5. Single Association related annotations .................................................................... 32 2.4.6. Collection related annotations ................................................................................ 32 2.4.6.1. Parameter annotations ................................................................................. 32 2.4.6.2. Extra collection types .................................................................................. 33 2.4.7. Cache ................................................................................................................... 35 2.4.8. Filters ................................................................................................................... 35 2.4.9. Queries ................................................................................................................. 36 Hibernate 3.1 beta 9 iiHibernate Annotations 3. Hibernate Validator .................................................................................................................. 37 3.1. Constraints ...................................................................................................................... 37 3.1.1. What is a constraint? .............................................................................................. 37 3.1.2. Built in constraints ................................................................................................. 37 3.1.3. Error messages ...................................................................................................... 38 3.1.4. Writing your own constraints ................................................................................. 39 3.1.5. Annotating your domain model .............................................................................. 40 3.2. Using the Validator framework ......................................................................................... 41 3.2.1. Database schema-level validation ........................................................................... 41 3.2.2. Hibernate event-based validation ............................................................................ 42 3.2.3. Application-level validation ................................................................................... 42 3.2.4. Validation informations ......................................................................................... 42 4. Hibernate Lucene Integration ................................................................................................... 44 4.1. Using Lucene to index your entities ................................................................................... 44 4.1.1. Annotating your domain model .............................................................................. 44 4.1.2. Enabling automatic indexing .................................................................................. 44 Hibernate 3.1 beta 9 iiiPreface Hibernate, like all other object/relational mapping tools, requires metadata that governs the transformation of data from one representation to the other (and vice versa). In Hibernate 2.x, mapping metadata is most of the time declared in XML text files. Another option is XDoclet, utilizing Javadoc source code annotations and a preprocessor at compile time. The same kind of annotation support is now available in the standard JDK, al- though more powerful and better supported by tools. IntelliJ IDEA, and Eclipse for example, support auto- completion and syntax highlighting of JDK 5.0 annotations. Annotations are compiled into the bytecode and read at runtime (in Hibernate's case on startup) using reflection, so no external XML files are needed. The EJB3 specification recognizes the interest and the success of the transparent object/relational mapping paradigm. The EJB3 specification standardizes the basic APIs and the metadata needed for any object/relational persistence mechanism. Hibernate EntityManager implements the programming interfaces and lifecycle rules as defined by the EJB3 persistence specification. Together with Hibernate Annotations, this wrapper imple- ments a complete (and standalone) EJB3 persistence solution on top of the mature Hibernate core. You may use a combination of all three together, annotations without EJB3 programming interfaces and lifecycle, or even pure native Hibernate, depending on the business and technical needs of your project. You can at all times fall back to Hibernate native APIs, or if required, even to native JDBC and SQL. Please note that this documentation is based on a preview release of the Hibernate Annotations that follows the public final draft of EJB 3.0/JSR-220 persistence annotations. This work is already very close to the final con- cepts in the new specification. Our goal is to provide a complete set of ORM annotations, including EJB3 standard annotations as well as Hibernate3 extensions for cases not covered by the specification. Eventually you will be able to create all possible mappings with annotations. See the JIRA road mapsection for more in- formation. The EJB3 Public final draft has change some annotations, please refer to http://www.hibernate.org/371.html as a migration guide between Hibernate Annotations 3.1beta7 and 3.1beta8. Hibernate 3.1 beta 9 ivChapter 1. Setting up an annotations project 1.1. Requirements • Download and unpack the Hibernate Annotations distribution from the Hibernate website. • This preview release requires Hibernate 3.2.0.CR2 and above. Do not use this release of Hibernate Annota- tions with an older version of Hibernate 3.x • This release is known to work on Hibernate core 3.2.0.CR2 • Make sure you have JDK 5.0 installed. You can of course continue using XDoclet and get some of the be- nefits of annotation-based metadata with older JDK versions. Note that this document only describes JDK 5.0 annotations and you have to refer to the XDoclet documentation for more information. 1.2. Configuration First, set up your classpath (after you have created a new project in your favorite IDE): • Copy all Hibernate3 core and required 3rd party library files (see lib/README.txt in Hibernate). • Copy hibernate-annotations.jar and lib/ejb3-persistence.jar from the Hibernate Annotations dis- tribution to your classpath as well. • To use the Chapter 4, Hibernate Lucene Integration, add the lucene jar file. We also recommend a small wrapper class to startup Hibernate in a static initializer block, known as Hibern- ateUtil. You might have seen this class in various forms in other areas of the Hibernate documentation. For Annotation support you have to enhance this helper class as follows: package hello; import org.hibernate.; import org.hibernate.cfg.; import test.; import test.animals.Dog; public class HibernateUtil private static final SessionFactory sessionFactory; static try sessionFactory = new AnnotationConfiguration().buildSessionFactory(); catch (Throwable ex) // Log exception throw new ExceptionInInitializerError(ex); public static Session getSession() throws HibernateException return sessionFactory.openSession(); Hibernate 3.1 beta 9 1Setting up an annotations project Interesting here is the use of AnnotationConfiguration. The packages and annotated classes are declared in your regular XML configuration file (usually hibernate.cfg.xml). Here is the equivalent of the above declara- tion: DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" hibernate-configuration session-factory mapping package="test.animals"/ mapping class="test.Flight"/ mapping class="test.Sky"/ mapping class="test.Person"/ mapping class="test.animals.Dog"/ /session-factory /hibernate-configuration Note that you can mix the hbm.xml use and the new annotation one. Alternatively, you can define the annotated classes and packages using the programmatic API sessionFactory = new AnnotationConfiguration() .addPackage("test.animals") //the fully qualified package name .addAnnotatedClass(Flight.class) .addAnnotatedClass(Sky.class) .addAnnotatedClass(Person.class) .addAnnotatedClass(Dog.class) .buildSessionFactory(); You can also use the Hibernate Entity Manager which has it's own configuration mechanism. Please refer to this project documentation for more details. There is no other difference in the way you use Hibernate APIs with annotations, except for this startup routine change or in the configuration file. You can use your favorite configuration method for other properties ( hi- bernate.properties, hibernate.cfg.xml, programmatic APIs, etc). You can even mix annotated persistent classes and classic hbm.cfg.xml declarations with the same SessionFactory. You can however not declare a class several times (whether annotated or through hbm.xml). You cannot mix configuration strategies (hbm vs annotations) in a mapped entity hierarchy either. To ease the migration process from hbm files to annotations, the configuration mechanism detects the mapping duplication between annotations and hbm files. HBM files are then prioritized over annotated metadata on a class to class basis. You can change the priority using hibernate.mapping.precedence property. The default is hbm, class, changing it to class, hbm will prioritize the annotated classes over hbm files when a conflict oc- curs. Hibernate 3.1 beta 9 2Chapter 2. Entity Beans 2.1. Intro This section covers EJB 3.0 entity bean annotations and Hibernate-specific extensions. 2.2. Mapping with EJB3 Annotations EJB3 entity beans are plain POJOs. Actually they represent the exact same concept as the Hibernate persistent entities. Their mappings are defined through JDK 5.0 annotations (an XML descriptor syntax for overriding will be defined in the EJB3 specification, but it's not finalized so far). Annotations can be split in two categor- ies, the logical mapping annotations (allowing you to describe the object model, the class associations, 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. EJB3 annotations are in the javax.persistence. package. Most JDK 5 compliant IDE (like Eclipse, IntelliJ IDEA and Netbeans) can autocomplete annotation interfaces and attributes for you (even without a specific "EJB3" module, since EJB3 annotations are plain JDK 5 annotations). For more and runnable concrete examples read the JBoss EJB 3.0 tutorial or review the Hibernate Annotations test suite. Most of the unit tests have been designed to represent a concrete example and be a inspiration source. 2.2.1. Declaring an entity bean Every bound persistent POJO class is an entity bean and is declared using the Entity annotation (at the class level): Entity public class Flight implements Serializable Long id; Id public Long getId() return id; public void setId(Long id) this.id = id; Entity declares the class as an entity bean (i.e. a persistent POJO class), Id declares the identifier property of this entity bean. The other mapping declarations are implicit. This configuration by exception concept is central to the new EJB3 specification and a major improvement. The class Flight is mapped to the Flight table, using the column id as its primary key column. Depending on whether you annotate fields or methods, the access type used by Hibernate will be field or property. The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access. Mixing EJB3 annotations in both fields and methods should be avoided. Hibernate will guess the access type from the position of Id or EmbeddedId. Defining the table Hibernate 3.1 beta 9 3Entity Beans Table is set at the class level; it allows you to define the table, catalog, and schema names for your entity bean mapping. If no Table is defined the default values are used: the unqualified class name of the entity. Entity Table(name="tbl_sky") public class Sky implements Serializable ... The Table element also contains a schema and a catalog attributes, if they need to be defined. You can also define unique constraints to the table using the UniqueConstraint annotation in conjunction with Table (for a unique constraint bound to a single column, refer to Column). Table(name="tbl_sky", uniqueConstraints = UniqueConstraint(columnNames="month", "day") ) A unique constraint is applied to the tuple month, day. Note that the columnNames array refers to the logical column names. The logical column name is defined by the Hibernate NamingStrategy implementation. The default EJB3 nam- ing strategy use the physical column name as the logical column name. Note that this may be different than the property name (if the column name is explicit). Unless you override the NamingStrategy, you shouldn't worry about that. Versioning for optimistic locking You can add optimistic locking capability to an entity bean using the Version annotation: Entity public class Flight implements Serializable ... Version Column(name="OPTLOCK") public Integer getVersion() ... The version property will be mapped to the OPTLOCK column, and the entity manager will use it to detect con- flicting updates (preventing lost updates you might otherwise see with the last-commit-wins strategy). The version column may be a numeric (the recommended solution) or a timestamp as per the EJB3 spec. Hi- bernate support any kind of type provided that you define and implement the appropriate UserVersionType. 2.2.2. Mapping simple properties Declaring basic property mappings Every non static non transient property (field or method) of an entity bean is considered persistent, unless you annotate it as Transient. Not having an annotation for your property is equivalent to the appropriate Basic annotation. The Basic annotation allows you to declare the fetching strategy for a property: public transient int counter; //transient property private String firstname; //persistent property Transient String getLengthInMeter() ... //transient property Hibernate 3.1 beta 9 4Entity Beans String getName() ... // persistent property Basic int getLength() ... // persistent property Basic(fetch = FetchType.LAZY) String getDetailedComment() ... // persistent property Temporal(TemporalType.TIME) java.util.Date getDepartureTime() ... // persistent property Enumerated(STRING) Starred getNote() ... //enum persisted as String in database counter, a transient field, and lengthInMeter, a method annotated as Transient, and will be ignored by the entity manager. name, length, and firstname properties are mapped persistent and eagerly fetched (the default for simple properties). The detailedComment property value will be lazily fetched from the database once a lazy property of the entity is accessed for the first time. Usually you don't need to lazy simple properties (not to be confused with lazy association fetching). Note To enable property level lazy fetching, your classes have to be instrumented: bytecode is added to the original one to enable such feature, please refer to the Hibernate reference documentation. If your classes are not instrumented, property level lazy loading is silently ignored. The recommended alternative is to use the projection capability of EJB-QL or Criteria queries. EJB3 support property mapping of all basic types supported by Hibernate (all basic Java types , their respective wrappers and serializable classes). Hibernate Annotations support out of the box Enum type mapping either in- to a ordinal column (saving the enum ordinal) or a string based column (saving the enum string representation): the persistence representation, defaulted to ordinal, can be overriden through the Enumerated annotation as shown in the note property example. In core Java APIs, the temporal precision is not defined. When dealing with temporal data you might want to describe the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (ie the actual date, only the time, or both). Use the Temporal annotation to fine tune that. Lob indicates that the property should be persisted in a Blob or a Clob depending on the property type: java.sql.Clob, Character, char and java.lang.String will be persisted in a Clob. java.sql.Blob, Byte, byte and serializable type will be persisted in a Blob. Lob public String getFullText() return fullText; Lob public byte getFullCode() return fullCode; If the property type implements java.io.Serializable and is not a basic type, and if the property is not annot- ated with Lob, then the Hibernate serializable type is used. Declaring column attributes Hibernate 3.1 beta 9 5Entity Beans The column(s) used for a property mapping can be defined using the Column annotation. Use it to override de- fault values (see the EJB3 specification for more information on the defaults). You can use this annotation at the property level for properties that are: • not annotated at all • annotated with Basic • annotated with Version • annotated with Lob • annotated with Temporal • annotated with org.hibernate.annotations.CollectionOfElements (for Hibernate only) Entity public class Flight implements Serializable ... Column(updatable = false, name = "flight_name", nullable = false, length=50) public String getName() ... The name property is mapped to the flight_name column, which is not nullable, has a length of 50 and is not updatable (making the property immutable). This annotation can be applied to regular properties as well as Id or Version properties. Column( name="columnName"; (1) boolean unique() default false; (2) boolean nullable() default true; (3) boolean insertable() default true; (4) boolean updatable() default true; (5) String columnDefinition() default ""; (6) String table() default ""; (7) int length() default 255; (8) int precision() default 0; // decimal precision (9) int scale() default 0; // decimal scale (1) name (optional): the column name (default to the property name) (2) unique (optional): set a unique constraint on this column or not (default false) (3) nullable (optional): set the column as nullable (default false). (4) insertable (optional): whether or not the column will be part of the insert statement (default true) (5) updatable (optional): whether or not the column will be part of the update statement (default true) (6) columnDefinition (optional): override the sql DDL fragment for this particular column (non portable) (7) table (optional): define the targeted table (default primary table) (8) length (optional): column length (default 255) (8) precision (optional): column decimal precision (default 0) (10) scale (optional): column decimal scale if useful (default 0) Embedded objects (aka components) It is possible to declare an embedded component inside an entity and even override its column mapping. Com- ponent classes have to be annotated at the class level with the Embeddable annotation. It is possible to override the column mapping of an embedded object for a particular entity using the Embedded and Hibernate 3.1 beta 9 6Entity Beans AttributeOverride annotation in the associated property: Entity public class Person implements Serializable // Persistent component using defaults Address homeAddress; Embedded AttributeOverrides( AttributeOverride(name="iso2", column = Column(name="bornIso2") ), AttributeOverride(name="name", column = Column(name="bornCountryName") ) ) Country bornIn; ... Embeddable public class Address implements Serializable String city; Country nationality; //no overriding here Embeddable public class Country implements Serializable private String iso2; Column(name="countryName") private String name; public String getIso2() return iso2; public void setIso2(String iso2) this.iso2 = iso2; public String getName() return name; public void setName(String name) this.name = name; ... A embeddable object inherit the access type of its owning entity (note that you can override that using the Hi- bernate specific AccessType annotations (see Hibernate Annotation Extensions). The Person entity bean has two component properties, homeAddress and bornIn. homeAddress property has not been annotated, but Hibernate will guess that it is a persistent component by looking for the Embeddable an- notation in the Address class. We also override the mapping of a column name (to bornCountryName) with the Embedded and AttributeOverride annotations for each mapped attribute of Country. As you can see, Coun- try is also a nested component of Address, again using auto-detection by Hibernate and EJB3 defaults. Over- riding columns of embedded objects of embedded objects is currently not supported in the EJB3 spec, however, Hibernate Annotations supports it through dotted expressions. Embedded AttributeOverrides( AttributeOverride(name="city", column = Column(name="fld_city") ) AttributeOverride(name="nationality.iso2", column = Column(name="nat_Iso2") ), AttributeOverride(name="nationality.name", column = Column(name="nat_CountryName") ) //nationality columns in homeAddress are overridden ) Address homeAddress; Hibernate Annotations supports one more feature that is not explicitly supported by the EJB3 specification. Hibernate 3.1 beta 9 7Entity Beans You can annotate a embedded object with the MappedSuperclass annotation to make the superclass properties persistent (see MappedSuperclass for more informations). While not supported by the EJB3 specification, Hibernate Annotations allows you to use association annota- tions in an embeddable object (ie ToOne nor ToMany). To override the association columns you can use AssociationOverride. If you want to have the same embeddable object type twice in the same entity, the column name defaulting will not work: at least one of the columns will have to be explicit. Hibernate goes beyond the EJB3 spec and allows you to enhance the defaulting mechanism through the NamingStrategy. DefaultComponentSafeNaming- Strategy is a small improvement over the default EJB3NamingStrategy that allows embedded objects to be de- faulted even if used twice in the same entity. Non-annotated property defaults If a property is not annotated, the following rules apply: • If the property is of a single type, it is mapped as Basic • Otherwise, if the type of the property is annotated as Embeddable, it is mapped as Embedded • Otherwise, if the type of the property is Serializable, it is mapped as Basic in a column holding the object in its serialized version • Otherwise, if the type of the property is java.sql.Clob or java.sql.Blob, it is mapped as Lob with the ap- propriate LobType 2.2.. Mapping identifier properties The Id annotation lets you define which property is the identifier of your entity bean. This property can be set by the application itself or be generated by Hibernate (preferred). You can define the identifier generation strategy thanks to the GeneratedValue annotation: • AUTO - either identity column, sequence or table depending on the underlying DB • TABLE - table holding the id • IDENTITY - identity column • SEQUENCE - sequence Hibernate provides more id generators than the basic EJB3 ones. Check Hibernate Annotation Extensions for more informations. The following example shows a sequence generator using the SEQ_STORE configuration (see below) Id GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_STORE") public Integer getId() ... The next example uses the identity generator: Id GeneratedValue(strategy=GenerationType.IDENTITY) Hibernate 3.1 beta 9 8Entity Beans public Long getId() ... The AUTO generator is the preferred type for portable applications (across several DB vendors). The identifier generation configuration can be shared for several Id mappings with the generator attribute. There are several configurations available through SequenceGenerator and TableGenerator. The scope of a generator can be the application or the class. Class-defined generators are not visible outside the class and can override applica- tion level generators. Application level generators are defined at package level (see package-info.java): javax.persistence.TableGenerator( name="EMP_GEN", table="GENERATOR_TABLE", pkColumnName = "key", valueColumnName = "hi" pkColumnValue="EMP", allocationSize=20 ) javax.persistence.SequenceGenerator( name="SEQ_GEN", sequenceName="my_sequence" ) package org.hibernate.test.metadata; If package-info.java in the org.hibernate.test.metadata package is used to initialize the EJB configura- tion, EMP_GEN and SEQ_GEN are application level generators. EMP_GEN defines a table based id generator using the hilo algorithm with a max_lo of 20. The hi value is kept in a table "GENERATOR_TABLE". The information is kept in a row where pkColumnName "key" is equals to pkColumnValue "EMP" and column valueColumnName "hi" contains the the next high value used. SEQ_GEN defines a sequence generator using a sequence named my_sequence. Note that this version of Hibern- ate Annotations does not handle initialValue and allocationSize parameters in the sequence generator. The next example shows the definition of a sequence generator in a class scope: Entity javax.persistence.SequenceGenerator( name="SEQ_STORE", sequenceName="my_sequence" ) public class Store implements Serializable private Long id; Id GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_STORE") public Long getId() return id; This class will use a sequence named my_sequence and the SEQ_STORE generator is not visible in other classes. Note that you can check the Hibernate Annotations tests in the org.hibernate.test.metadata.id package for more examples. You can define a composite primary key through several syntaxes: • annotate the component property as Id and make the component class Embeddable • annotate the component property as EmbeddedId Hibernate 3.1 beta 9 9Entity Beans • annotate the class as IdClass and annotate each property of the entity involved in the primary key with Id While quite common to the EJB2 developer, IdClass is likely new for Hibernate users. The composite primary key class corresponds to multiple fields or properties of the entity class, and the names of primary key fields or properties in the primary key class and those of the entity class must match and their types must be the same. Let's look at an example: Entity IdClass(FootballerPk.class) public class Footballer //part of the id key Id public String getFirstname() return firstname; public void setFirstname(String firstname) this.firstname = firstname; //part of the id key Id public String getLastname() return lastname; public void setLastname(String lastname) this.lastname = lastname; public String getClub() return club; public void setClub(String club) this.club = club; //appropriate equals() and hashCode() implementation Embeddable public class FootballerPk implements Serializable //same name and type as in Footballer public String getFirstname() return firstname; public void setFirstname(String firstname) this.firstname = firstname; //same name and type as in Footballer public String getLastname() return lastname; public void setLastname(String lastname) this.lastname = lastname; //appropriate equals() and hashCode() implementation As you may have seen, IdClass points to the corresponding primary key class. While not supported by the EJB3 specification, Hibernate allows you to define associations inside a composite Hibernate 3.1 beta 9 10Entity Beans identifier. Simply use the regular annotations for that Entity AssociationOverride( name="id.channel", joinColumns = JoinColumn(name="chan_id") ) public class TvMagazin EmbeddedId public TvMagazinPk id; Temporal(TemporalType.TIME) Date time; Embeddable public class TvMagazinPk implements Serializable ManyToOne public Channel channel; public String name; ManyToOne public Presenter presenter; 2.2.4. Mapping inheritance EJB3 supports the three types of inheritance: • Table per Class Strategy: the union-class element in Hibernate • Single Table per Class Hierarchy Strategy: the subclass element in Hibernate • Joined Subclass Strategy: the joined-subclass element in Hibernate The chosen strategy is declared at the class level of the top level entity in the hierarchy using the Inheritance annotation. Note Annotating interfaces is currently not supported. Table per class This strategy has many drawbacks (esp. with polymorphic queries and associations) explained in the EJB3 spec, the Hibernate reference documentation, Hibernate in Action, and many other places. Hibernate work around most of them implementing this strategy using SQL UNION queries. It is commonly used for the top level of an inheritance hierarchy: Entity Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Flight implements Serializable This strategy support one to many associations provided that they are bidirectional. This strategy does not sup- port the IDENTITY generator strategy: the id has to be shared across several tables. Consequently, when using this strategy, you should not use AUTO nor IDENTITY. Single table per class hierarchy All properties of all super- and subclasses are mapped into the same table, instances are distinguished by a spe- cial discriminator column: Hibernate 3.1 beta 9 11Entity Beans Entity Inheritance(strategy=InheritanceType.SINGLE_TABLE) DiscriminatorColumn( name="planetype", discriminatorType=DiscriminatorType.STRING ) DiscriminatorValue("Plane") public class Plane ... Entity DiscriminatorValue("A320") public class A320 extends Plane ... Plane is the superclass, it defines the inheritance strategy InheritanceType.SINGLE_TABLE. It also defines the discriminator column through the DiscriminatorColumn annotation, a discriminator column can also define the discriminator type. Finally, the DiscriminatorValue annotation defines the value used to differentiate a class in the hierarchy. All of these attributes have sensible default values. The default name of the discriminator column is DTYPE. The default discriminator value is the entity name (as defined in Entity.name) for Discrim- inatorType.STRING. A320 is a subclass; you only have to define discriminator value if you don't want to use the default value. The strategy and the discriminator type are implicit. Inheritance and DiscriminatorColumn should only be defined at the top of the entity hierarchy. Joined subclasses The PrimaryKeyJoinColumn and PrimaryKeyJoinColumns annotations define the primary key(s) of the joined subclass table: Entity Inheritance(strategy=InheritanceType.JOINED) public class Boat implements Serializable ... Entity public class Ferry extends Boat ... Entity PrimaryKeyJoinColumn(name="BOAT_ID") public class AmericaCupClass extends Boat ... All of the above entities use the JOINED strategy, the Ferry table is joined with the Boat table using the same primary key names. The AmericaCupClass table is joined with Boat using the join condition Boat.id = Amer- icaCupClass.BOAT_ID. Inherit properties from superclasses This is sometimes useful to share common properties through a technical or a business superclass without in- cluding it as a regular mapped entity (ie no specific table for this entity). For that purpose you can map them as MappedSuperclass. MappedSuperclass public class BaseEntity Basic Temporal(TemporalType.TIMESTAMP) public Date getLastUpdate() ... public String getLastUpdater() ... ... Hibernate 3.1 beta 9 12Entity Beans Entity class Order extends BaseEntity Id public Integer getId() ... ... In database, this hierarchy will be represented as an Order table having the id, lastUpdate and lastUpdater columns. The embedded superclass property mappings are copied into their entity subclasses. Remember that the embeddable superclass is not the root of the hierarchy though. Note Properties from superclasses not mapped as MappedSuperclass are ignored. Note The access type (field or methods), is inherited from the root entity, unless you use the Hibernate an- notation AccessType Note The same notion can be applied to Embeddable objects to persist properties from their superclasses. You also need to use MappedSuperclass to do that (this should not be considered as a standard EJB3 feature though) Note It is allowed to mark a class as MappedSuperclass in the middle of the mapped inheritance hierarchy. Note Any class in the hierarchy non annotated with MappedSuperclass nor Entity will be ignored. You can override columns defined in entity superclasses at the root entity level using the AttributeOverride annotation. MappedSuperclass public class FlyingObject implements Serializable public int getAltitude() return altitude; Transient public int getMetricAltitude() return metricAltitude; ManyToOne public PropulsionType getPropulsion() return metricAltitude; ... Entity AttributeOverride( name="altitude", column = Column(name="fld_altitude") ) AssociationOverride( name="propulsion", joinColumns = JoinColumn(name="fld_propulsion_fk") ) public class Plane extends FlyingObject ... Hibernate 3.1 beta 9 13Entity Beans The altitude property will be persisted in an fld_altitude column of table Plane and the propulsion associ- ation will be materialized in a fld_propulsion_fk foreign key column. You can define AttributeOverride(s) and AssociationOverride(s) on Entity classes, MappedSuperclass classes and properties pointing to an Embeddable object. 2.2.5. Mapping entity bean associations/relationships One-to-one You can associate entity beans through a one-to-one relationship using OneToOne. There are two cases for one- to-one associations: either the associated entities share the same primary keys values or a foreign key is held by one of the entities (note that this FK column in the database should be constrained unique to simulate one- to-one multiplicity). First, we map a real one-to-one association using shared primary keys: Entity public class Body Id public Long getId() return id; OneToOne(cascade = CascadeType.ALL) PrimaryKeyJoinColumn public Heart getHeart() return heart; ... Entity public class Heart Id public Long getId() ... The one to one is marked as true by using the PrimaryKeyJoinColumn annotation. In the following example, the associated entities are linked through a foreign key column: Entity public class Customer implements Serializable OneToOne(cascade = CascadeType.ALL) JoinColumn(name="passport_fk") public Passport getPassport() ... Entity public class Passport implements Serializable OneToOne(mappedBy = "passport") public Customer getOwner() ... Hibernate 3.1 beta 9 14Entity Beans A Customer is linked to a Passport, with a foreign key column named passport_fk in the Customer table. The join column is declared with the JoinColumn annotation which looks like the Column annotation. It has one more parameters named referencedColumnName. This parameter declares the column in the targeted entity that will be used to the join. Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable. Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work). The association may be bidirectional. In a bidirectional relationship, one of the sides (and only one) has to be the owner: the owner is responsible for the association column(s) update. To declare a side as not responsible for the relationship, the attribute mappedBy is used. mappedBy refers to the property name of the association on the owner side. In our case, this is passport. As you can see, you don't have to (must not) declare the join column since it has already been declared on the owners side. If no JoinColumn is declared on the owner side, the defaults apply. A join column(s) will be created in the owner table and its name will be the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column(s) in the owned side. In this example passport_id be- cause the property name is passport and the column id of Passport is id. Many-to-one Many-to-one associations are declared at the property level with the annotation ManyToOne: Entity() public class Flight implements Serializable ManyToOne( cascade = CascadeType.PERSIST, CascadeType.MERGE ) JoinColumn(name="COMP_ID") public Company getCompany() return company; ... The JoinColumn attribute is optional, the default value(s) is like in one to one, the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column in the owned side. In this example company_id because the property name is company and the column id of Company is id. ManyToOne has a parameter named targetEntity which describes the target entity name. You usually don't need this parameter since the default value (the type of the property that stores the association) is good in al- most all cases. However this is useful when you want to use interfaces as the return type instead of the regular entity. Entity() public class Flight implements Serializable ManyToOne( cascade = CascadeType.PERSIST, CascadeType.MERGE, targetEntity=CompanyImpl.class ) JoinColumn(name="COMP_ID") public Company getCompany() return company; ... public interface Company ... Collections Hibernate 3.1 beta 9 15Entity Beans Overview You can map Collection, List (ie ordered lists, not indexed lists), Map and Set. The EJB3 specification de- scribes how to map an ordered list (ie a list ordered at load time) using javax.persistence.OrderBy annota- tion: this annotation takes into parameter a list of comma separated (target entity) properties to order the collec- tion by (eg firstname asc, age desc), if the string is empty, the collection will be ordered by id. OrderBy currently works only on collections having no association table. For true indexed collections, please refer to the Hibernate Annotation Extensions. EJB3 allows you to map Maps using as a key one of the target entity prop- erty using MapKey(name="myProperty") (myProperty is a property name in the target entity). When using MapKey (without property name), the target entity primary key is used. The map key uses the same column as the property pointed out: there is no additional column defined to hold the map key, and it does make sense since the map key actually represent a target ptoperty. Be aware that once loaded, the key is no longer kept in sync with the property, in other words, if you change the property value, the key will not change automatically in your Java model (Map support the way Hibernate 3 does is currently not supported in this release). Many people confuse map capabilities and MapKey ones. These are two different features. MapKey still has some limitations, please check the forum or the JIRA tracking system for more informations. Hibernate has several notions of collections. Table 2.1. Collections semantics Semantic java representation annotations Bag semantic java.util.List, java.util.Collection org.hibernate.annotations.Collec tionOfElements, OneToMany, ManyToMany List semantic java.util.List org.hibernate.annotations.Collec tionOfElements, OneToMany, ManyToMany + OrderBy, org.hibernate.annotations.Index Column Set semantic java.util.Set org.hibernate.annotations.Collec tionOfElements, OneToMany, ManyToMany Map semantic java.util.Map org.hibernate.annotations.Collec tionOfElements, OneToMany, ManyToMany + MapKey So specifically, java.util.List collections wo OrderBy nor org.hibernate.annotations.IndexColumn are go- ing to be considered as bags. Collection of primitive, core type or embedded objects is not supported by the EJB3 specification. Hibernate Annotations allows them however (see Hibernate Annotation Extensions). Entity public class City OneToMany(mappedBy="city") OrderBy("streetName") public ListStreet getStreets() return streets; ... Hibernate 3.1 beta 9 16

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.