Monday, October 13, 2014

My Hibernate




  • ·         hibernate.cfg

<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/hibernateDemo</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="hibernate/person.hbm.xml"/>
    <mapping resource="hibernate/hat.hbm.xml"/>
  </session-factory>
</hibernate-configuration>



  •         person.hbm
<hibernate-mapping>
    <class name="hibernate.Person" table="PERSON">
        <id column="personid" name="personid" type="int">
            <generator class="increment"/>
        </id>
        <property column="name" name="name" type="string"/>
        <property column="age" name="age" type="int"/>
    
        <set cascade="all" name="hats" table="HAT">
            <key column="personid"/>
            <one-to-many class="hibernate.Hat"/>
        </set>    
    </class>
</hibernate-mapping>

  •           hat.hbm



<hibernate-mapping>
    <class name="hibernate.Hat" table="HAT">
    
        <id column="hatid" name="hatid">
            <generator class="increment"/>
        </id>
    
        <property column="color" name="color"/>
        <property column="size" name="size"/>
  
        <many-to-one name="personid" class="hibernate.Person" fetch="join">
            <column name="personid" />
        </many-to-one>
  
    </class>
</hibernate-mapping>


  • ·         sessionfactoryutil

 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernatedemo;

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

/**
 *
 * @author Hasangi
 */
public class SessionFactoryUtil {

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

  • Person.java
package hibernate;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;


public class Person {
   
    private int personid;
    private String name;
    private int age;
    private Set hats;

    public Set getHats() {
        return hats;
    }

    public void setHats(Set hats) {
        this.hats = hats;
    }
   
    public Person()
    {
        hats=new HashSet();
    }
   
    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public int getPersonid() {
        return personid;
    }

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

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

    public void setPersonid(int personID) {
        this.personid = personID;
    }
   
    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;

    }
   
}
  •  Hat.java

 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate;


public class Hat {
  
   private int hatid;
   private String color;

 
   private String size;
   private Person personid;

    public String getColor() {
        return color;
    }

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

    public int getHatid() {
        return hatid;
    }

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

    public Person getPersonid() {
        return personid;
    }

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

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }
  
    public String tostring()
    {
        return "Name :"+getHatid() +" color :"+getColor() +" size :"+getSize();
    }
 
 
}

  •  Main.java


 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;


public class Hibernate {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

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

        /*
         * Person p1 = new Person();
         *
         * p1.setName("kamal");
         *
         * p1.setAge(22);
         *
         * createPerson(p1); p1.setAge(44); updatePerson(p1);
         *
         *
         * // listPerson();
         *
         *
         * Person p2 = new Person(); p2.setName("Peter"); p2.setAge(31);
         * createPerson(p2); listPerson(); p1.setAge(44); updatePerson(p1);
         * p2.setName("Peter John"); updatePerson(p2); listPerson();
         *
         *
         */
    }

   
public static void listPerson() {
        Transaction tx = null;
        Session session = sessionfactoryutil.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.getPersonid() + " " + element.getName() + " " + element.getAge());
            }
            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;
            }
        }
    }

   
public static void deletePerson(Person person) {
        Transaction tx = null;
        Session session = sessionfactoryutil.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;
            }
        }
    }

   
public static void createPerson(Person person) {

        Transaction tx = null;

        Session session = sessionfactoryutil.getCurrentSession();
        try {


            tx = session.beginTransaction();

            session.save(person);
// System.out.print("hiii");
            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;
            }
        }
    }

    public static void updatePerson(Person person) {
        Transaction tx = null;
        Session session = sessionfactoryutil.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;
            }
        }
    }



public static void ViewPerson(int ID) {
        Transaction tx = null;
        Session session = SessionFactoryUtil.getCurrentSession();
        try {
            tx = session.beginTransaction();
            List persons = session.createQuery("select p from Person as p where p.personid=:id").setParameter("id", ID).list();
            System.out.println("*** Content of the Person Table ***");
            System.out.println("*** Start ***");

            if (persons.isEmpty()){
                System.out.println("Person Not Vailed ........");
            }
            else{
               
                Person p=(Person)persons.get(0);               
                 System.out.println(p);
            }             
            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;
            }
        }


}






No comments:

Post a Comment