Archive

Archive for the ‘Hibernate’ Category

Hibernate Many-To-One Example

September 3, 2011 Leave a comment

Here the hibernate Many-To-One relationship is explained using the following example.
Severals Books can be published by a Publisher.

Many-to-One table design diagram

Many-To-One_Relationship

Many-To-One_Relationship

Book.java

package com.room.hibernate.many_one.sample;

import java.io.Serializable;

public class Book implements Serializable{

	private static final long serialVersionUID = 1L;
	private Long id;
	private String title;
	private Publisher publisher;
	
......... generate Getters and Setters	

	public String toString(){
		return new StringBuffer().append("Book Id: ").append(this.id).append("\n")
		.append("Book Title: ").append(this.title).append("\n")
		.append("Book Publisher: ").append(this.publisher).append("\n")
		.append("-----------------------------------------------------").toString();
	}

}

Publisher.java

package com.room.hibernate.many_one.sample;

import java.io.Serializable;

public class Publisher implements Serializable{

	private static final long serialVersionUID = 1L;
	private Long id;
	private String name;
	
	....... generate Getters and Setters

	public String toString(){
		return new StringBuffer().append("Publisher ID: ").append(this.id).append("\n")
		.append("Publisher Name: ").append(this.name).append("\n")
		.append("-----------------------------------------------").toString();
	}

}

Book.hbm.xml

<?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 package="com.room.hibernate.many_one.sample">
    <class name="Book" table="HIB_MA_BOOK">
        <id name="id" type="long" column="BK_ID" >
        	<generator class="sequence">
        		<param name="sequence">BK_ID_SEQ</param>
        	</generator>
        </id>
        <property name="title" column="BK_TITLE"/>
        <many-to-one name="publisher" class="Publisher" column="BK_PUB_ID" cascade="all"/>
    </class>
</hibernate-mapping>

Publisher.hbm.xml

<?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 package="com.room.hibernate.many_one.sample">
    <class name="Publisher" table="HIB_CH_PUBLISHER">
        <id name="id" type="long"  column="PUB_ID">
        	<generator class="sequence">
        		<param name="sequence">PUB_ID_SEQ</param>
        	</generator>
        </id>
        <property name="name" column="PUB_NAME"/>
    </class>
</hibernate-mapping>

Hibernate configuration file(hibernate.cfg.xml)

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<!-- a SessionFactory instance listed as /jndi/name -->
	<session-factory>
		<!-- properties -->
		<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
		<property name="show_sql">true</property>
		<property name="connection.url">jdbc:oracle:thin:@SABA:1521:XE</property>
		<property name="connection.username">system</property>
		<property name="connection.password">password</property>
		<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
		<property name="current_session_context_class">thread</property>
		<property name="dialect">org.hibernate.dialect.OracleDialect</property>
		<property name="hibernate.hbm2ddl.auto">create-update</property>
		<!-- Many to One Mapping -->
		<mapping resource="com/room/hibernate/many_one/sample/Book.hbm.xml" />
		<mapping resource="com/room/hibernate/many_one/sample/Publisher.hbm.xml" /> 
 	</session-factory>
</hibernate-configuration>

Oracle Queries to create table and sequences

CREATE TABLE HIB_CH_PUBLISHER(PUB_ID NUMBER PRIMARY KEY,PUB_NAME VARCHAR2(30) NOT NULL);

CREATE TABLE HIB_MA_BOOK(BK_ID NUMBER PRIMARY KEY,BK_TITLE VARCHAR2(30),BK_PUB_ID NUMBER NOT NULL,
             CONSTRAINT FK_BK_PUB_ID FOREIGN KEY(BK_PUB_ID) REFERENCES HIB_CH_PUBLISHER(PUB_ID));
             
CREATE SEQUENCE PUB_ID_SEQ START WITH 201 INCREMENT BY 1 NOCYCLE;
CREATE SEQUENCE BK_ID_SEQ START WITH 2001 INCREMENT BY 1 NOCYCLE;

Test class to test Hibernate Many-to-One relationship

package com.room.hibernate.many_one.sample.test;

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

