Wednesday, February 17, 2010

Hibernate - Many To One Example

****************************************************************************************
Tables
****************************************************************************************
create table "SCOTT"."ADD_RESS"(
"ADDRESS_ID" NUMBER(10) not null,
"ADDRESS_STREET" VARCHAR2(20),
"ADDRESS_CITY" VARCHAR2(20),
"ADDRESS_STATE" VARCHAR2(20),
"ADDRESS_PIN" NUMBER(10),
constraint "PK_ADD_RESS" primary key ("ADDRESS_ID")
);

create unique index "PK_ADD_RESS" on "SCOTT"."ADD_RESS"("ADDRESS_ID");



create table "SCOTT"."STUDENT"(
"STUDENT_ID" NUMBER(10) not null,
"STUDENT_NAME" VARCHAR2(30),
"STUDENT_ADDRESS" NUMBER(10),
constraint "PK_STUDENT" primary key ("STUDENT_ID")
);

alter table "SCOTT"."STUDENT"
add constraint "ADD_FK"
foreign key ("STUDENT_ADDRESS")
references "SCOTT"."ADD_RESS"("ADDRESS_ID");
create unique index "PK_STUDENT" on "SCOTT"."STUDENT"("STUDENT_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.xml File
****************************************************************************************

****************************************************************************************
Pojo Classes
****************************************************************************************
package model;
// default package



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

public class Student implements java.io.Serializable {


// Fields

private Long studentId;
private Add_ress addRess;
private String studentName;


// Constructors

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


/** full constructor */
public Student(Add_ress addRess, String studentName) {
this.addRess = addRess;
this.studentName = studentName;
}


// Property accessors

public Long getStudentId() {
return this.studentId;
}

public void setStudentId(Long studentId) {
this.studentId = studentId;
}

public Add_ress getAddRess() {
return this.addRess;
}

public void setAddRess(Add_ress addRess) {
this.addRess = addRess;
}

public String getStudentName() {
return this.studentName;
}

public void setStudentName(String studentName) {
this.studentName = studentName;
}
}

package model;
// default package

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


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

public class Add_ress implements java.io.Serializable {


// Fields

private Long addressId;
private String addressStreet;
private String addressCity;
private String addressState;
private Long addressPin;
private Set students = new HashSet(0);


// Constructors

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


/** full constructor */
public Add_ress(String addressStreet, String addressCity, String addressState, Long addressPin, Set students) {
this.addressStreet = addressStreet;
this.addressCity = addressCity;
this.addressState = addressState;
this.addressPin = addressPin;
this.students = students;
}


// Property accessors

public Long getAddressId() {
return this.addressId;
}

public void setAddressId(Long addressId) {
this.addressId = addressId;
}

public String getAddressStreet() {
return this.addressStreet;
}

public void setAddressStreet(String addressStreet) {
this.addressStreet = addressStreet;
}

public String getAddressCity() {
return this.addressCity;
}

public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}

public String getAddressState() {
return this.addressState;
}

public void setAddressState(String addressState) {
this.addressState = addressState;
}

public Long getAddressPin() {
return this.addressPin;
}

public void setAddressPin(Long addressPin) {
this.addressPin = addressPin;
}

public Set getStudents() {
return this.students;
}

public void setStudents(Set students) {
this.students = students;
}
}
****************************************************************************************
Mapping Files
****************************************************************************************


****************************************************************************************
Actual DAO Class
****************************************************************************************
package test;

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

import model.Add_ress;
import model.Student;

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

import factory.HibernateSessionFactory;

public class TestManyToOne {

/**
* @param args
*/
public static void main(String[] args) {
//Saving Address and Student Objects
Add_ress add_ress = new Add_ress();
add_ress.setAddressCity("Yanam");
add_ress.setAddressState("Pondicherry");
add_ress.setAddressStreet("1st Cross");
add_ress.setAddressPin(533464l);

Student student = new Student();
student.setStudentName("Swetha");
Student student1 = new Student();
student1.setStudentName("Nagendra");
student.setAddRess(add_ress);
student1.setAddRess(add_ress);
Set studentSet = new HashSet();
studentSet.add(student);
studentSet.add(student1);

add_ress.setStudents(studentSet);

// new TestManyToOne().saveStudent(Add_ress.class, add_ress);
//Saving Address and Student Objects

/********************************************************************/
//Getting Address and Student Objects.
/*Add_ress add_ress1 = new Add_ress();
add_ress1.setAddressId(4l);
add_ress1 = (Add_ress)new TestManyToOne().getAddress(Add_ress.class, add_ress1.getAddressId());
System.out.println("City : " + add_ress1.getAddressCity());
System.out.println("State : " + add_ress1.getAddressState());
System.out.println("Street: " + add_ress1.getAddressStreet());
System.out.println("PIN : " + add_ress1.getAddressPin());
studentSet = add_ress1.getStudents();
for (Student student2 : studentSet) {
System.out.println("--------------------------------------------");
System.out.println("Student ID : " + student2.getStudentId());
System.out.println("Student Name: " + student2.getStudentName());
}*/
//Getting Address and Student Objects.

/********************************************************************/
Add_ress add_ress2 = new Add_ress();

Set stdSet = new HashSet();
Student std1 = new Student();
std1.setStudentId(5l);
Student std2 = new Student();
std2.setStudentId(6l);
stdSet.add(std1);
stdSet.add(std2);
add_ress2.setAddressId(4l);
add_ress2.setStudents(stdSet);
new TestManyToOne().deleteAddress(add_ress2);
}


public void saveStudent(Class clazz, Object object) throws HibernateException {
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
Serializable id = session.save(object);
session.close();
tx.commit();
}

public Object getAddress(Class clazz, long id) throws HibernateException {
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
Object returnObj = session.get(clazz, id, LockMode.UPGRADE);
return returnObj;
}

public void deleteAddress(Add_ress add_ress) throws HibernateException {
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
session.delete(add_ress);
//session.close();
tx.commit();
}

}

****************************************************************************************

No comments:

Post a Comment