Sunday, October 12, 2014

Hibernate Java Application

1. Create data base

Services->JavaDB->Create Database->Give name->Username->Password-(demo-app-app)>Connect
Click on tables ->Create table"Person"->Add columns

id-integer-PK
name-varchar(20)
age-varchar(20)

2.Create class
Click on the project package->Create new javaclass->Finish
Right click on window ->Add getters and Setters->Select calsses tick all->generate getters and setters


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernatedemo;


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

public class Person {

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

   
    //default constructor with no argument

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

3.Add Hibernate libries to the project

Right Click onthe libries->Add Libries->Hibernate 4.x->Add

4.Create Cofiguration file

(Not inside the current package inside the Source package )

Right click on souce package->New->other->Hibernate->HibernateCofigWizard->Select db"Person"
from drop down

Click on the souce tab it shows row XML file->Add additional propeties

Optional propeties->Configuration propeties->hibernate.show.sql->true
Mislanious propeties->Hibernate Sesion context->thread

5.Create Mapping file 

Click inside the current package->New->Hobernate->Hibernate Mapping wizard->NameIt as"Person"->Next->...Type Person->Select Peson class->DB table->Select Person table

<Class name= "hiber"/>--------remove this back slash
</Class>

Then add content within the <class> tags
<Class>
<id column="personid" name="personid">
<generator class="increment"/>
</id>
<property column="name" name="name"/>
<property column="age" name="age"/>
</Class>

6.Create Session Facory class
New ->Hibernate->Hibernate.Util.java->give a name-> SessionFacoryUtil->Finish

Add codes in red color

package hibernatedemo;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

import org.hibernate.Session;

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

7.Inside the Main class

Ctrl+Shift+i

Import Hibernate.transaction;

Main(){}

//List all people on console

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

}


//Delete a person

private 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;
}
}

}


//Create Person
private static void createPerson(Person person) {
Transaction tx = null;
Session session = SessionFactoryUtil.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;
}
}

}


//Update people

private 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;
}
}

}


8.Inside main method call the appropriate methods

public static void main(String[] args) {

Person p1 = new Person();


//Create person 1
p1.setName("Saman");
p1.setAge(22);
createPerson(p1);

//Create person 2
Person p2 = new Person();
p2.setName("Peter");
p2.setAge(31);
createPerson(p2);

//Display
listPerson();

//Update p1 age
p1.setAge(44);
updatePerson(p1);

//Update p2 name
p2.setName("Peter John");
updatePerson(p2);

//Dispaly
listPerson();

}

9.Run the application


-------------------------------------------------------------------------------------------------------------------------

10.Query to perform people age greater than 20

Copy the list person method and change the name to listpersonAbove
Pass parameter age


private static void listPersonAbove(int age) {

Transaction tx = null;

Session session = SessionFactoryUtil.getCurrentSession();
try {

//Rempove this part 

//tx = session.beginTransaction();
//List persons = session.createQuery("select p from Person as p").list();

//Add this part 

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

Person fooPerson = new 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;
}
}

}


11.Run the method inside the main method

public static void main(String[] args) {

Person p1 = new Person();
//Dispaly
listPersonAbove(20);

}

--------------------------------------------------------------------------------------------------------------------------

One to many relationships

1.Create Hat table with inside the demo database

(hatid,color,size,PersonId(int))


2.Create Hat class

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

3.Modify the Person class

package hibernatedemo;

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


public class Person {

    private int personid;
    private String name;
    private int age;
   
//hat collection
    private Set hats;

    public Set getHats() {
        return hats;
    }

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



//default constructor with no argument
//
//    public Person() {
//    }

//Change Constructor
    public Person() {
        hats = new HashSet();
    }

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

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



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

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

}


4.Create hibernate Mapping file for HAT class
Select Class Hat By typing H and select table from drop down

Change the attributes accordingly ""-remove displayed one and ctrl_space-select relevant attribute.

<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>

5.Change Person Mapping file

<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>

Change the class name,fields name you use in your application


6. Add the code inside the main

public static void main(String[] args) {
  Person p1 = new Person();

  p1.setName("Saman With Hats");
  p1.setAge(30);


//P1 has 2 hats H1
  Hat h1 = new Hat();
  h1.setColor("Black");
  h1.setSize("Small");

//H2
   Hat h2 = new Hat();
  h2.setColor("White");
   h2.setSize("Large");


   p1.addHat(h1);
   p1.addHat(h2);

createPerson(p1);
listPerson();
}


7.Run the application















No comments:

Post a Comment