import com.room.hibernate.many_one.sample.Book;
import com.room.hibernate.many_one.sample.Publisher;

public class HibernateManyToOneTest {
	
	public static void main(String[] args) {
		Session session=getHibernateSession();
		Transaction transaction=session.beginTransaction();
		System.out.println("----- Transaction Started -----");
		
//		Book book=(Book)session.get(Book.class, Long.valueOf("1000"));
		session.save(buildBook());
		transaction.commit();
		System.out.println("----- Book Detail Persisted -----");
		closeHibernateSession(session);
	}

	private static Session getHibernateSession() {
		return new Configuration().configure().buildSessionFactory().openSession();
	}
	
	private static void closeHibernateSession(Session session){
		if(session!=null){
			session.flush();
			session.close();
			System.out.println("--- Session Closed ----");
		}
	}
	
	private static Book buildBook(){
		Book book=new Book();
		book.setTitle("Head First Java");
		Publisher publisher=new Publisher();
		publisher.setName("TATA MGRAHILL");
		book.setPublisher(publisher);
		return book;
	}
}
Advertisements

Hibernate Many-To-Many Example

September 3, 2011 Leave a comment

Here the Hibernate Many-To-Many relationship is explained using the following example.
An Author can write several books likewise a Book can be written by several Authors.

The Many-To-Many relationship table design diagram given below.

Many-To-Many_Relationship

Many-To-Many_Relationship

Author.java

package com.room.hibernate.many_many.sample;

import java.io.Serializable;
import java.util.List;

public class Author implements Serializable{

	private static final long serialVersionUID = 1L;
	private Long id;
	private String authorName;
	private List<Book> authorBooks;
	
.......... generate Getters and Setters

}

Book.java

package com.room.hibernate.many_many.sample;

import java.io.Serializable;
import java.util.List;

public class Book implements Serializable{

	private static final long serialVersionUID = 1L;
	private Long id;
	private String bookName;
	private List<Author> bookAuthors;
	
....... Getters and Setters
	
}

Author.hbm.xml

<?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 package="com.room.hibernate.many_many.sample">
	<class name="Author" table="HIB_SA_AUTHOR">
		<id name="id" type="long" column="AU_ID">
			<generator class="sequence">
				<param name="sequence">SA_AU_ID_SEQ</param>
			</generator>
		</id>
		<property name="authorName" type="java.lang.String" column="AU_NAME" not-null="true"/>
		<list name="authorBooks" cascade="all" table="HIB_SA_BOOK_AUTHOR" inverse="true" lazy="true">
            <key column="AU_BOOK_ID"/><!-- AU_BOOK_ID -->
            <index column="idx"/>
            <many-to-many class="Book" column="BK_AUTHOR_ID"/>
        </list>
	</class>
</hibernate-mapping>

Book.hbm.xml

<?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 package="com.room.hibernate.many_many.sample">
	<class name="Book" table="HIB_SA_BOOK">
		<id name="id" type="long" column="BK_ID">
			<generator class="sequence">
				<param name="sequence">SA_BK_ID_SEQ</param>
			</generator>
		</id>
		<property name="bookName" type="java.lang.String" column="BK_NAME" not-null="true"/>
		<list name="bookAuthors" cascade="all" table="HIB_SA_BOOK_AUTHOR" inverse="true" lazy="true">
            <key column="BK_AUTHOR_ID"/>
            <index column="idx"/>
            <many-to-many class="Author" column="AU_BOOK_ID"/>
        </list>
	</class>
</hibernate-mapping>

Hibernate configuration file (hibernate.cfg.xml)

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<!-- a SessionFactory instance listed as /jndi/name -->
	<session-factory>
		<!-- properties -->
		<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
		<property name="show_sql">true</property>
		<property name="connection.url">jdbc:oracle:thin:@SABA:1521:XE</property>
		<property name="connection.username">system</property>
		<property name="connection.password">password</property>
		<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
		<property name="current_session_context_class">thread</property>
		<property name="dialect">org.hibernate.dialect.OracleDialect</property>
		<property name="hibernate.hbm2ddl.auto">create-update</property>
		
		<!-- Many To Many Mapping -->
		<mapping resource="com/room/hibernate/many_many/sample/Author.hbm.xml" />
		<mapping resource="com/room/hibernate/many_many/sample/Book.hbm.xml" />
	</session-factory>
