Monday, October 13, 2014

Hibernate Application  Full code One to Many



One person has many Hats
In hat table create personId column
Hat class implement getters and setters for personId,Generate hat mapping file including personID.
Person class create hat collection
In person mapping file add Hat collection property


Souce pakage

Config file-:

<?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.dialect">org.hibernate.dialect.DerbyDialect</property>
    <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
    <property name="hibernate.connection.url">jdbc:derby://localhost:1527/demo</property>
    <property name="hibernate.connection.username">app</property>
    <property name="hibernate.connection.password">app</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <mapping resource="hibernatedemo/Person.xml"/>
    <mapping resource="hibernatedemo/Hat.xml"/>
  </session-factory>
</hibernate-configuration>
--------------------------------------------------------------------------------------------------------------------------Current package
Hat.java

package hibernatedemo;

/**
 *
 * @author MANISHA
 */
public class Hat {

    private int hatid;
    private String color;
    private String size;
    private int personid;

// Getters and Setters
    public int getHatid() {
        return hatid;
    }

    public void setHatid(int hatid) {
        this.hatid = hatid;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public int getPersonid() {
        return personid;
    }

    public void setPersonid(int personid) {
        this.personid = personid;
    }

    public String toString() {
        return "Hat: " + getHatid()
                + " Color: " + getColor()
                + " Size: " + getSize();
    }
}
-------------------------------------------------------------------------------------------------------------------
Hat mapping file

<?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="hibernatedemo.Hat" table="HAT">
        <id column="HATID" name="hatid">
            <generator class="increment"/>
        </id>
        <property column="PERSONID" name="personid"/>
        <property column="COLOR" name="color"/>
        <property column="SIZE" name="size"/>
  
    </class>
</hibernate-mapping>
----------------------------------------------------------------------------------------------------------------------
Project name use as Main file

Hibenatedemo.java

package hibernatedemo;

import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author MANISHA
 */
public class HibernateDemo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
//        Person p1 = new Person();
//        p1.setName("Saman");
//        p1.setAge(22);
//        createPerson(p1);
//        Person p3 = new Person();
//        p3.setName("Mani");
//        p3.setAge(31);
//        createPerson(p3);
//        listPerson();
//         p1.setAge(50);
//         updatePerson(p1);
//         listPerson();

        //select peaple above 45
     //   listPersonabove(45);

        Person p2 = new Person();
        p2.setName("Kate With Hats");
        p2.setAge(30);
        
        Hat h1 = new Hat();
        h1.setColor("Black");
        h1.setSize("Small");
        
        Hat h2 = new Hat();
        h2.setColor("White");
        h2.setSize("Large");
        
        p2.addHat(h1);
        p2.addHat(h2);
        
