OneToMany Mapping Demonstration Using Hibernate Annotation

Hi Friends,as I promised in my last post ,I come again with the demonstration of #OneToMany mapping using Hibernate #annotation using a real life example.
To understand , hibernate Annotation please see my previous post.
To illustrate OneToMany mapping ,I am assuming that every Quote can have many QuoteLineitem. Quote and QuoteLineitem are two separate entities.

Sample Code to demonstrate OneToMany mapping

This sample code includes the pojo/orm classes,DAO class,HibernateSessionFactory Class and Hibernate configuration file.

ORM Classes

package com.nik.hibernate.dto;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Cacheable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.IndexColumn;
import org.hibernate.annotations.Type;

@Entity
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
@Table(name = "QUOTE")
public class Quote implements Serializable {
  /**
   * 
   */
  private static final long serialVersionUID = -1407877852260806165L;
  
  @Id
  @Column(name = "quote_id", unique = true)
  private String quoteID;
  @Column(name = "salesforce_opportunity_id")
  private String salesforceOpportunityID;
  @Column(name = "plan_id")
  private String planID;
  @Column(name = "date")
  @Type(type = "java.util.Date")
  private Date date;
  @Column(name = "org_name")
  private String orgName;
  @Column(name = "org_billing_address")
  private String orgBillingAddress;
  @Column(name = "valid_until")
  @Type(type = "java.util.Date")
  private Date validUntil;
  @Column(name = "payment_terms")
  private String paymentTerms;
  @Column(name = "shipping_address")
  private String shippingAddress;
  @Column(name = "contact_name")
  private String contactName;
  @Column(name = "contact_phone")
  private String contactPhone;
  @Column(name = "contact_email")
  private String contactEmail;
  @Column(name = "sales_name")
  private String salesName;
  @Column(name = "sales_phone")
  private String salesPhone;
  @Column(name = "sales_email")
  private String salesEmail;
  @Column(name = "currency")
  private String currency;
  @OneToMany(cascade = { CascadeType.ALL },  targetEntity = com.nik.hibernate.dto.QuoteLineItem.class)
  @JoinColumn(name = "quote_id")
  @IndexColumn(name = "quotelineitem_idx")
  private List<QuoteLineItem> quoteItems = new ArrayList<QuoteLineItem>();

  public Quote(String quoteID, String salesforceOpportunityID, String planID,
      Date date, String orgName, String orgBillingAddress,
      Date validUntil, String paymentTerms, String shippingAddress,
      String contactName, String contactPhone, String contactEmail,
      String salesName, String salesPhone, String salesEmail,
      String currency) {
    super();
    this.quoteID = quoteID;
    this.salesforceOpportunityID = salesforceOpportunityID;
    this.planID = planID;
    this.date = date;
    this.orgName = orgName;
    this.orgBillingAddress = orgBillingAddress;
    this.validUntil = validUntil;
    this.paymentTerms = paymentTerms;
    this.shippingAddress = shippingAddress;
    this.contactName = contactName;
    this.contactPhone = contactPhone;
    this.contactEmail = contactEmail;
    this.salesName = salesName;
    this.salesPhone = salesPhone;
    this.salesEmail = salesEmail;
    this.currency = currency;
    }

  public String getQuoteID() {
    return quoteID;
  }

  public void setQuoteID(String quoteID) {
    this.quoteID = quoteID;
  }

  public String getSalesforceOpportunityID() {
    return salesforceOpportunityID;
  }

  public void setSalesforceOpportunityID(String salesforceOpportunityID) {
    this.salesforceOpportunityID = salesforceOpportunityID;
  }

  public String getPlanID() {
    return planID;
  }

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

  public Date getDate() {
    return date;
  }

  public void setDate(Date date) {
    this.date = date;
  }

  public String getOrgName() {
    return orgName;
  }

  public void setOrgName(String orgName) {
    this.orgName = orgName;
  }

  public String getOrgBillingAddress() {
    return orgBillingAddress;
  }

  public void setOrgBillingAddress(String orgBillingAddress) {
    this.orgBillingAddress = orgBillingAddress;
  }

  public Date getValidUntil() {
    return validUntil;
  }

  public void setValidUntil(Date validUntil) {
    this.validUntil = validUntil;
  }

  public String getPaymentTerms() {
    return paymentTerms;
  }

  public void setPaymentTerms(String paymentTerms) {
    this.paymentTerms = paymentTerms;
  }

  public String getShippingAddress() {
    return shippingAddress;
  }

  public void setShippingAddress(String shippingAddress) {
    this.shippingAddress = shippingAddress;
  }

  public String getContactName() {
    return contactName;
  }

  public void setContactName(String contactName) {
    this.contactName = contactName;
  }

  public String getContactPhone() {
    return contactPhone;
  }

  public void setContactPhone(String contactPhone) {
    this.contactPhone = contactPhone;
  }

  public String getContactEmail() {
    return contactEmail;
  }

  public void setContactEmail(String contactEmail) {
    this.contactEmail = contactEmail;
  }

  public String getSalesName() {
    return salesName;
  }

  public void setSalesName(String salesName) {
    this.salesName = salesName;
  }