</hibernate-configuration>

Queries to create table and sequences in Oracle

CREATE TABLE HIB_SA_BOOK(BK_ID NUMBER PRIMARY KEY,BK_NAME VARCHAR2(30) NOT NULL);
                         
CREATE TABLE HIB_SA_AUTHOR(AU_ID NUMBER PRIMARY KEY,AU_NAME VARCHAR2(25) NOT NULL);

CREATE TABLE HIB_SA_BOOK_AUTHOR(BK_AUTHOR_ID NUMBER,
                                AU_BOOK_ID NUMBER,
                                PRIMARY KEY(BK_AUTHOR_ID,AU_BOOK_ID));

CREATE SEQUENCE SA_BK_ID_SEQ START WITH 500 INCREMENT BY 1 NOCYCLE;
CREATE SEQUENCE SA_AU_ID_SEQ START WITH 2000 INCREMENT BY 1 NOCYCLE;

ALTER TABLE HIB_SA_BOOK_AUTHOR 
    ADD CONSTRAINT FK_BK_AU_ID FOREIGN KEY (BK_AUTHOR_ID) REFERENCES HIB_SA_BOOK(BK_ID);

ALTER TABLE HIB_SA_BOOK_AUTHOR 
    ADD CONSTRAINT FK_AU_BK_ID FOREIGN KEY (AU_BOOK_ID) REFERENCES HIB_SA_AUTHOR(AU_ID);

Test class to test hibernate many to many relationship

package com.room.hibernate.many_many.sample.test;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.room.hibernate.many_many.sample.Author;
import com.room.hibernate.many_many.sample.Book;
import com.room.hibernate.many_one.sample.Publisher;

public class HibernateManyToManyTest {
	private static SessionFactory sessionFactory=null;
	private static final ThreadLocal threadLocal=new ThreadLocal();
	
	public static void main(String[] args) {
		Session session=currentHibernateSession();
		Transaction transaction=session.beginTransaction();
		System.out.println("----- Transaction Started -----");
		
//		Book book=(Book)session.get(Book.class, Long.valueOf("1000"));
		session.save(buildBook());
		transaction.commit();
		System.out.println("----- Book Detail Persisted -----");
		closeHibernateSession();
	}
	
	private static SessionFactory getHibernateSessionFactory() {
		if(sessionFactory==null){
			sessionFactory=new Configuration().configure().buildSessionFactory();
		}
		return sessionFactory;
	}
	
	private static Session currentHibernateSession(){
		Session session=(Session)threadLocal.get();
		if(session==null){
			session = getHibernateSessionFactory().openSession();
			threadLocal.set(session);
		}
		return session;
	}
	
	private static void closeHibernateSession() {
       Session s = (Session) threadLocal.get();
        if (s != null){
        	s.flush();
            s.close();
        }  
       threadLocal.set(null);
    }
	
	private static Book buildBook(){
		Book book=new Book();
		book.setBookName("Hibernate In Action");
		
		List<Author> authorList=new ArrayList<Author>();
		Author author1=new Author();
		author1.setAuthorName("Gavin King");
		
		Author author2=new Author();
		author2.setAuthorName("Kathi Siera");
		authorList.add(author1);
		authorList.add(author2);
		
		book.setBookAuthors(authorList);
		
		return book;
	}
}

Hibernate One-To-Many Example

August 31, 2011 Leave a comment

Hibernate one to many sample. For this one-many relationship Student and Subject relationship is given.

1. Student.java

package com.room.hibernate.one_many.sample;

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

public class Student implements Serializable {

	private static final long serialVersionUID = 1L;
	private Long id;
	private String name;
	private String className;
	private Set<Subject> subjects;

	.... Generate Getters and Setters

