Thursday, August 22, 2013

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

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

Hibernate ( Mapping – One-To-One ) XML 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 - Create mapping files ( stock.hbm.xml and stockdetails.hbm.xml )
Step 3 - Hibernate Configurations ( hibernate.cfg.xml )
Step 4 - 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;

public class Stock implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;
private Integer stockId;
private String stockCode;
private String stockName;
private StockDetails stockDetails;

//TODO Generate getters and setters
}


package pojo;

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

public class StockDetails implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;
private Integer stockId;
private String compName;
private String compDesc;
private String remark;
private Date listedDate;
private Stock stock;

//TODO Generate getters and setters
}

Step 2 - Create mapping file

Create a mapping file “Stock.hbm.xml” which maps “StockDetails.java” POJO and the “employee” table in the database.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
       <hibernate-mapping>
            <class name="pojo.Stock" table="stock">
                 <id name="stockId" type="java.lang.Integer">
                    <column name="stockid" />
                    <generator class="assigned" />
                </id>
                <property name="stockCode" type="string">
                     <column name="stockCode" length="10" not-null="true" unique="true" />
                </property>
                <property name="stockName" type="string">
                    <column name="stockname" length="20" not-null="true" unique="true" />
                </property>
 
                <one-to-one name="stockDetails" class="pojo.StockDetails"
                        cascade="save-update"></one-to-one>
            </class>
     </hibernate-mapping>


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
         "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
          <hibernate-mapping>
               <class name="pojo.StockDetails" table="stockdetails">
                   <id name="stockId" type="java.lang.Integer">
                        <column name="stockid" />
                          <generator class="foreign">
                             <param name="property">stock</param>
                          </generator>
                  </id>
                  <property name="compName" type="string">
                       <column name="companyname" length="100" not-null="true"/>
                  </property>
                  <property name="compDesc" type="string">
                       <column name="companydesc" length="100" not-null="true"/>
                  </property>
                  <property name="remark" type="string">
                       <column name="remark" length="50" not-null="true"/>
                  </property>
                  <property name="listedDate" type="java.util.Date">
                       <column name="listeddate" length="4" not-null="true"/>
                  </property>  
                  <one-to-one name="stock" class="pojo.Stock" constrained="true"></one-to-one>
             </class>
       </hibernate-mapping>
 
 
Step 3 - 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 resource="hbm/Stock.hbm.xml"/>
               <mapping resource="hbm/StockDetails.hbm.xml"/>
             </session-factory>
        </hibernate-configuration>


Step 4 - 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 org.hibernate.cfg.Configuration;

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 Configuration().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 Configuration().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();
       }
   }
}