  public String getSalesPhone() {
    return salesPhone;
  }

  public void setSalesPhone(String salesPhone) {
    this.salesPhone = salesPhone;
  }

  public String getSalesEmail() {
    return salesEmail;
  }

  public void setSalesEmail(String salesEmail) {
    this.salesEmail = salesEmail;
  }

  public String getCurrency() {
    return currency;
  }

  public void setCurrency(String currency) {
    this.currency = currency;
  }

  public List<QuoteLineItem> getQuoteItems() {
    return quoteItems;
  }

  public void setQuoteItems(List<QuoteLineItem> quoteItems) {
    this.quoteItems = quoteItems;
  }
}

 

package com.nik.hibernate.dto;

import java.io.Serializable;
import java.math.BigDecimal;

import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Type;

@Entity
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
@Table(name = "QUOTE_LINEITEM")
public class QuoteLineItem implements Serializable {
 /**
 * 
 */
 private static final long serialVersionUID = -7021025790629327013L;
 @Id
 @Column(name = "quotelineitem_id", unique = true)
 private String quoteLineItemID;
 @Column(name = "quote_id")
 private String quoteID;
 @Column(name = "service_id")
 private String serviceID;
 @Column(name = "description")
 private String description;
 @Column(name = "type")
 private String type;
 @Column(name = "unit")
 private String unit;
 @Column(name = "rate")
 @Type(type = "java.math.BigDecimal")
 private java.math.BigDecimal rate;
 @Column(name = "quantity")
 @Type(type = "java.math.BigDecimal")
 private java.math.BigDecimal quantity;
 @Column(name = "amount")
 @Type(type = "java.math.BigDecimal")
 private java.math.BigDecimal amount;

 public QuoteLineItem(String quoteLineItemID,String quoteID, String serviceID, String description,
 String type, String unit, BigDecimal rate, BigDecimal quantity,
 BigDecimal amount) {
 super();
 this.quoteLineItemID=quoteLineItemID;
 this.quoteID = quoteID;
 this.serviceID = serviceID;
 this.description = description;
 this.type = type;
 this.unit = unit;
 this.rate = rate;
 this.quantity = quantity;
 this.amount = amount;
 }

 public String getQuoteLineItemID() {
 return quoteLineItemID;
 }

 public void setQuoteLineItemID(String quoteLineItemID) {
 this.quoteLineItemID = quoteLineItemID;
 }

 public String getQuoteID() {
 return quoteID;
 }

 public void setQuoteID(String quoteID) {
 this.quoteID = quoteID;
 }

 public String getServiceID() {
 return serviceID;
 }

 public void setServiceID(String serviceID) {
 this.serviceID = serviceID;
 }

 public String getDescription() {
 return description;
 }

 public void setDescription(String description) {
 this.description = description;
 }

 public String getType() {
 return type;
 }

 public void setType(String type) {
 this.type = type;
 }

 public String getUnit() {
 return unit;
 }

 public void setUnit(String unit) {
 this.unit = unit;
 }

 public java.math.BigDecimal getRate() {
 return rate;
 }

 public void setRate(java.math.BigDecimal rate) {
 this.rate = rate;
 }

 public java.math.BigDecimal getQuantity() {
 return quantity;
 }

 public void setQuantity(java.math.BigDecimal quantity) {
 this.quantity = quantity;
 }

 public java.math.BigDecimal getAmount() {
 return amount;
 }

 public void setAmount(java.math.BigDecimal amount) {
 this.amount = amount;
 }
}


package com.nik.hibernate.dao;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.nik.hibernate.dto.Quote;
import com.nik.hibernate.dto.QuoteLineItem;
import com.nik.util.HibernateSessionFactory;

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

    System.out.println("Hibernate One-To-Many example (Annotation)");
    
    SessionFactory sf = HibernateSessionFactory.getSessionFactory();
    Session session = sf.getCurrentSession();
    session.beginTransaction();
    Quote quote=new Quote("q1", "salesforceOpportunityID", "planID",new Date(), "orgName", "orgBillingAddress", new Date(),"paymentTerms", "shippingAddress", "contactName", "contactPhone","contactEmail","salesName","salesPhone","salesEmail"," currency");
    List<QuoteLineItem> quoteItemList=new ArrayList<QuoteLineItem>();
    for(int i=0;i<=10;i++){
      quoteItemList.add(new QuoteLineItem("qLineItem"+i,"q1","service"+i,"description","type"+1,"unit" ,new BigDecimal(i),new BigDecimal(i),new BigDecimal(i*i)));
    }
    quote.setQuoteItems(quoteItemList);
    session.save(quote);
    
    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.Quote" />
    <mapping class="com.sysvana.dto.QuoteLineItem" />
    

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

I hope you like this post and this real life example will help you to understand OneToMany hibernate mapping using annotations. Will come with best practices for hibernate mapping and cascading concept. Till then enjoy coding.Feel free to comment and post your feedback if any.

1 Response

  1. Esmaria says:

    You’re an extremely practical website; could not
    make it without ya! http://tinyurl.com/jjl3tn9

Leave a Reply

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