	public String toString() {
		return new StringBuffer().append("Roll No: ").append(this.id)
				.append("\t").append("Student Name: ").append(this.name)
				.append("\t").append("Class Name: ").append(this.className)
				.append("\t").append("Subjects :").append(this.subjects)
				.append("\n").toString();
	}
}

2. Subject.java


package com.room.hibernate.one_many.sample;

import java.io.Serializable;

public class Subject implements Serializable {

	private static final long serialVersionUID = 1L;

	private Long id;
	private String subName;
	private Integer subMark;

	...... Getters and Setters

	public String toString() {
		return new StringBuffer().append("Subject Code: ").append(this.id)
				.append("\t").append("Subject Name: ").append(this.subName)
				.append("\t").append("Subject Mark: ").append(this.subMark)
				.append("\n").toString();
	}
}

Hibernate mapping xml for the genarated entity classes

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.room.hibernate.one_many.sample">

	<class name="Student" table="HIB_MA_STUDENT">
		<id name="id" type="long" column="STU_ROLLNO">
			<generator class="sequence">
				<param name="sequence">STU_ID_SEQ</param>
			</generator>
		</id>

		<property name="name" column="STU_NAME" />
		<property name="className" column="STU_CLASSNAME" />
		<set name="subjects" cascade="all" table="HIB_CH_SUBJECT">
			<key column="STU_ROLLNO"/>
			<one-to-many class="com.room.hibernate.one_many.sample.Subject"/>
		</set>
	</class>
</hibernate-mapping>

Subject.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.room.hibernate.one_many.sample">

	<class name="Subject" table="HIB_CH_SUBJECT">
		<id name="id" type="long" column="SUB_CODE">
			<generator class="sequence">
				<param name="sequence">SUB_ID_SEQ</param>
			</generator>
		</id>

		<property name="subName" column="SUB_NAME" />
		<property name="subMark" column="SUB_MARK" />
	</class>
</hibernate-mapping>

Hibernate configuration file “hibernate.cfg.xml”

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<!-- a SessionFactory instance listed as /jndi/name -->
	<session-factory>
		<!-- properties -->
		<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
		<property name="show_sql">true</property>
		<property name="connection.url">jdbc:oracle:thin:@SABA:1521:XE</property>
		<property name="connection.username">system</property>
		<property name="connection.password">password</property>
		<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
		<property name="current_session_context_class">thread</property>
		<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
		<property name="hibernate.hbm2ddl.auto">create</property>
		<!-- mapping files -->
		<mapping resource="com/room/hibernate/one_many/sample/Subject.hbm.xml" />
		<mapping resource="com/room/hibernate/one_many/sample/Student.hbm.xml" />
	</session-factory>
</hibernate-configuration>

SQL Query to create dependant table for hibernate entities created

CREATE TABLE HIB_CH_SUBJECT(SUB_CODE number PRIMARY KEY,SUB_NAME varchar2(15) NOT NULL,SUB_MARK NUMBER);

CREATE TABLE HIB_MA_STUDENT(STU_ROLLNO NUMBER PRIMARY KEY,
			    STU_NAME varchar2(20) NOT NULL,
			    STU_CLASSNAME varchar2(10),
			    SUB_CODE number NOT NULL,
			    CONSTRAINT FK_SUB_CODE FOREIGN KEY(SUB_CODE) REFERENCES HIB_CH_SUBJECT(SUB_CODE));

CREATE SEQUENCE STU_ID_SEQ START WITH 100 INCREMENT BY 1 NOCACHE NOCYCLE;
CREATE SEQUENCE SUB_ID_SEQ START WITH 500 INCREMENT BY 1 NOCACHE NOCYCLE;

Test class to test the hibernate one-many insertion into table

HibernateTest.java

package com.room.hibernate.one_many.sample.test;

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

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.room.hibernate.one_many.sample.Student;
import com.room.hibernate.one_many.sample.Subject;

public class HibernateTest {

	private static SessionFactory sessionFactory=null;

	public static void main(String[] args) {
		Session session=getHibernateSession();
		Transaction transaction=session.beginTransaction();

		session.saveOrUpdate(buildStudent());

		transaction.commit();
		closeHibernateSession(session);
	}

