Wednesday, February 17, 2010

Hibernate - One to Many Example

Tables
****************************************************************************************
create table "SCOTT"."EMPLOYEE"(
"ID" NUMBER(10) not null,
"NAME" VARCHAR2(50),
"DEPT" VARCHAR2(20),
"SAL" NUMBER(10),
constraint "PK_EMPLOYEE" primary key ("ID")
);

create unique index "PK_EMPLOYEE" on "SCOTT"."EMPLOYEE"("ID");

create table "SCOTT"."ADDRESS"(
"ID" NUMBER(10) not null,
"EMP_ID" NUMBER(10),
"STREET" VARCHAR2(30),
"CITY" VARCHAR2(30),
"STATE" VARCHAR2(30),
"PIN" NUMBER(8),
constraint "PK_ADDRESS" primary key ("ID")
);

alter table "SCOTT"."ADDRESS"
add constraint "EMP_ID_FK"
foreign key ("EMP_ID")
references "SCOTT"."EMPLOYEE"("ID");
create unique index "PK_ADDRESS" on "SCOTT"."ADDRESS"("ID");
****************************************************************************************
Hibernate Session Factory Class
****************************************************************************************
package factory;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {

/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal threadLocal = new ThreadLocal();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;

private HibernateSessionFactory() {
}

/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the SessionFactory if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}

return session;
}

/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}

/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);

if (session != null) {
session.close();
}
}

/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}

/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}

/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}

}
****************************************************************************************
HibernateCFG.xls file

****************************************************************************************
Pojo Classes
****************************************************************************************
package model;
// default package
/**
* AddressModel generated by MyEclipse - Hibernate Tools
*/

public class AddressModel implements java.io.Serializable {
// Fields

private Long id;
private EmployeeModel employee;
private String street;
private String city;
private String state;
private Long pin;


// Constructors

/** default constructor */
public AddressModel() {
}


/** full constructor */
public AddressModel(EmployeeModel employee, String street, String city, String state, Long pin) {
this.employee = employee;
this.street = street;
this.city = city;
this.state = state;
this.pin = pin;
}


// Property accessors

public Long getId() {
return this.id;
}

public void setId(Long id) {
this.id = id;
}

public EmployeeModel getEmployee() {
return this.employee;
}

public void setEmployee(EmployeeModel employee) {
this.employee = employee;
}

public String getStreet() {
return this.street;
}

public void setStreet(String street) {
this.street = street;
}

public String getCity() {
return this.city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return this.state;
}

public void setState(String state) {
this.state = state;
}

public Long getPin() {
return this.pin;
}

public void setPin(Long pin) {
this.pin = pin;
}
}


package model;
// default package

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

/**
* EmployeeModel generated by MyEclipse - Hibernate Tools
*/

public class EmployeeModel implements java.io.Serializable {
// Fields
private Long id;
private String name;
private String dept;
private Long sal;
private Set addresses = new HashSet(0);


// Constructors

/** default constructor */
public EmployeeModel() {
}


/** full constructor */
public EmployeeModel(String name, String dept, Long sal, Set addresses) {
this.name = name;
this.dept = dept;
this.sal = sal;
this.addresses = addresses;
}


// Property accessors

public Long getId() {
return this.id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return this.name;
}

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

public String getDept() {
return this.dept;
}

public void setDept(String dept) {
this.dept = dept;
}

public Long getSal() {
return this.sal;
}

public void setSal(Long sal) {
this.sal = sal;
}

public Set getAddresses() {
return this.addresses;
}

public void setAddresses(Set addresses) {
this.addresses = addresses;
}
}


****************************************************************************************
Mapping files



****************************************************************************************
Actual DAO Class

package test;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import model.AddressModel;
import model.EmployeeModel;

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

import factory.HibernateSessionFactory;

public class EMPDAO {

/**
* @param args
*/
public static void main(String[] args) {
EmployeeModel employeeModel = new EmployeeModel();
employeeModel.setName("Gangadhara Rao D");
employeeModel.setSal(1000L);
employeeModel.setDept("Java");

Set set = new HashSet();
AddressModel addressModel = new AddressModel();
addressModel.setStreet("3rd Cross");
addressModel.setCity("Bangalore");
addressModel.setState("Karnataka");
addressModel.setPin(560068L);
addressModel.setEmployee(employeeModel);
set.add(addressModel);
employeeModel.setAddresses(set);

employeeModel = (EmployeeModel)new EMPDAO().saveEmployee(EmployeeModel.class, employeeModel);
System.out.println(employeeModel.getId());
}


public Object saveEmployee(Class clazz, Object object) throws HibernateException {
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
Serializable id = session.save(object);
tx.commit();
/*session.flush();
session.refresh(object);*/
Object returnObj = session.get(clazz, id, LockMode.UPGRADE);
return returnObj;
}

}
****************************************************************************************

No comments:

Post a Comment