One To One Mapping Using Hibernate Annotaion

Hi friends, in this post, I am going to demonstrate One to One mapping implementation using hibernate.
Before going to do the sample code,I would like to introduce annotation.

Hibernate Annotation

Annotation is a powerful way which replaces the XML and other properties file configuration.Hibernate annotation provides the metadata for the Object and Relational Table mapping.The hibernate annotation introduced from Hibernate 3.X.
Now to illustrate the one to one mapping, let’s assume one scenario in which Organization is an entity with following attributes mentioned in the Pojo class.Further, we proceed  with the assumption that every Organization has a single Contract .Hence each Organization is related to one OrganizationContract which represents one to one relationships.

  Sample Code to demonstrate One to One mapping

OneToOne Hibernate Mapping

package com.nik.hibernate.dto;

import java.io.Serializable;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity
@Table(name = "ORGANIZATION")
public class Organization implements Serializable {
 /**
 * 
 */
 private static final long serialVersionUID = 1083220907162313257L;
 public Organization(String orgID, String orgCode, String displayName,
 String domain, List<String> technicalContact,
 List<String> billingContact, List<String> administrationContact,
 String organizationLogo, double siCreditLimit) {
 super();
 this.orgID = orgID;
 this.orgCode = orgCode;
 this.displayName = displayName;
 this.domain = domain;
 this.technicalContact = technicalContact;
 this.billingContact = billingContact;
 this.administrationContact = administrationContact;
 this.organizationLogo = organizationLogo;
 this.siCreditLimit = siCreditLimit;
}

@Id
 @Column(name = "id", unique = true)
 private String orgID;
 @Transient
 private String orgCode;
 @Column(name = "name")
 private String displayName;
 @Column(name = "org_domainname")
 private String domain;
 @Transient
 private List<String> technicalContact;
 @Transient
 private List<String> billingContact;
 @Transient
 private List<String> administrationContact;
 @Transient
 private String organizationLogo;
 @Transient
 private double siCreditLimit;
 @OneToOne(mappedBy="organization" , cascade=CascadeType.ALL)
 private OrganizationContract orgContract;

 public String getOrgID() {
 return orgID;
 }

 public void setOrgID(String orgID) {
 this.orgID = orgID;
 }

 public String getOrganizationLogo() {
 return organizationLogo;
 }

 public void setOrganizationLogo(String organizationLogo) {
 this.organizationLogo = organizationLogo;
 }

 
 public String getOrgCode() {
 return orgCode;
 }

 public void setOrgCode(String orgCode) {
 this.orgCode = orgCode;
 }

 public String getDisplayName() {
 return displayName;
 }

 public void setDisplayName(String displayName) {
 this.displayName = displayName;
 }


 public String getDomain() {
 return domain;
 }

 public void setDomain(String domain) {
 this.domain = domain;
 }

 public List<String> getTechnicalContact() {
 return technicalContact;
 }

 public void setTechnicalContact(List<String> technicalContact) {
 this.technicalContact = technicalContact;
 }

 public List<String> getBillingContact() {
 return billingContact;
 }

 public void setBillingContact(List<String> billingContact) {
 this.billingContact = billingContact;
 }

 public List<String> getAdministrationContact() {
 return administrationContact;
 }

 public void setAdministrationContact(List<String> administrationContact) {
 this.administrationContact = administrationContact;
 }

 public double getSiCreditLimit() {
 return siCreditLimit;
 }

 public void setSiCreditLimit(double siCreditLimit) {
 this.siCreditLimit = siCreditLimit;
 }

public OrganizationContract getOrgContract() {
 return orgContract;
}

public void setOrgContract(OrganizationContract orgContract) {
 this.orgContract = orgContract;
}
}
package com.nik.hibernate.dto;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.PrimaryKeyJoinColumn;
//import org.hibernate.annotations.Type;