	private static Session getHibernateSession(){
		sessionFactory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
		return sessionFactory.openSession();
	}

	private static void closeHibernateSession(Session session){
		if(session!=null){
			session.flush();
			session.close();
		}
	}

	private static Student buildStudent(){
		Student student=new Student();
		student.setName("Selva Kumar");
		student.setClassName("VI-A");

		Subject subject1=new Subject();
		subject1.setSubName("TAMIL");
		subject1.setSubMark(80);

		Subject subject2=new Subject();
		subject2.setSubName("ENGLISH");
		subject2.setSubMark(78);

		Subject subject3=new Subject();
		subject3.setSubName("MATHS");
		subject3.setSubMark(93);

		Subject subject4=new Subject();
		subject4.setSubName("SCIENCE");
		subject4.setSubMark(88);

		Subject subject5=new Subject();
		subject4.setSubName("SOCIAL SCIENCE");
		subject4.setSubMark(84);

		Set<Subject> subjectColl=new HashSet<Subject>();
		subjectColl.add(subject1);
		subjectColl.add(subject2);
		subjectColl.add(subject3);
		subjectColl.add(subject4);
		subjectColl.add(subject5);

		student.setSubjects(subjectColl);

		return student;
	}

}

Hibernate search using Criteria API’s

December 28, 2010 Leave a comment

Here I have given the sample for multi-criteria search in hibernate using criteria API’s.

The Hibernate criteria api’s provided the simple way for building dynamic queries on hibernate persisted databases.

Here I have consider the Customer entity to be search using the multi-criteria query in hibernate. The Customer entity has the Name and Address entities.
I consider the Address as component which is going to stored in Customer table and Name details to be stored in seperate table.

Jars required :

ant-antlr-1.6.3.jar
antlr-2.7.5H3.jar
asm.jar
asm-attrs.jar
cglib-2.1.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.6.jar
ehcache-1.1.jar
hibernate3.jar
hsqldb.jar
jta.jar
log4j-1.2.9.jar
xerces-2.6.2.jar

Customer.java

package com.room.hibernate.search;

import java.io.Serializable;

public class Customer implements Serializable{

	private static final long serialVersionUID = 1L;
	private Long id;
	private Name name;
	private Address address;
	
	public Name getName() {
		return name;
	}
	public void setName(Name name) {
		this.name = name;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String toString(){
		return this.id+"\n"+this.name+"\n"+this.address;
	}
}

Name.java

package com.room.hibernate.search;

import java.io.Serializable;

public class Name implements Serializable{

	private static final long serialVersionUID = 1L;
	private Long id;
	private String firstName;
	private String middleName;
	private String lastName;
	
      //Setter and Getter methods ......

	public String toString(){
		return this.id+" "+this.firstName+" "+this.middleName+" "+this.lastName;
	}
	
}

Address.java

package com.room.hibernate.search;

import java.io.Serializable;

public class Address implements Serializable{

	private static final long serialVersionUID = 1L;
	private String street;
	private Integer zipCode;
	private String city;
	private String state;
	
        //Setter and Getter methods
	public String toString(){
		return this.street+" "+this.zipCode+" "+this.city+" "+this.state;
	}
}

Define a hibernate mapping file for entities defined as table.

Customer.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.room.hibernate.search">

	<class name="Customer" table="HIB_CUSTOMER">
		<id name="id" column="CUST_ID">
			<generator class="sequence">
					<param name="sequence">HIB_CUST_SEQ</param>
			</generator>
		</id>
		<many-to-one name="name" 
					 column="CUST_NAME_ID"
					 cascade="all"
					 class="Name"/>
		<component name="address" class="Address">
			<property name="street" column="CUST_STREET"/>
			<property name="zipCode" column="CUST_ZIP"/>
			<property name="city" column="CUST_CITY"/>
			<property name="state" column="CUST_STATE"/>
		</component>
	</class>
</hibernate-mapping>

Name.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.room.hibernate.search">

