Tuesday, October 14, 2014

EJB/Hibernate



EJB/Hibernate
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;
    private Set hats;

//GETTERS / SETTERS
    public Person() {
        hats = new HashSet();
    }

    public void addHat(Hat hat) {
        this.hats.add(hat);
    }

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

    @Override
    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;
    }
}
//--------------------------------------------------------------------
package hibernatedemo;

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

public class Hibernatedemo {

    public static void main(String[] args) {
      
//       Person p1 = new Person();
//       p1.setName("Saman");
//       p1.setAge(22);
//       createPerson(p1);
//        Person p2 = new Person();
//        p2.setPersonid(1);
//        p2.setName("bbbbbb");
//        p2.setAge(99);
//        createPerson(p2);
//        listPerson();
//        p1.setAge(44);
        //updatePerson(p1);
        //p2.setName("Peter John");
//        updatePerson(p2);
  //    listPerson();
        //System.out.println("jjjjjjjjjjjj");

        Person p1 = new Person();
       // p1.setPersonid(1);
        p1.setName("Saman With Hats");
        p1.setAge(30);
        Hat h1 = new Hat();
        h1.setColor("Black");
        h1.setSize("1");
        Hat h2 = new Hat();
        h2.setColor("White");
        h2.setSize("2");
        p1.addHat(h1);
        p1.addHat(h2);
        createPerson(p1);
        listPerson();
    }

    private static void listPerson() {
        Transaction tx = null;
        Session session = SessionFactoryUtil.getCurrentSession();
        try {
            tx = session.beginTransaction();
            //Query q = session.createQuery("select p from Person as p where p.age>:age");
            //Person fooPerson = new Person();
            //fooPerson.setAge();
            //q.setProperties(fooPerson);
            //List persons = q.list();
            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 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 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 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 class SessionFactoryUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed."
                    + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Session openSession() {
        return sessionFactory.openSession();
    }

   
    public static Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    public static void close() {
        if (sessionFactory != null) {
            sessionFactory.close();
        }
    }

}
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 toString() {
        return "Hat: " + getHatid()
                + " Color: " + getColor()
                + " Size: " + getSize();
    }

}


// Links
https://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html

No comments:

Post a Comment