Sunday, January 23, 2011

Hibernate One to Many example

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>
        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
        <property name="hibernate.connection.username">test</property>
        <property name="hibernate.connection.password">test</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
      
<mapping resource="vendor.hbm.xml"/>
<mapping resource="customer.hbm.xml"/>
 </session-factory>
</hibernate-configuration>


customer.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Customer" table="CUST">
<id name="cid" column="CID">
<generator class="increment"/>
</id>
<property name="cnm" column="CNM" type="string"/>
<property name="vidfk" column="VIDFK"/>
</class>
</hibernate-mapping>

vendor.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="Vendar" table="VEND">
    <id name="vid" column="VID">
    <generator class="increment" />
    </id>
    <property name="vnm" column="VNAME" type="java.lang.String"/>
    <set name="custs" cascade="all"  lazy="true" inverse="true" fetch="join">
       <key column="VIDFK" />
       <one-to-many class="Customer"/>
      </set>
    </class>
</hibernate-mapping>

Vendor.java :

package com.test.hibernate;
/**
 * @author Mallik
 *
 */
import java.util.*;
public class Vendar {
    /**
     * DataMembers Declaration
     *
     */
private int vid;
private String vnm;
private Set custs;

//setters&getters
public int getVid() {
    return vid;
}
public void setVid(int vid) {
    this.vid = vid;
}
public String getVnm() {
    return vnm;
}
public void setVnm(String vnm) {
    this.vnm = vnm;
}
public Set getCusts() {
    return custs;
}
public void setCusts(Set custs) {
    this.custs = custs;
}
}
Customer.java  :
package com.test.hibernate;
/**
 * @author Mallik
 *
 */
public class Customer {
    
    /**
     * DataMembers Declaration
     *
     */
    private int cid;
    private String cnm;
    private int vidfk;
    
    //setters&getters
    public int getCid() {
        return cid;
    }
    public void setCid(int cid) {
        this.cid = cid;
    }
    public String getCnm() {
        return cnm;
    }
    public void setCnm(String cnm) {
        this.cnm = cnm;
    }
    public int getVidfk() {
        return vidfk;
    }
    public void setVidfk(int vidfk) {
        this.vidfk = vidfk;
    }
}


Test.java :
package com.test.hibernate;
/**
 * @author Mallik
 *
 */
import java.util.*;
import org.hibernate.cfg.*;
import org.hibernate.*;
public class Test {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Session ses=new Configuration().configure().buildSessionFactory().openSession();
        Vendar v=new Vendar();
    //v.setVid(14);
        v.setVnm("RAJU");
        Set set=new HashSet();
        Customer c1=new Customer();
        c1.setCnm("cust1");
        //c1.setCid(22);
        c1.setVidfk(v.getVid());
        
        set.add(c1);
        
        Customer c2=new Customer();
        c2.setCnm("cust2");
        //c2.setCid(61);
        c2.setVidfk(v.getVid());
        set.add(c2);
        
        v.setCusts(set);
        
        Transaction transaction = null;
        try {
        transaction = ses.beginTransaction();
        ses.save(v);
        transaction.commit();
        System.out.println("okkkkkkkkkkk");
        } catch (Exception e)
        {
            System.out.println(e);
        if (transaction != null) {
        transaction.rollback();
        }
        } finally {
        ses.close();
        }
    }
}

Select.java :
package com.test.hibernate;
/**
 * @author Mallik
 *
 */
import java.util.*;
import org.hibernate.cfg.*;
import org.hibernate.*;
public class Select {
    /**
     * @param args
     */
    public static void main(String[] args)throws Exception {
        // TODO Auto-generated method stub
        
        //getting Session object
Session ses=new Configuration().configure().buildSessionFactory().openSession();
Object o=ses.get(Vendar.class,new Integer(11));
//typecasting Object class into Vendar class
Vendar v=(Vendar)o;
System.out.println("vendar Name:"+v.getVnm());
        Set s=v.getCusts();
        
        //using iterator() to retrieve Data from Set CollectionFrameWork
        Iterator it=s.iterator();
        while(it.hasNext())
        {
            Object o1=it.next();
            Customer c=(Customer)o1;
            
            System.out.println("Customer ID:"+c.getCid());
            System.out.println("Customer Name:"+c.getCnm());
            System.out.println("Customer Name:"+c.getVidfk());
        }
        ses.close();
    }
}

1 comment:

Anonymous said...

very good tutorial. simple and easy to understand