	<class name="Name" table="HIB_CUSTOMER_NAME">
		<id name="id" column="CUST_NAME_ID">
			<generator class="sequence">
					<param name="sequence">HIB_CUST_NAME_SEQ</param>
			</generator>
		</id>
		<property name="firstName" column="CUST_FNAME"/>
		<property name="middleName" column="CUST_MNAME"/>
		<property name="lastName" column="CUST_LNAME"/>
	</class>
</hibernate-mapping>

Create a class for Search customer details using hibernate criteria api’s. Here can able to define the Order using Criteria.addOrder(Order.desc(“somevariable”)) method.

package com.room.hibernate.search.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.AliasToBeanResultTransformer;

import com.room.hibernate.search.Customer;

public class SearchDao {

	private Session session;
	public SearchDao(Session hbSession){
		this.session=hbSession;
	}
	
	private Class<Customer> getEntityClass(){
		return Customer.class;
	}
	public List<CustomerSearchResult> search(final Customer customer){
		Criteria criteria=session.createCriteria(getEntityClass());
		//alias
		criteria.createAlias("name", "custName");
		//create projection list for result transformer
		ProjectionList pl=Projections.projectionList();
		pl.add(Projections.property("id").as("custId"));
		pl.add(Projections.property("custName.firstName").as("customerName"));
		pl.add(Projections.property("address.city").as("custCity"));
		pl.add(Projections.property("address.state").as("custState"));
		pl.add(Projections.property("address.zipCode").as("zipCode"));
		
		criteria.setProjection(pl);
		criteria.setResultTransformer(new AliasToBeanResultTransformer(CustomerSearchResult.class));
		System.out.println("------- building criteria ---------");
		//Restrictions.ilike - adding restriction to criteria for Case-Insensitive search  
		if(customer.getName()!=null){
			if(customer.getName().getFirstName()!=null){
				criteria.add(Restrictions.ilike("custName.firstName", customer.getName().getFirstName()+"%"));
			}
			if(customer.getName().getLastName()!=null){
				System.out.println("lname not null");
				criteria.add(Restrictions.ilike("custName.lastName", customer.getName().getLastName()+"%"));
			}
		}
		if(customer.getAddress()!=null){
			if(customer.getAddress().getCity()!=null){
				criteria.add(Restrictions.ilike("address.city", customer.getAddress().getCity()+"%"));
			}
			if(customer.getAddress().getState()!=null){
				criteria.add(Restrictions.ilike("address.state", customer.getAddress().getState()+"%"));
			}
			if(customer.getAddress().getZipCode()!=null){
				criteria.add(Restrictions.eq("address.zipCode", customer.getAddress().getZipCode()));
			}
		}
		return criteria.list();
	}
}

SearchDao class returns the list of CustomerSearchResult objects which is defined in Projections. Create Result transformer pojo class.

CustomerSearchResult.java

package com.room.hibernate.search.dao;

import java.io.Serializable;

public class CustomerSearchResult implements Serializable{

	private static final long serialVersionUID = 1L;
	private Long custId;
	private String customerName;
	private String custCity;
	private String custState;
	private Integer zipCode;
	
	//Setter and Getter methods
}

Create a hibernate configuration file has the details of Database and Dialect going to be usined and the mapping files configured.(hibernate.cfg.xml )

Create a test class for the Hibernate search criteria :

CustomerSearchTest

package com.room.hibernate.search.dao.test;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.room.hibernate.search.Address;
import com.room.hibernate.search.Customer;
import com.room.hibernate.search.Name;
import com.room.hibernate.search.dao.CustomerSearchResult;
import com.room.hibernate.search.dao.SearchDao;

public class CustomerSearchTest {

	private static SessionFactory sessionFactory=null;
	
	public static void main(String[] args) {
		Session session=getHibernateSession();
		Transaction transaction=session.beginTransaction();
		SearchDao dao=new SearchDao(session);
		List<CustomerSearchResult> list=dao.search(buildCustomer());
		System.out.println("Size "+(list.size()));
		System.out.println("Response :"+list);
		for(CustomerSearchResult response:list){
			System.out.println(response +"\n");
		}
		transaction.commit();
		closeHibernateSession(session);
	}
	