@Entity
@Table(name = "ORG_CONTRACT")
public class OrganizationContract implements Serializable {
 /**
 * 
 */
 private static final long serialVersionUID = -6194397757243435418L;
 @Id
 @Column(name = "id")
 private String contractID;
 @Column(name = "org_id")
 private String orgID;
 @Column(name = "plan_id")
 private String planID;
 @Column(name = "start_date")
// @Type(type = "java.util.Date")
 private Date startDate;
 @Column(name = "end_date")
// @Type(type = "java.util.Date")
 private Date endDate;
 @Column(name = "signed_on")
 private String signedOn;
 @Column(name="term")
 private String term;
 @Column(name = "sales_person")
 private String salesPerson;
 
 @OneToOne
 @PrimaryKeyJoinColumn
 private Organization organization;

 public OrganizationContract(String contractID, String orgID, String planID,
 Date startDate, Date endDate, String signedOn, String term,
 String salesPerson) {
 super();
 this.contractID = contractID;
 this.orgID = orgID;
 this.planID = planID;
 this.startDate = startDate;
 this.endDate = endDate;
 this.signedOn = signedOn;
 this.term = term;
 this.salesPerson = salesPerson;
}

public String getContractID() {
 return contractID;
 }

 public void setContractID(String contractID) {
 this.contractID = contractID;
 }

 public String getOrgID() {
 return orgID;
 }

 public void setOrgID(String orgID) {
 this.orgID = orgID;
 }

 public String getPlanID() {
 return planID;
 }

 public void setPlanID(String planID) {
 this.planID = planID;
 }

 

 public Date getStartDate() {
 return startDate;
 }

 public void setStartDate(Date startDate) {
 this.startDate = startDate;
 }

 public Date getEndDate() {
 return endDate;
 }

 public void setEndDate(Date endDate) {
 this.endDate = endDate;
 }

 public String getTerm() {
 return term;
 }

 public void setTerm(String term) {
 this.term = term;
 }

 public String getSignedOn() {
 return signedOn;
 }

 public void setSignedOn(String signedOn) {
 this.signedOn = signedOn;
 }

 public String getSalesPerson() {
 return salesPerson;
 }

 public void setSalesPerson(String salesPerson) {
 this.salesPerson = salesPerson;
 }

public Organization getOrganization() {
 return organization;
}

public void setOrganization(Organization organization) {
 this.organization = organization;
}
}
package com.nik.hibernate.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.nik.hibernate.dto.Organization;
import com.nik.hibernate.dto.OrganizationContract;
import com.nik.util.HibernateSessionFactory;

public class OrganizationLocalService {
  @SuppressWarnings("unchecked")
  public static void main(String[] args) {

    System.out.println("Hibernate One-To-One example (Annotation)");
    
    SessionFactory sf = HibernateSessionFactory.getSessionFactory();
    Session session = sf.getCurrentSession();
    session.beginTransaction();

    OrganizationContract orgContract = new OrganizationContract("10th Street", "LA", "San Francisco", null, null, "U.S.", null, null);
    
    Organization org = new Organization("org001", "o11", "TestOrg", "test.org", null,null,null, null,0.0);
    org.setOrgContract(orgContract);	
    
    
    session.save(org);

    
    session.getTransaction().commit();
    session.close();

  }
}

 Hibernate Supporting Classes & Configuration

package com.nik.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

 
public class HibernateSessionFactory {
 
    private static final SessionFactory sessionFactory = buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure()
                    .buildSessionFactory();

        } catch (Exception e) {
            System.err.println("SessionFactory creation failed due to " + e);
            throw new ExceptionInInitializerError(e);
        }
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

 hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.datasource">java:comp/env/jdbc/hibernatetute</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <!-- auto management of contextual session -->
    <property name="hibernate.current_session_context_class">thread</property>

    <!-- Changes implementing second level and query cache -->
  
    <mapping class="com.sysvana.dto.Organization" />
    <mapping class="com.sysvana.dto.OrganizationContract" />
    

  </session-factory>
</hibernate-configuration>

 

I hope you like this post and this will help you to understand basics of hibernate mapping using annotations. Will come up with  other important mappings concept which is more practical and real life scenarios. Till then enjoy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *