Tuesday 13 December 2011

Hibernate configuration using Database


PART-1

PART-2
to be continue..!

Friday 9 December 2011

One to One Mapping in Hibernate with full details

Hi New World,

As a IT professional, i had faced so many difficulties with technologies, But no need to strugle with them. That is the main reason today i am coming up with Blog. To make technologies easy.

Today, i am starting with simple One to One relationship with DB2 and mapping with Hibernate as well..

One-One Relationship

Start --> DB2 ControlCenter
Create table with the name "STUDENT" as a parent table and add columns as given like in the below picture
Add primary key to "Student_ID" 
Click Next to Next and Finish.
Now we are successfully created parent table in Database.
Next we have to create child table named as "ADDRESS"
Add columns like above. And assign primary key and foreign key to Address-id
Click Next to Next finally finish.
Now we completed database part. Next we will look into Hibernate mapping using Eclipse IDE

Select workspace
Create new java project in your workspace
Give name to the project
Configure the build path

Add library files

Create Hibernate configuration file.
Give Driver class, URL, Username and Password. create console configuration and select database connection
Click on finish.
After finish all these steps hibernate.cfg.xml file is looking like below

<?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.driver_class">com.ibm.db2.jcc.DB2Driver</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.url">jdbc:db2://localhost:50000/LEARN</property>
        <property name="hibernate.connection.username">db2admin</property>
        <property name="hibernate.dialect">org.hibernate.dialect.DB2Dialect</property>
        <mapping resource="com\blog\mapping\Student.hbm.xml"/>
        <mapping resource="com\blog\mapping\AddressS.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Next create Hibernate Reverse Engineering
Select Console Configuration, select include the tables, and click finish

After finish this the xml file is looking like below

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>
  <table-filter match-schema="DB2Admin" match-name="ADDRESS_S"/>
  <table-filter match-schema="DB2Admin" match-name="STUDENT"/>
</hibernate-reverse-engineering>

Now We have to generate code means hibernate mapping files and model classes
Select console configuration, hibernate reverse engineering xml file, and select exporters for hbm files and java classes
After finish these steps we will get 4 files
Student.java

package com.blog.mapping;

// default package
// Generated Dec 9, 2011 8:47:00 PM by Hibernate Tools 3.2.4.GA

/**
 * Student generated by hbm2java
 */
public class Student implements java.io.Serializable {

    private int studentid;
    private String name;
    private String emailid;
    private String contactno;
    private AddressS addressS;

    public Student() {
    }

    public Student(int studentid, String name, String emailid, String contactno) {
        this.studentid = studentid;
        this.name = name;
        this.emailid = emailid;
        this.contactno = contactno;
    }

    public Student(int studentid, String name, String emailid,
            String contactno, AddressS addressS) {
        this.studentid = studentid;
        this.name = name;
        this.emailid = emailid;
        this.contactno = contactno;
        this.addressS = addressS;
    }

    public int getStudentid() {
        return this.studentid;
    }

    public void setStudentid(int studentid) {
        this.studentid = studentid;
    }

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

    public void setName(String name) {
        this.name = name;
    }

    public String getEmailid() {
        return this.emailid;
    }

    public void setEmailid(String emailid) {
        this.emailid = emailid;
    }

    public String getContactno() {
        return this.contactno;
    }

    public void setContactno(String contactno) {
        this.contactno = contactno;
    }

    public AddressS getAddressS() {
        return this.addressS;
    }

    public void setAddressS(AddressS addressS) {
        this.addressS = addressS;
    }

}

Address.java
package com.blog.mapping;

// default package
// Generated Dec 9, 2011 8:47:00 PM by Hibernate Tools 3.2.4.GA

/**
 * AddressS generated by hbm2java
 */
public class AddressS implements java.io.Serializable {

    private int addressId;
    private Student student;
    private String addressLine1;
    private String city;
    private String state;
    private String pincode;

    public AddressS() {
    }

    public AddressS(Student student, String addressLine1, String city,
            String state, String pincode) {
        this.student = student;
        this.addressLine1 = addressLine1;
        this.city = city;
        this.state = state;
        this.pincode = pincode;
    }

    public int getAddressId() {
        return this.addressId;
    }

    public void setAddressId(int addressId) {
        this.addressId = addressId;
    }

    public Student getStudent() {
        return this.student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    public String getAddressLine1() {
        return this.addressLine1;
    }

    public void setAddressLine1(String addressLine1) {
        this.addressLine1 = addressLine1;
    }

    public String getCity() {
        return this.city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return this.state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getPincode() {
        return this.pincode;
    }

    public void setPincode(String pincode) {
        this.pincode = pincode;
    }

}

Student.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">
<!-- Generated Dec 9, 2011 8:47:00 PM by Hibernate Tools 3.2.4.GA -->
<hibernate-mapping>
    <class name="com.blog.mapping.Student" table="STUDENT" schema="MURALIKRISHNA">
        <comment>This is Creating for Blog</comment>
        <id name="studentid" type="int">
            <column name="STUDENTID" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="NAME" length="25" not-null="true" />
        </property>
        <property name="emailid" type="string">
            <column name="EMAILID" length="100" not-null="true" />
        </property>
        <property name="contactno" type="string">
            <column name="CONTACTNO" length="25" not-null="true" />
        </property>
        <one-to-one name="addressS" class="com.blog.mapping.AddressS"></one-to-one>
    </class>
</hibernate-mapping>

Address.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">
<!-- Generated Dec 9, 2011 8:47:00 PM by Hibernate Tools 3.2.4.GA -->
<hibernate-mapping>
    <class name="com.blog.mapping.AddressS" table="ADDRESS_S" schema="MURALIKRISHNA">
        <comment>This is child table creating for blog</comment>
        <id name="addressId" type="int">
            <column name="ADDRESS_ID" />
            <generator class="foreign">
                <param name="property">student</param>
            </generator>
        </id>
        <one-to-one name="student" class="com.blog.mapping.Student" constrained="true"></one-to-one>
        <property name="addressLine1" type="string">
            <column name="ADDRESS_LINE1" length="100" not-null="true" />
        </property>
        <property name="city" type="string">
            <column name="CITY" length="50" not-null="true" />
        </property>
        <property name="state" type="string">
            <column name="STATE" length="50" not-null="true" />
        </property>
        <property name="pincode" type="string">
            <column name="PINCODE" length="15" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

Write a Test class to insert a record into database

/**
 *
 */
package com.blog.main;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.blog.mapping.AddressS;
import com.blog.mapping.Student;



/**
 * @author Muralikrishna
 *
 */
public class TestOnetoOne {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Session session = null;
        try{
            System.out.println("SessionFactory is loading");
            SessionFactory factory = new Configuration().configure().buildSessionFactory();
            System.out.println("Opening a session");
            session = factory.openSession();
            System.out.println("Begin Tansaction");
            Transaction tx = session.beginTransaction();
            Student stu = new Student(0, "Nethaji","indian@gmail.com","9999999999");
            AddressS addr = new AddressS(stu, "santhapeta", "Nellore","andhra pradesh","524001");
           
            System.out.println("Inserting values into Database");
            session.save(addr);
            tx.commit();
            System.out.println("Record successfully added");           
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            session.close();
        }

    }

}
OUTPUT :

SessionFactory is loading
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Opening a session
Begin Tansaction
Inserting values into Database
Record successfully added

Now Check in Database
Success fully inserted values :

Keep smile :)