	private static  Customer buildCustomer(){
		Customer cust=new Customer();
		Name name=new Name();
		name.setFirstName("R");
		
		cust.setName(name);
		Address address=new Address();
		address.setState("TamilNadu");
		cust.setAddress(address);
		return cust;
	}
	
	private static Session getHibernateSession(){
		sessionFactory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
		return sessionFactory.openSession();
	}
	
	private static void closeHibernateSession(Session session){
		if(session!=null){
			session.flush();
			session.close();
		}
	}
}
Categories: Hibernate

Simple Hibernate Example

September 1, 2010 1 comment

Here we will see about simple hibernate example

Jars required :

ant-antlr-1.6.3.jar
antlr-2.7.5H3.jar
asm.jar
asm-attrs.jar
cglib-2.1.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.6.jar
ehcache-1.1.jar
hibernate3.jar
hsqldb.jar
jta.jar
log4j-1.2.9.jar
xerces-2.6.2.jar

Project package structure

1. First i write a POJO view class which is going to be mapped to the ralational table.

Employee.java

package com.test.sample.hib.view;

import java.io.Serializable;

public class Employee implements Serializable{

	private static final long serialVersionUID = 1L;
	private Long id;
	private String name;
	private String department;

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
		public String getDepartment() {
		return department;
	}
	public void setDepartment(String department) {
		this.department = department;
	}

	public boolean equals(Object emp){
		if(emp == this){
			return true;
		}
		if(emp instanceof Employee){
			if(this.getName()!=null && ((Employee)emp).getName()!=null){
				return this.getId() == ((Employee)emp).getId()
						&& this.getName().equals(((Employee)emp).getName());
			}
		}
		return false;
	}
	public int hashCode(){
		return this.getId().intValue();
	}
}

2. Write a hibernate mapping file for the POJO class

Employee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.test.sample.hib.view">

	<class name="Employee" table="SA_MA_EMPLOYEE">
		<id name="id" type="long" column="EMP_ID">
			<generator class="sequence">
				<param name="sequence">emp_id_seq</param>
			</generator>
		</id>

		<property name="name" column="EMP_NAME" />
		<property name="department" column="EMP_DEPT" />
	</class>
</hibernate-mapping>

3. Write a hibernate configuration file to connect with database and put a entry of hibernate mapping file like <mapping resource=”${package}/Employee.hbm.xml”/>. This configuration has to be placed under the source folder.

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<!-- a SessionFactory instance listed as /jndi/name -->
	<session-factory>
		<!-- properties -->
		<property name="show_sql">true</property>
		<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
		<property name="connection.username">system</property>
		<property name="connection.password">password</property>
		<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
		<property name="current_session_context_class">thread</property>
		<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
		<!-- mapping files -->
		<mapping resource="com/test/sample/hib/view/Employee.hbm.xml" />
	</session-factory>
</hibernate-configuration>

4. Create a table which is equivalent to the hibernate mapping file .

CREATE TABLE SA_MA_EMPLOYEE ( EMP_ID NUMBER PRIMARY KEY,
                                                EMP_NAME VARCHAR2(20),
 	                                        EMP_DEPT VARCHAR2(20));

CREATE SEQUENCE EMP_ID_SEQ START WITH 1;

5. Write a Test calss.

TestHibernateSample.java

package com.test.sample.hib.test;

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

import com.test.sample.hib.view.Employee;

public class TestHibernateSample {

	public static void main(String[] args) {
		Session session = null;

		try {
			// This step will read hibernate.cfg.xml
			SessionFactory sessionFactory = new Configuration().configure()
					.buildSessionFactory();
			session = sessionFactory.openSession();
			// Create new instance of Contact and set
			System.out.println("Inserting Record");
			Employee emp = new Employee();
			emp.setName("Rathina");
			emp.setDepartment("R&D");
			session.save(emp);
			System.out.println("Done");
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			// Actual contact insertion will happen at this step
			session.flush();
			session.close();

		}

	}
}