Thursday, August 22, 2013

Hibernate ( Mapping – One-To-One ) Annotation Application

Hibernate ( Mapping – One-To-One ) Annotation Application

Hibernate ( Mapping – One-To-One ) Application

One-to-one relationship occurs when one entity is mapping exactly one occurrence in another entity.

A one-to-one relationship table design, a “stock” table contains exactly one record in “stockdetails” table.
Both tables have the same stockid as primary key.
In “stockdetails” table, stockid is the primary key and also a foreign key to STOCK table.

CREATE TABLE IF NOT EXISTS `stock` (
`stockid` int(11) NOT NULL,
`stockcode` varchar(50) NOT NULL,
`stockname` varchar(100) NOT NULL,
PRIMARY KEY (`stockid`),
UNIQUE KEY `stockcode` (`stockcode`,`stockname`)
)

CREATE TABLE IF NOT EXISTS `stockdetails` (
`stockid` int(11) NOT NULL,
`companyname` varchar(100) NOT NULL,
`companydesc` varchar(100) NOT NULL,
`remark` varchar(50) NOT NULL,
`listeddate` date NOT NULL,
PRIMARY KEY (`stockid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `stockdetails`
ADD CONSTRAINT `stockdetails_ibfk_1` FOREIGN KEY (`stockid`) REFERENCES `stock` (`stockid`) ON DELETE CASCADE ON UPDATE CASCADE;


Step 1 - Create POJO (Model) classes ( Stock.java and StockDetails.java)
Step 2 - Hibernate Configurations ( hibernate.cfg.xml )
Step 3 - Create class to do the execution ( ExecuteApplication.java ) 

Step 1 - Create POJO classes 
 
Create POJO (Plain Old Java Object) classes that represents the Stock, and StockDetails.

package pojo;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table( name = "stock", catalog = "myworkspace",
uniqueConstraints = {
@UniqueConstraint( columnNames = "stockcode" ),
@UniqueConstraint( columnNames = "stockname" )
})
public class Stock implements Serializable {

   /**
  *
  */
   private static final long serialVersionUID = 1L;
   @Id
   @Column(name = "stockid", unique = true, nullable = false)
   private Integer stockId;
   @Column(name = "stockcode", unique = true, nullable = false, length = 10)
   private String stockCode;
   @Column(name = "stockName", unique = true, nullable = false, length = 50)
   private String stockName;
   @OneToOne( fetch = FetchType.LAZY, mappedBy = "stock", cascade =   CascadeType.ALL)
   private StockDetails stockDetails;

   //TODO generate getters and setters
}

-----------------------------------------------------------------------------------------------------------------------------

package pojo;

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

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table (name = "stockdetails", catalog = "myworkspace")
public class StockDetails implements Serializable{
 
  /**
  *
  */
  private static final long serialVersionUID = 1L;
  
  @Id
  @GenericGenerator( name = "generator",
  strategy = "foreign",
  parameters = @Parameter ( name = "property", value = "stock"))
  @GeneratedValue( generator = "generator")
  @Column ( name = "stockid", unique = true, nullable = false)
  private Integer stockId;
 
  @Column ( name = "companyname", nullable = false)
  private String compName;
 
  @Column ( name = "companydesc", nullable = false)
  private String compDesc;
 
  @Column ( name = "remark", nullable = false)
  private String remark;
 
  @Column ( name = "listeddate", nullable = false)
  private Date listedDate;
 
  @OneToOne(fetch = FetchType.LAZY)
  @PrimaryKeyJoinColumn
  private Stock stock;

  //TODO generate getters and setters
}

Step 2 - Hibernate Configurations

Create configuration file name as hibernate.cfg.xml and save it.

<?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>
          <!-- SQL dialect -->
          <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
          <!-- Database connection settings -->
          <property name="hibernate.connection.url">jdbc:mysql://localhost:3306 /myworkspace</property>
          <property name="hibernate.connection.username">root</property>
          <property name="hibernate.connection.password">res13pg</property>
          <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
          <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
          <!-- Echo all executed SQL to stdout -->
          <property name="show_sql">true</property>
 
          <mapping class="pojo.Stock"/>
          <mapping class="pojo.StockDetails"/>
        </session-factory>
    </hibernate-configuration>
 

Step 3 - Create Execute class

Create a ExecuteApplication class to do the execution.

package impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import pojo.Stock;
import pojo.StockDetails;

public class ExecuteApplication {

   /**
   * @param args
   */
   public static void main(String[] args) {
      ExecuteApplication executeEmployee = new ExecuteApplication();
      executeEmployee.addStock();
      executeEmployee.listStocks();
   }

   private void addStock(){
      Transaction transaction = null;
      Session hbSession = new     AnnotationConfiguration().configure("config/hibernate.cfg.xml")
 .buildSessionFactory().openSession();
 
      try{
          transaction = hbSession.beginTransaction();
    
          Stock stock = new Stock();
          stock.setStockId(123456);
          stock.setStockCode("NB100");
          stock.setStockName("Notebooks");

          StockDetails stockDetails = new StockDetails();
          stockDetails.setCompName("Abans");
          stockDetails.setCompDesc("Pionior in Notebooks");
          stockDetails.setRemark("Good Service");
          stockDetails.setListedDate(new Date());
          stock.setStockDetails(stockDetails);
          stockDetails.setStock(stock);

          hbSession.save(stock);
          hbSession.getTransaction().commit();
          System.out.println("Insert the Stock Record");
      }catch (Exception e) {
          if(null != transaction){
              transaction.rollback();
          }
          e.printStackTrace();
      }finally{
          hbSession.flush();
          hbSession.close();
      }
  }

  private void listStocks(){
        Transaction transaction = null;
        Session hbSession = new AnnotationConfiguration().configure("config/hibernate.cfg.xml")
.buildSessionFactory().openSession();
         try{
             transaction = hbSession.beginTransaction();
             @SuppressWarnings("unchecked")
             List<Stock> stockList = hbSession.createQuery("FROM Stock").list();
              
             for(Iterator<Stock> iterator = stockList.iterator(); iterator.hasNext();){
                   Stock stock = iterator.next();
                   System.out.println("");
                   System.out.println("StockId : " + stock.getStockId());
                   System.out.println("StockCode : " + stock.getStockCode());
                   System.out.println("StockName : " + stock.getStockName());
                   System.out.println("CompanyName : " +  stock.getStockDetails().getCompName());
                   System.out.println("CompanyDesc : " + stock.getStockDetails().getCompDesc());
                   System.out.println("Remark : " + stock.getStockDetails().getRemark());
                   System.out.println("ListedDate : " + stock.getStockDetails().getListedDate());
              }
              hbSession.getTransaction().commit();
         }catch (Exception e) {
               if(null != transaction){
                     transaction.rollback();
               }
               e.printStackTrace();
          }finally{
               hbSession.flush();
               hbSession.close();
          }
     }
}
 

Out put on the above application as follows.