Search This Blog

Tuesday, 27 August 2013

One -to-One & One-to-many & many to one & many to many association in hibernate demonstration

Hibernate - one to one xml declaration:

AbcParentEntity.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="com.xyz.entity.AbcParentEntity" table="PARENT_TABLE">
<id name="parentId" type="short">
            <column name="PARENT_COL_ID" precision="4" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="name" type="string">
            <column name="PARENT_COL_NAME" length="200" />
        </property>

<one-to-one name="childObject" class="com.xyz.entity.AbcChildEntity" cascade="all" />
</class>
</hibernate-mapping>

AbcChildEntity.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="com.xyz.entity.AbcChildEntity" table="CHILD_TABLE_1">
        <id name="childId" type="short">
            <column name="CHILD_TAB_COL_ABC_ID" precision="4" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="childName" type="string">
            <column name="CHILD_TAB_COL_ABC_NAME" length="200" />
        </property>
    </class>

</hibernate-mapping>




One-to-many association in hibernate demonstration


AbcParentEntity.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="com.xyz.entity.AbcParentEntity" table="PARENT_TABLE">
        <id name="parentId" type="short">
            <column name="PARENT_COL_ID" precision="4" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="name" type="string">
            <column name="PARENT_COL_NAME" length="200" />
        </property>
        <set name="childObjects1" table="CHILD_TABLE_1" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="CHILD_TAB_COL_ABC_ID" precision="22" scale="0" />
            </key>
            <one-to-many class="com.xyz.entity.AbcChildEntity" />
        </set>
        <set name="childObjects2" table="CHILD_TABLE_2" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="CHILD_TAB_COL_XYZ_ID" precision="4" scale="0" />
            </key>
            <one-to-many class="com.xyz.entity.XyzChildEntity" />
        </set>
    </class>
</hibernate-mapping>

AbcChildEntity.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="com.xyz.entity.AbcChildEntity" table="CHILD_TABLE_1">
        <id name="childId" type="short">
            <column name="CHILD_TAB_COL_ABC_ID" precision="4" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="childName" type="string">
            <column name="CHILD_TAB_COL_ABC_NAME" length="200" />
        </property>
    </class>
</hibernate-mapping>

XyzChildEntity.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="com.xyz.entity.XyzChildEntity" table="CHILD_TABLE_2">
        <id name="xyzId" type="big_decimal">
            <column name="CHILD_TAB_COL_XYZ_ID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="xyzName" type="string">
            <column name="CHILD_TAB_COL_XYZ_NAME" length="200" />
        </property>
    </class>
</hibernate-mapping>

AbcParentEntity.java
=================================================

package com.xyz.entity;

import java.util.Set;

import java.io.Serializable;

public class AbcParentEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    private Short parentId;

    private String name;

    private Set<XyzChildEntity> childObjects2;

    private Set<AbcChildEntity> childObjects1;

    public AbcParentEntity() {
    }

    public Short getParentId() {
        return this.parentId;
    }

    public void setParentId(Short parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public Set<AbcChildEntity> getChildObjects1() {
        return this.childObjects1;
    }

    public void setChildObjects1(Set<AbcChildEntity> childObjects1) {
        this.childObjects1 = childObjects1;
    }

    public Set<XyzChildEntity> getChildObjects2() {
        return this.childObjects2;
    }

    public void setChildObjects2(Set<XyzChildEntity> childObjects2) {
        this.childObjects2 = childObjects2;
    }
}
AbcChildEntity.java
===============================================

package com.xyz.entity;

import java.io.Serializable;

public class AbcChildEntity implements Serializable {
   
    private static final long serialVersionUID = 1L;

    private Short childId;

    private String subVerticalName;


    public AbcChildEntity() {
    }

    public Short getChildId() {
        return this.childId;
    }

    public void setChildId(Short childId) {
        this.childId = childId;
    }

    public String getChildName() {
        return this.childName;
    }

    public void setChildName(String childName) {
        this.childName = childName;
    }


}

XyzChildEntity.java
==============================================

package com.xyz.entity;

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


public class XyzChildEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    private BigDecimal xyzId;

    private String customerName;

    public XyzChildEntity() {
    }

    public BigDecimal getXyzId() {
        return this.xyzId;
    }

    public void setXyzId(BigDecimal xyzId) {
        this.customerId = xyzId;
    }

    public String getCustomerName() {
        return this.customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

}


Hibernate - many to one xml declaration:

AbcParentEntity.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="com.xyz.entity.AbcParentEntity" table="PARENT_TABLE">
<id name="parentId" type="short">
            <column name="PARENT_COL_ID" precision="4" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="name" type="string">
            <column name="PARENT_COL_NAME" length="200" />
        </property>

</class>
</hibernate-mapping>

AbcChildEntity.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="com.xyz.entity.AbcChildEntity" table="CHILD_TABLE_1">
        <id name="childId" type="short">
            <column name="CHILD_TAB_COL_ABC_ID" precision="4" scale="0" />
            <generator class="assigned" />
        </id>

        <property name="childName" type="string">
            <column name="CHILD_TAB_COL_ABC_NAME" length="200" />
        </property>

