Saturday, 22 September 2012

Hibernate Annotation One-to-One Mapping Example

While the Hibernate documentation section 2.2.5 is a good place to start for a concrete example for an example of a one-to-one annotation based relationship mapping, the example below describes a couple of scenarios and the annotations that worked in setting up the relationships.

Give below is an example of  a One-to-One  bi-directional relationship between a User object and a Registration object,

In the User object, set up the annotations as follows :

@Entity
@Table(name = "user")
public class User implements Serializable {
........
........
private UserRegistration userRegistration;
.........
  @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  @JoinColumn(name = "USR_REG_SYS_ID")
   public UserRegistration getUserRegistration() {
        return this.userRegistration;
    }
.........
} // End of User class

The JoinColumn annotation refers to the to the USER_REGN_ID column in the User table that has a Foreign Key reference to the User_Registration table.

In the UserRegistration object, set up the annotation as follows:

@Entity
@Table(name = " userRegistration")
public class UserRegistration implements Serializable {

........
........
private User user;

........
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "userRegistration")
 public  User  getUser() {
        return this.user;
 }

The mappedBy annotation implies that the userRegistration attribute in the User object manages the relationship reference between the objects. In other words, the User table holds the (Foreign) key reference to the relationship.


1 comment:

Saira said...

Useful annotation examples! For more information on document annotation Apps, click http://groupdocs.com/apps/annotation