Hibernate O/R Mapping

Object/relational mappings can be done with following approaches:

-> using Java 5 annotations (via the Java Persistence 2 annotations)

-> using the Hibernate legacy XML files approach known as hbm.xml

We will now discuss the concepts of mapping documents (both annotations and XML).

Entity: An entity is a regular Java object which will be persisted by Hibernate.

Identifiers: Mapped classes must declare the primary key column of the database table.

Property: You need to decide which property needs to be made persistent in a given entity. In the annotations world, every non static non transient property of an entity is considered persistent, unless you annotate it as @Transient. Not having an annotation for your property is equivalent to the appropriate @Basic annotation.

-->Embeddable Objects: Embeddable objects are the objects whose properties are mapped to the same table as owning entity. We can use the same using annotation @Embedded and @Embeddable

-->Inheritance strategy: Java is a language which allows inheritance where one class can inherit other whereas Relational databases have no concept of inheritance. Hibernate defines several inheritance mechanisms, mainly defined though the @Inheritance annotation or the element

Several strategy to map the same with hibernate:

-->Single table per class hierarchy strategy

In this type of strategy one single table is used to map the hierarchy and an extra column is used to which act as a discrminator to identify the class. Table will have a column for every attribute of every class in the hierarchy. A discriminator column is used to determine which class the particular row belongs to, each class in the hierarchy defines its own unique discriminator value.

-->Table per concrete class strategy

In this type of strategy tables are created per class and related by primary and foreign key. But duplicate column is added in subclass tables.

-->Table per class strategy

In this type of strategy tables are created per class and related by primary and foreign key. No duplicate columns. A discriminator column is not required for this mapping strategy. Each subclass must, however, declare a table column holding the object identifier.

-->Mapping one to one and one to many associations:

In Database, data of one table can be associated with another using column mapping. So we need to do some kind of association among entities also. To mark an association, we can use @ManyToOne or @OnetoOne.