<many-to-one name="parentObject" class="com.xyz.entity.AbcParentEntity" cascade="all" />

    </class>
</hibernate-mapping>

Hibernate Many to Many xml declaration:

Tables:

Table_name   Column_Names
 Company company_id, company_name
  Item                   item_id, item_name
Com_Item        company_id, item_id

AbcCompany.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="com.abc.AbcCompany" table="Company">
        <id name="companyId" type="java.lang.Integer">
            <column name="company_id" />
            <generator class="identity" />
        </id>
        <property name="companyName" type="string">
            <column name="company_name" length="10" not-null="true" unique="true" />
        </property>
        <set name="items" table="Com_Item"
        inverse="false" lazy="true" fetch="select" cascade="all" >
            <key>
                <column name="company_id" not-null="true" />
            </key>
            <many-to-many entity-name="com.abc.AbcItem">
                <column name="item_id" not-null="true" />
            </many-to-many>
        </set>
    </class>
</hibernate-mapping>

AbcItem.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="com.abc.AbcItem" table="Item">
        <id name="itemId" type="java.lang.Integer">
            <column name="item_id" />
            <generator class="identity" />
        </id>
        <property name="itemName" type="string">
            <column name="item_name" length="10" not-null="true" unique="true" />
        </property>
        <set name="companies" table="Com_Item"
        inverse="false" lazy="true" fetch="select" cascade="all" >
            <key>
                <column name="item_id" not-null="true" />
            </key>
            <many-to-many entity-name="com.abc.AbcCompany">
                <column name="company_id" not-null="true" />
            </many-to-many>
        </set>
    </class>
</hibernate-mapping>


Table Per Class Hierarchy 

table_name column_names
  Card                   cid, amt,type, ctype, dctype

Card.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="com.xyz.Card" table="Card">
<id name="cardId" column="cid" />
<discriminator column="dcolumn" type="string" length="5"/>
<property name="" column="amt" />

<subclass name="com.xyz.CreditCard" discriminator-value="CC">
<property name="creditCardType" column="cctype" length="10" />
</subclass>

<subclass name="com.xyz.DebitCard" discriminator-value="DC">
<property name="debitCardType" column="dctype" length="10" />
</subclass>

</class>

</hibernate-mapping>


Table Per Concrete class

table_name column_names
  Card                   cid, amt
  Credit_Card          cid, amt, ctype
  Debit_Card           cid, amt, dctype

<?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="com.xyz.Card" table="Card">
<id name="cardId" column="cid" />
<property name="" column="amt" />

<union-subclass name="com.xyz.CreditCard" table="Credit_Card">
<property name="creditCardType" column="cctype" length="10" />
</union-subclass>

<union-subclass name="com.xyz.DebitCard" table="Debit_Card">
<property name="debitCardType" column="dctype" length="10" />
</union-subclass>

</class>
       
</hibernate-mapping>


Table Per Sub class

table_name column_names
  Card                   cid, amt
  Credit_Card          ccid, ctype
  Debit_Card           cdid, dctype


<?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="com.xyz.Card" table="Card">
<id name="cardId" column="cid" />
<property name="" column="amt" />

<joined-subclass name="com.xyz.CreditCard" table="Credit_Card">
<key column="ccId"></key>  
<property name="creditCardType" column="cctype" length="10" />
</joined-subclass>

<joined-subclass name="com.xyz.DebitCard" table="Debit_Card">
<key column="dcId"></key>  
<property name="debitCardType" column="dctype" length="10" />
</joined-subclass>

</class>
       
</hibernate-mapping>

Monday, 26 August 2013

Reading Excel file data and making java objects Example by using POI-API

Note: .xlsx Which will accommodate more number of rows(maximum 1,048,576). Usually in .xls format which will throw java heap space problem, can’t create more than 65,000 rows.


Reading Excel file data and making java objects Example by using POI-API


ExcelReader.java
===============================================

import java.math.BigDecimal;

import java.util.List;

import java.util.Map;

import java.util.ArrayList;

import java.util.HashMap;

import java.io.FileInputStream;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import com.xyz.vo.CourseVo;

public class ExcelReader {

    private static final Logger LOG = LoggerFactory.getLogger(ExcelReader.class);

    public List<CourseVo> readDataFromExcel(String filePath){

        Map<String,Object> map = readExcelSheet(filePath);

        LOG.info((String)map.get("headers"));

        List<CourseVo> valueObjectList = (List<CourseVo>)map.get("valueObjectList");

        for (CourseVo vo:valueObjectList) {
            LOG.info("Code :  " + vo.getCode()+"  Name: "+vo.getName()+"  Sessions : "+vo.getSessions()+
                    "  Duration : "+vo.getDuration()+"  MaxScoreMarks : "+vo.getScoreMarks()+" StartMonth  : "+vo.getStartMonth());

        }

        return volist;

    }

 