        createPerson(p2);
        listPerson();

    }

    private static void createPerson(Person person) {
        Transaction tx = null;
        Session session = SessionFactryUtil.getCurrentSession();
        try {
            tx = session.beginTransaction();
            session.save(person);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                try {
// Second try catch as the rollback could fail as well
                    tx.rollback();
                } catch (HibernateException e1) {
                    System.out.println("Error rolling back transaction");
                }
// throw again the first exception
                throw e;
            }
        }
    }

    private static void updatePerson(Person person) {
        Transaction tx = null;
        Session session = SessionFactryUtil.getCurrentSession();
        try {
            tx = session.beginTransaction();
            session.update(person);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                try {
// Second try catch as the rollback could fail as well
                    tx.rollback();
                } catch (HibernateException e1) {
                    System.out.println("Error rolling back transaction");
                }
// throw again the first exception
                throw e;
            }
        }
    }

    private static void deletePerson(Person person) {
        Transaction tx = null;
        Session session = SessionFactryUtil.getCurrentSession();
        try {
            tx = session.beginTransaction();
            session.delete(person);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                try {
// Second try catch as the rollback could fail as well
                    tx.rollback();
                } catch (HibernateException e1) {
                    System.out.println("Error rolling back transaction");
                }
// throw again the first exception
                throw e;
            }
        }
    }

    private static void listPerson() {
        Transaction tx = null;
        Session session = SessionFactryUtil.getCurrentSession();
        try {
            tx = session.beginTransaction();
            List persons = session.createQuery(
                    "select p from Person as p").list();
            System.out.println("*** Content of the Person Table ***");
            System.out.println("*** Start ***");
            for (Iterator iter = persons.iterator(); iter.hasNext();) {
                Person element = (Person) iter.next();
                System.out.println(element);
            }
            System.out.println("*** End ***");
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                try {
// Second try catch as the rollback could fail as well
                    tx.rollback();
                } catch (HibernateException e1) {
                    System.out.println("Error rolling back transaction");
                }
                throw e;
            }
        }
    }

    private static void listPersonabove(int age) {
        Transaction tx = null;
        Session session = SessionFactryUtil.getCurrentSession();
        try {
            tx = session.beginTransaction();

            Query q = session.createQuery("select p from Person as p where p.age >:age");
            Person fooPerson = new Person();

            //using set propety in dummy person
            fooPerson.setAge(age);
            q.setProperties(fooPerson);
            List persons = q.list();

            System.out.println("*** Content of the Person Table ***");
            System.out.println("*** Start ***");
            for (Iterator iter = persons.iterator(); iter.hasNext();) {
                Person element = (Person) iter.next();
                System.out.println(element);
            }
            System.out.println("*** End ***");

            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                try {
// Second try catch as the rollback could fail as well
                    tx.rollback();
                } catch (HibernateException e1) {
                    System.out.println("Error rolling back transaction");
                }
                throw e;
            }
        }
    }

}

------------------------------------------------------------------------------------------------------------------------
Person.java

package hibernatedemo;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 *
 * @author MANISHA
 */
public class Person {

    private int personid;
    private String name;
    private int age;

    public Set getHats() {
        return hats;
    }

    public void setHats(Set hats) {
        this.hats = hats;
    }

    //hat collection
    private Set hats;

    //default constructor with no argument
//
//    public Person() {
//    }
    public Person() {
        hats = new HashSet();
    }

    // Getters and Setters
    public void addHat(Hat hat) {
        this.hats.add(hat);
    }

    public void removeHat(Hat hat) {
        this.hats.remove(hat);
    }

    public String toString() {
        String personString = "Person: " + getPersonid()
                             + " Name: " + getName()
                             + " Age: " + getAge();
        String hatString = "";
        for (Iterator iter = hats.iterator(); iter.hasNext();) {
            Hat hat = (Hat) iter.next();
            hatString = hatString + "\t\t" + hat.toString() + "\n";
        }
        return personString + "\n" + hatString;
    }

    public int getPersonid() {
        return personid;
    }

    public void setPersonid(int personid) {
        this.personid = personid;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

//    @Override
//    public String toString() {
//        return "Person: " + getPersonid()
//                + " Name: " + getName()
//                + " Age: " + getAge();
//    }
}

----------------------------------------------------------------------------------------------------------------------
Person.xml

<?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="hibernatedemo.Person" table="PERSON">
        <id column="PERSONID" name="personid">
            <generator class="increment"/>
        </id>
        <property column="NAME" name="name"/>
        <property column="AGE" name="age"/>
        <set cascade="all" name="hats" table="HAT">
            <key column="PERSONID"/>
            <one-to-many class="hibernatedemo.Hat"/>
        </set>
    </class>
</hibernate-mapping>
-----------------------------------------------------------------------------------------------------------------------
package hibernatedemo;

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

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author MANISHA
 */
public class SessionFactryUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * Opens a session and will not bind it to a session context
     *
     * @return the session
     */
    public static Session openSession() {
        return sessionFactory.openSession();
    }

    /**
     * Returns a session from the session context. If there is no session in the
     * context it opens a session, stores it in the context and returns it. This
     * factory is intended to be used with a hibernate.cfg.xml including the
     * following property <property
     * name="current_session_context_class">thread</property>
     * This would return the current open session or if this does not exist,
     * will create a new session
     *     
* @return the session
     */
    public static Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * closes the session factory
     */
    public static void close() {
        if (sessionFactory != null) {
            sessionFactory.close();
        }
    }

}

--------------------------------------------------------------------------------------------------------------------------
run
















No comments:

Post a Comment