Hibernate Application

·         Create Java Class
public class Person {
private int personid ;
private String name;
private int age;
// Generate Getters and Setters for the above
// Properties
@Override
public String toString() {
return "Person: "+getPersonid()+
" Name: "+getName()+
" Age: "+getAge();
}
}
·         Create Hibernate configuration file using hibernate configuration wizard.
Optional cofig - hibernate.show_sql=true.
Miscellaneous - hibernate.current_session_context_class=thread

·         Create Hibernate map file.

<id column="personid" name="personid">
<generator class="increment"/>
</id>
<property column="name" name="name"/>
<property column="age" name="age"/>


·         Create Session Factory Util class

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


·         Create Test Client and following methods

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


·         Check using following code in main method

public static void main(String[] args) {
Person p1 = new Person();
p1.setName("Saman");
p1.setAge(22);
createPerson(p1);
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();
}
·         Insert Person
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();


Add Many to many relationship


·         Create Hat class

public class Hat {
private int hatid;
private String color;
private String size;
private int personid;
// Getters and Setters
public String toString() {
return "Hat: "+getHatid()+
" Color: "+getColor()+
" Size: "+getSize();
}
}

·         Add Hat list to person class
private Set hats;


·         Create Hibernate mapping class and add properties

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


·         Modify person class as following.

<set cascade="all" name="hats" table="HAT">
<key column="personid"/>
<one-to-many class="hibernatedemo.Hat"/>
</set>


·         Check using following code in main method

public static void main(String[] args) {
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();

      }

Comments

Popular posts from this blog

Encrypt and Decrypt text using alphabet shifting method

Gridview to Datatable and Viewstate

You think Creating Circuler Graph is a difficult task ...........!!!