    public Map<String,Object> readExcelSheet(String filePath) {

     

            CourseVo courseVo = null;

            Map<String, Object> courseVOMap = null;

            try {

                LOG.info("File path"+filePath);

                XSSFWorkbook myWorkBook = new XSSFWorkbook(new FileInputStream(filePath));

                XSSFSheet mySheet = myWorkBook.getSheetAt(0);

                boolean isFirstRow = true;

                courseVOMap = new HashMap<String, Object>();

                List<CourseVo> cellsList = new ArrayList<CourseVo>();

                String headers = null;

                for(Row myRow : mySheet){

                    courseVo = new CourseVo();

                    if (isFirstRow) {

                        headers = addHeaderRowCells(courseVo, myRow);

                        courseVOMap.put("headers", headers);

                    } else {

                        addVoRowCells(cellsList, myRow);

                    }

                 

                    if(isFirstRow) {

                        isFirstRow = false;

                    }

                }

                courseVOMap.put("valueObjectList", cellsList);

            } catch (Exception e) {

                LOG.error(e.getMessage());

            }

            return courseVOMap;

        }

    public void addVoRowCells(List<CourseVo> cellList, Row row) {

        int cellInd = 0;

        CourseVo valueObject = new CourseVo();

     

        Cell cell = row.getCell(cellInd++);

            try{

            valueObject.setCode(String.valueOf((int)cell.getNumericCellValue()));

            }catch(Exception e){

                LOG.error(e.getMessage());

            }

            myCell = row.getCell(cellInd++);

            try{

            valueObject.setName(cell.getStringCellValue());

            }catch(Exception e){

                LOG.error(e.getMessage());

            }

            myCell = row.getCell(cellInd++);

            try{

            valueObject.setSessions((short)cell.getNumericCellValue());

            }catch(Exception e){

                LOG.error(e.getMessage());

            }

            myCell = row.getCell(cellInd++);

            try{

            valueObject.setDuration(BigDecimal.valueOf(cell.getNumericCellValue()));

            }catch(Exception e){

                LOG.error(e.getMessage());

            }

            myCell = row.getCell(cellInd++);

            try{

            valueObject.setScoreMarks(BigDecimal.valueOf((int)cell.getNumericCellValue()));

            }catch(Exception e){

                LOG.error(e.getMessage());

            }

            myCell = row.getCell(cellInd++);

            try{

            valueObject.setStartMonth(cell.getDateCellValue());

            }catch(Exception e){

                LOG.error(e.getMessage(););

            }

            cellList.add(valueObject);
}

 

    public String addHeaderRowCells(CourseVo vo, Row row) {

        int cellInd = 0;

        String header = "";

        try{

            Cell cell = row.getCell(cellInd++);

            header = cell.getStringCellValue();

            cell = row.getCell(cellInd++);

            header += "," + cell.getStringCellValue();

            cell = row.getCell(cellInd++);

            header += "," + cell.getStringCellValue();

            cell = row.getCell(cellInd++);

            header += "," + cell.getStringCellValue();

            cell = row.getCell(cellInd++);

            header += "," + cell.getStringCellValue();

            cell = row.getCell(cellInd++);

            header += "," + cell.getStringCellValue();

        }catch(Exception e){

            LOG.error(e.getMessage(););

        }

        return header;

    }

    }

CourseVo.java
========================================
package com.xyz.vo;

import java.math.BigDecimal;

import java.util.Date;

/**

 * @author Pedababu M

 *

 */

public class CourseVo {

    String code;

    String name;

    short sessions;

    BigDecimal Duration;

    BigDecimal scoreMarks;

    Date startMonth;

    /**

     * @return the code

     */

    public String getCode() {

        return code;

    }

    /**

     * @param code the code to set

     */

    public void setCode(String code) {

        this.code = code;

    }

    /**

     * @return the name

     */

    public String getName() {

        return name;

    }

    /**

     * @param name the name to set

     */

    public void setName(String name) {

        this.name = name;

    }

    /**

     * @return the sessions

     */

    public short getSessions() {

        return sessions;

    }

    /**

     * @param sessions the sessions to set

     */

    public void setSessions(short sessions) {

        this.sessions = sessions;

    }

    /**

     * @return the duration

     */

    public BigDecimal getDuration() {

        return Duration;

    }

    /**

     * @param duration the duration to set

     */

    public void setDuration(BigDecimal duration) {

        Duration = duration;

    }

    /**

     * @return the scoreMarks

     */

    public BigDecimal getScoreMarks() {

        return scoreMarks;

    }

    /**

     * @param scoreMarks the scoreMarks to set

     */

    public void setScoreMarks(BigDecimal scoreMarks) {

        this.scoreMarks = scoreMarks;

    }

    /**

     * @return the startMonth

     */

    public Date getStartMonth() {

        return startMonth;

    }

    /**

     * @param startMonth the startMonth to set

     */

    public void setStartMonth(Date startMonth) {

        this.startMonth = startMonth;

    }

}