Tuesday, December 31, 2013

How to download source of dependencies jars using Maven

To download source of dependencies jars in local repository while building project using Maven, you need to add "dependency:sources" goal while building your project.

Run following command for your project and it will download all sources for dependencies if it exists.
Command : mvn dependency:sources

You can find more information related to dependency plugin at Maven Dependency Plugin project.


Sunday, December 1, 2013

Java: List of books you must read

Here is list of must read books if you are java developer.
1. Head first OOAD
2. Effective java
3. Java puzzlers
4. Java concurrency in practice
5. Design patterns by GOF
6. Spring in action
Your comments are welcome if you want to add to this list.

Monday, August 26, 2013

Java: Thread program to demonstrate wait and notify

Below question was asked to one of my friend during interview:

Write program to create 2 Threads "Jack" and "Jill". You write a program which will print " Jack Jill Jack Jill"
Thread execution:  Thread1, Thread2, again Thread2, then Thread2.


I tried to write program for above problem :
T1. Java:


public class T1 implements Runnable {
private static int count = 0;
public synchronized void run() {
int threadCount = 0;
while (true) {
count++;
threadCount = count;
System.out.println(Thread.currentThread().getName());

try {

notifyAll();
while (threadCount >= count) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}

// If you comment below if block, Jack , jill threads will run
// forever one after another.
// So added to check if Jack and Jill threads run one after another
// 2 times
if (count >= 4) {
count++;
System.out.println(Thread.currentThread().getName() + " End");
notifyAll();
break;
}
}

}
public static void main(String[] args) {
T1 t = new T1();
Thread t1 = new Thread(t, "Jack");
Thread t2 = new Thread(t , "Jill");
t1.start();
t2.start();
}

}


Output:

Jack
Jill
Jack
Jill
Jack End
Jill End

Saturday, July 27, 2013

Java : How HashMap stores and returns element

Hashing technique is useful in searching exact data in very short time.
In Java Collection Framework, Hashmap class provides functionality to store data using hashing techniques.
Here is how HashMap works internally.

Following main parameters are used to store data in HashMap:
  • Internal static class Entry which contains following variables
    • Key
    • Value
    • Next element
    • Hash value
  • Array of Entry objects (Bucket)
  • Threshold (Initial capacity * load factor)


While putting element in HashMap:
·         If key is null, it allows putting single value against null key. If you are trying to add another value against null key, it returns existing value in HashMap against null key and stores new value against null key.
o   Entry Object is stored at Bucket location 0. Hash value is also zero for null key.


·         How Value is stored against key in HashMap:
  •       Internal hash function is used to calculate hash value for hashcode of key. Hashcode of key is passed to hash function to get hash value.
  • Bucket index is found based on hash value and length of bucket. (Bucket is array which is used to store data. Data is Entry objects which contains key, value, next object and hash values). Bucket index = hash value & (bucket size-1). Bitwise and operator is used to find out index value.
  • Iterator is used to iterate over Entry objects at given index (if exists) to check if same key is already exists by comparing hash value and object equality using equals function. If same key is found, new value is stored against key and old value is returned.

Tuesday, July 16, 2013

JMS overview and sample standalone example

JMS API is used to allow applications to create, send, receive messages. It is mostly used in enterprise distributed systems (J2EE applications) for processing data asynchronously. It consists of
JMS API architecture
Messaging domain
Messaging receiver

JMS API Architecture:
JMS application consists of :

  1. JMS provider:  Messaging system that implements JMS interfaces and provide admin and control features
  2. JMS Client: Programs that produce and consume messages.
  3. Messages: objects that are transferred between JMS clients to communicate information.
  4. Administered Objects: pre configured JMS objects created by JMS administrator to be used by clients. Two kind of objects are destinations and connection factories.


There are 2 types of approaches for messaging- Point to point and Publish/subscribe.

  • Point to Point messaging: Based on message queue, message sender and message receiver. Message is addressed to specific queue. Queues retain all message until it is consumed by receiver or until message expires.
  • Publish/Subscribe messaging: In Pub/Sub messaging, message producer sends message to Topic. Message is delivered to receivers who have subscribed to that topic.

Apache ActiveMQ, Weblogic, OpenJMS, IBM Websphere MQ  are few examples of JMS provider implementations.
Below sample example shows simple standalone example of  JMS point to point messaging where administered objects (server configuration) are not used. You need Apache ActiveMQ jars to run this program.

Sample TestJMS.java file:

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQQueue;


public class TestJMS {

public static void main(String[] args) {

try {
//Start JMS service
BrokerService broker = new BrokerService();
broker.addConnector("tcp://localhost:61616");
broker.start();


ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");

Connection conn = connectionFactory.createConnection();

Queue queue = new ActiveMQQueue("testQueue");

Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

//Message Producer
MessageProducer prod = session.createProducer(queue);
//Message consumer
MessageConsumer consumer = session.createConsumer(queue);

TextMessage msg = session.createTextMessage("Hello JMS");
conn.start();
prod.send(msg);

Message message = null;
while((message = consumer.receiveNoWait()) != null){
if(message != null){
System.out.println("Message received:"+((TextMessage)message).getText());
}
}

conn.close();
broker.stop();

} catch (Exception e) {
e.printStackTrace();
}

}
}


Output of program:
Message received:Hello JMS

You can download ActiveMQ at : http://activemq.apache.org/

I have used "activemq-all-5.6.0.jar" as Build path library to run above application.

Thursday, July 4, 2013

Java: Thread Basics and Questions

Here are few general questions and answers related to Threads in Java

1. What is thread?
--> Thread is lightweight process which has its own stack trace but share resources.

2. Types of Thread:
--> Daemon thread and User thread : JVM exits when all user threads complete. It does not care whether daemon threads are complete or not.

3. How can we create Thread in java
--> a)  By extending Thread class
      b) By Implementing Runnable interface
Implementing Runnable is preferred because extending a Thread is meant to create specialized version of Class Thread where we may need some special behaviour. And We always instantiate thread by creating new instance of Thread class.

4. How to start a new thread?
--> by calling start() method of thread instance.

5. Explain different Thread states:
--> New : When thread instance is created and start method is not yet invoked. Thread t = new Thread(Runnable r);
Runnable: When thread is eligible to run but execution is not started. Threads enters in runnable state for first time when start() method is called. Thread also enters in runnable state after coming back from blocked, waiting, sleeping state.
Running: When scheduler picks thread for execution from runnable pool.
Waiting/Sleeping/Blocking: When thread is still alive but not eligible to run. Thread is not runnable but it might come to runnable when particular event happens.
Dead: Thread is dead when its run method completes. Once thread is dead, it cannot be invoke again by calling start(). It will generate runtime exception. Thread object is still valid object but not valid for separate thread of execution.

6. What is yield() method of Thread:
--> yield() method make currently running thread back to runnable pool to get other threads in runnable pool to get chance. But it is not guaranteed. Same thread can be picked up for execution by thread scheduler. When yield() is called. Thread goes from Running to Runnable state.

7. What is join() method:
--> Let one thread to join at the end of another thread. when t.join() is called. Currently running thread to join at the end of t. It means that currently running thread is blocked till t thread is complete.

8. When Currently running thread leaves running state:
a. When thread is complete. (run method is complete)
b. Thread can not acquire lock on object whose method it is trying to call.
c. When scheduler decides to move thread from running to runnable state.
d. Call to wait() on object

9. How can you prevent more than one threads to access code in Java
--> Using synchronization. We can use either synchronized method or synchronized block so that only one thread can access that method/block of code at a time.

10. How synchronization works
--> Synchronization work with lock on object. Every object in java has built in lock. When non-static method is synchronized, Thread which is running the code acquires lock on object which is calling method. No other thread can call synchronized method for that object unless current thread comes out of sync. method.
When synchronized method completes, thread releases lock so that other threads can call synchronized method on that object. Same applies for Synchronized block.
We declare synchronized block with synchronized(object){ }. We can pass any object as parameter to synchronized block. Thread acquires lock on that object. If we pass "this" as parameter to synchronized block, current instance of that class is locked.
Static methods can be synchronized. There is class instance (only one instance) of every class on which thread acquires lock.

Note: wait() method gives up lock while sleep(), yield(),join(), notify() keeps lock.

11. How thread interact with each other.
--> Using wait(), notify(), notifyAll(). Note that these methods should be called from synchronized block/method.

Wednesday, July 3, 2013

Object Oriented Programming Basic Concepts

Object oriented programming is useful for many aspects:
1. Code reuse.
2. Better design


Encapsulation: Hiding data and behaviour of an Object and provide interface (public methods) to outside objects to access data. It helps in preventing users from setting objects state directly which can cause inconsistency.

Inheritance: Way to establish relationship between objects. Here class inherit properties and method of parent class. Inheritance is termed as "Is a relationship" (Parent-Child relationship)

Polymorphism: Means many forms. Similar type of objects can behave differently for same message.
It is tightly coupled with Inheritance. Parent class provide interface(method) which is implemented differently by different child classes.


Tuesday, June 25, 2013

Java : General purpose Implementation Classes in Collection Framework


Collection framework consists of general purpose implementation of Set, Map, List interfaces.
Details of Interfaces in Collection framework is available at Collection Framework Interfaces
Main characteristics of General purpose implementation in Collection framework is described as below.

HashSet:
  • Extends AbstractSet, implements Set, Cloneable, Serializable.
  • Implements Set interface backed by HashMap instance.
  • Null element is allowed.
  • Unordered collection.
  • Default initial capacity of 16 and load factor of 0.75.
  • Constant time performances for basic operations (add, remove, size, contains).
  • Iterating over set requires time proportional to number of elements in Set and capacity of backing HashMap instance.
  • Not synchronized.
  • Iterator returned by this class is fail-fast. If set is modified after iterator is created, iterator throws ConcurrentModificationException.

TreeSet:
  •  Extends AbstractSet, implements NavigableSet, Cloneable, Serializable
  • Implementation is based on TreeMap.
  • Elements are ordered by natural order or by Comparable provided at the time of creation of Set.
  • Not synchronized.
  • Null is not allowed.
  • Iterator returned by this class is fail-fast. If set is modified after iterator is created, iterator throws ConcurrentModificationException.
  • There are methods available to get subset of existing Set. Subset is backed by original Set, so any addition of element within range to set will be reflected to Subset and vice-versa.
    • subset(fromElement, toElement) - fromElement is inclusive and toElement is excluded
    • subSet(fromElement,  boolean fromInclusive, toElement, boolean toInclusive) –using Boolean fromElement and toElement can be made inclusive or excluded.

ArrayList:
  • Extends AbstractList, implements List, Cloneable, Serializable, RandomAccess.
  • Random access of elements is fast compared to LinkedList.
  • Element are stored in sequence in array.
  • Null is allowed.
  • Not synchronized.
  • Iterator returned by this class is fail-fast. If set is modified after iterator is created, iterator throws ConcurrentModificationException.
  • ArrayList has capacity which is size of array to store objects. ensureCapacity  method is used to make sure that size of ArrayList is appropriate.
  • Default initial capacity is 10.


LinkedList:
  • Extends AbstractSequentialList, implements List, Deque, Cloneable, Serializable.
  • Null is allowed.
  • Methods available to add, remove, get element at the beginning and end of the list.
  • Not synchronized.
  • Iterator returned by this class is fail-fast. If set is modified after iterator is created, iterator throws ConcurrentModificationException.

  
HashMap:
  • Extends AbstractMap, Implements Map, Serializable, Cloneable.
  • HashMap allows one null key
  • Not synchronized.
  • Iterator returned by this class is fail-fast. If set is modified after iterator is created, iterator throws ConcurrentModificationException.
  • HashMap has two parameters – Initial capacity and load factor which affects performance.
  • Default initial capacity 16
  • Default load factor 0.75
  • Rehashing is done when capacity/load factor is more than number of elements in HashMap.

Wednesday, June 19, 2013

Java : Interfaces in Collection Framework

Collection Interfaces:

  •  Collection
  • Set
    •    SortedSet
    •    NavigableSet
  • List
  • Queue
    •  BlockingQueue
    • TransferQueue
    • Deque
  • Map
    • SortedMap
    • NavigableMap
    • ConcurrentMap
    • ConcurrentNavigableMap

Main interfaces:
  • Collection:
    • Root interface in Collection hierarchy. It represents group of objects. Java does not provide direct implementation of this interface. It provides implementation of more specific interfaces by extending this interface like Set, List.
    • This interface defines basic operations for group of objects.
    • There are also some methods which are tagged as optional operations which may not be applicable for specific type of collection. E.g. For read only collections, add(E), remove(Object) methods are not required, so implementation classes may just throw UnsupportedOperationException in method implementation.  If the invocation would have no effect on the collection, then it may or may not throw exception.
  • Set:
    • Collection that contains no duplicate elements and at most one null element. (some implementations does not allow null)
    • You have to be careful when mutable objects are added as elements of set. Set behaviour is not specified if value of object which is in set is changed which affects equals comparison.
    • Set provides additional constraint on add method to prevent duplicates.
  • List:
    • List is ordered collection. List may contain duplicates.
    • List provides special iterator, called ListIterator, which allows element insertion, bidirectional access.
    • List provides additional constraint over iterator, add, remove methods to maintain sequence of elements.
  • Queue:
    • Queue typically, but not necessarily, order elements in FIFO manner. Among the exceptions are priority queues, which order elements according to a supplied comparator or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out)
    • Queue provides additional methods for insertion, removal, inspection operations which returns special value (null or false) if operation fails. Collection methods add, remove, element throws exception if method fails.
    • Queue generally does not allow null. (Except LinkedList). Null should not be inserted into queue because null is returned by poll method to indicate that queue is empty.
  • Map:
    • Object that contains key-value pair. Map interface does not extends Collection.
    • Map cannot contain duplicate key. So special care should be taken when mutable objects are used as keys.

Additional Interfaces:


  • SortedSet:
    • Ordered collection.
    • Elements are by default in natural order or as per Comparator provided at creation time.
    • All elements inserted into a sorted set must implement the Comparable interface.
    • General implementation of SortedSet should provide 4 standard constructors.
      • Void constructor with no parameter
      • Constructor with parameter as Comparator
      • Constructor with parameter as Collection
      • Constructor with parameter as SortedSet
  • NavigableSet:
    • It extends SortedSet and provides navigation methods to find closest match for given target.
    • Navigation methods are lower, floor, ceiling, higher.
    • pollFirst and pollLast methods that return and remove the lowest and highest element, if one exists, else returning null.
  • Deque:
    • Double ended queue. Extends Queue.
    • Element insertion and removal at both ends.
    • Interface defines methods (add, remove, get) to access elements at both end of queue. All methods have 2 forms. One throws exception if operation fails and other returns special value (null or false).
  • BlockingQueue:
    • Interface of concurrent package. Use for Producer-Consumer type operation.
    • While inserting element in queue, it waits if for space to be available when queue is full.
    • While retrieving element from queue, it waits if queue is empty.

Friday, June 14, 2013

Java Collection Framework Basic

Java collection framework and its classes are used to store and process group of objects.

Advantages of Collection framework:
  •  Reduces programming effort: Useful data structures and utility classes to process data for searching/sorting etc. are readily available in Collection framework.
  •   Provides inter- operability between API’s: Collection objects are used to pass/return to different API methods instead of creating different data structures for each API.
  • Increased performance: High performance implementation of data structure in Collection framework.

  
Collection framework consists of:
  1. Collection Interfaces: Different type of collection interfaces like set, map, list, queue.
  2. Collection implementation classes: Different type of concrete implementations of collection interfaces.
  3. Concurrent implementation: Implementations for concurrent use.
  4. Algorithms: Utility classes with methods to do searching, sorting operations.


Thursday, June 13, 2013

Java: Storing null key in HashMap

HashMap is useful in searching exact data in short time.
HashMap allows only one null key. Let's see how it stores null key internally.

If key is null, HashMap allows putting single value against null key. 
If you are trying to add another value against null key, it returns existing value for null key and stores new value against null key.
Internally HashMap maintains array of Entry class(internal class of HashMap which is used to store data) which is also called as Bucket.
Entry class contains key, value, nextElement, hash-value variables.

Data with null key is stored at Bucket location 0(array index 0 of Entry array). Hash value is also zero for null key.

Example:
HashMap h = new HashMap();  You can also use HashMap instead of HashMap.
h.put(null, "A");         -- Value "A" is stored against null key
h.put(null, "B");         -- Value "B" is stored against null key and old value "A" is returned as return type of put function is V i.e. value object
h.put(null, "C");         -- Value "C" is stored against null key and old value "B" is returned 



Wednesday, June 5, 2013

Sample Hibernate Application Using Eclipse and using annotations

In first example, I have created sample Hibernate project using mapping files
Next step is to convert same application to use annotations.
Change Employee.java and Department.java files to use annotations as shown below.

Employee.java

package com.test.beans;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="EMP")
public class Employee {
@Id @GeneratedValue
@Column(name="emp_id")
private Long empId;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="degn")
private String designation;
@Column(name="sal")
private double salary;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="dept")
private Department dept;
public Long getEmpId() {
return empId;
}
public void setEmpId(Long empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
}

Department.java:

package com.test.beans;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="DEPT")
public class Department {
@Id @GeneratedValue
@Column(name="dept_id")
private long deptId;
@Column(name="dept_name")
private String deptName;
@Column(name="loc")
private String location;
public long getDeptId() {
return deptId;
}
public void setDeptId(long deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}

Change hibernate.cfg.xml file as:

  <? xml version="1.0" encoding="UTF-8"?>


<!

DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD/EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >


<hibernate-configuration>



<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>

<mapping class="com.test.beans.Employee" />
<mapping class="com.test.beans.Department" /> 
</session-factory>
</hibernate-configuration>


You can delete (organization.hbm.xml) hbm mapping file.

Now your sample annotation project is ready. You can run Test.java file to check the output.

Sunday, June 2, 2013

Automatic Dirty checking and Transaction write-behind concepts of Hibernate

Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transaction write-behind.

Automatic Dirty checkingIf object which is already saved is modified, then Hibernate automatically call update on that object.
Hibernate is capable of detecting all objects that are modified or are dirty. It is done with the help of PersistanceContext.
Within PersistanceContext, Hibernate has copy of all persistent objects that are loaded from database in Session. It compares persistent object to determine whether object is modified.


Hibernate allows implementation of custom dirty checking algorithm. This is done by implementing findDirty() method of org.hibernate.Interceptor interface for a Session.

Friday, May 31, 2013

Sample Hibernate Application Using Eclipse using mapping file

Here are steps to create sample hibernate application using eclipse. I am using hibernate version 4.2 and MySQL database for reference.
First I will create it using mapping xml file. Then convert same application to use annotation and finally JPA.
Create Java Project as:

Create java project - HibernateJPA

Create below packages in src folder by using option "create package"
com.test.beans
com.test.resources
com.test.dao
com.test.util

Add hibernate dependencies for project by right clicking on project "Build Path" --> Configure Build Path.
Under Libraries Tab: Add external jar button and add Hibernate required jar files.
  • antlr-2.7.7.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.1.Final.jar
  • hibernate-core-4.2.0.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • javassist-3.15.0-GA.jar
  • jboss-logging-3.1.0.GA.jar
  • jboss-transaction-api_1.1_spec-1.0.0.Final.jar
Also add mysql connector jar.
  • mysql-connector-java-3.1.14-bin.jar
 Create HibernateUtil.java file under package com.test.util for creating and using SessionFactory object as:
For more details about building SessionFactory refer post Creating SessionFactory.
HibernateUtil.java


package com.test.util;



import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;



public class HibernateUtil {
       private static SessionFactory sessionFactory;

static{
       try {
               sessionFactory = new Configuration().configure("com/test/resources/hibernate.cfg.xml").buildSessionFactory();


       }

       catch (Exception e) {                
           throw new ExceptionInInitializerError(e);
       }

   }


public static SessionFactory getSessionFactory(){
     return sessionFactory;
}
public static void shutDown(){
      getSessionFactory().close();
}
}
 
 Employee and Department classes which are persistace objects in package com.test.beans:

Employee.java



package  com.test.beans;





public class Employee {



private Long empId;
private String firstName;
private String lastName;
private String designation;
private double salary;
private Department dept;
public Long getEmpId() {
        return empId;
}
public void setEmpId(Long empId) {
        this.empId = empId;
}
public String getFirstName() {
        return firstName;
}
public void setFirstName(String firstName) {
        this.firstName = firstName;
}
public String getLastName() {
        return lastName;
}
public void setLastName(String lastName) {
        this.lastName = lastName;
}
public String getDesignation() {
       return designation;
}
public void setDesignation(String designation) {
       this.designation = designation;
}
public double getSalary() {
      return salary;
}
public void setSalary(double salary) {
     this.salary = salary;
}
public Department getDept() {
     return dept;
}
public void setDept(Department dept) {
     this.dept = dept;
}
}


Department.java 

package  com.test.beans;

public class Department {
private long deptId;

private String deptName;
private String location;



public long getDeptId() {

         return deptId;
}
public void setDeptId(long deptId) {
           this.deptId = deptId;
}

public String getDeptName() {
          return deptName;


}


public void setDeptName(String deptName) {
         this.deptName = deptName;
}
public String getLocation() {
         return location;


}


public void setLocation(String location) {
         this.location = location;
}
}
We need hibernate configuration file for settings related to connecting database. (configuration file contains much more but for simple application, i am only defining minimum required settings)

hibernate.cfg.xml

  <? xml version="1.0" encoding="UTF-8"?>


<!

DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD/EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >


<hibernate-configuration>



<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<mapping resource="com/test/beans/organization.hbm.xml" />
</session-factory>
</hibernate-configuration>



Now we need mapping file which defines mapping of Persistance classes with database tables:

organization.hbm.xml



< xml version="1.0"?>



<!



DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">


package="com.test.beans">
<class name="Department" table="DEPT">
     <id name="deptId" column="dept_id">
               <generator class="native" />
     </id>
     <property name="deptName" type="string" column="dept_name" unique="true"/>
     <property name="location" type="string" column="loc"/>
</class>
<class name="Employee" table="EMP" >
       <id name="empId" column="emp_id">
                 <generator class="native"></generator>
       </id>
       <property name="firstName" type="string" column="first_name" />
       <property name="lastName" type="string" column="last_name" />
       <property name="designation" type="string" column="degn" />
       <property name="salary" type="double" column="sal" />
       <many-to-one name="dept" column="dept"  class="Department" />
</class>
</hibernate-mapping>



Hibernate application is ready and let's create test class to test the application.

Test.java




package com.test.dao;



import org.hibernate.Session;
import org.hibernate.Transaction;
import com.test.beans.Department;
import com.test.beans.Employee;
import com.test.util.HibernateUtil;

public  class Test {



public static void main(String[] args) {
          Employee emp = new Employee();
          emp.setFirstName("fName");
          emp.setLastName("lName");
          emp.setDesignation("Java Developer");
          emp.setSalary(20000);
          Department dept= new Department();         
          dept.setDeptName("Design");         
          emp.setDept(dept);        
          Session sess = HibernateUtil.getSessionFactory().openSession();
         Transaction tran = sess.beginTransaction();
         sess.save(emp);
         sess.flush();
         tran.commit();
         sess.close();
}
}
After running above class, Employee and Department data is stored in respective tables. You get console log to understand how hibernate works in background.
Console Log:






May 31, 2013 7:18:36 PM org.hibernate.annotations.common.Version


INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}

May 31, 2013 7:18:36 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.0.Final}
May 31, 2013 7:18:36 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
May 31, 2013 7:18:36 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 31, 2013 7:18:36 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: com/test/resources/hibernate.cfg.xml
May 31, 2013 7:18:36 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: com/test/resources/hibernate.cfg.xml
May 31, 2013 7:18:36 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
May 31, 2013 7:18:36 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: com/test/beans/organization.hbm.xml
May 31, 2013 7:18:36 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
May 31, 2013 7:18:36 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
May 31, 2013 7:18:36 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
May 31, 2013 7:18:36 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
May 31, 2013 7:18:36 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
May 31, 2013 7:18:36 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/test]
May 31, 2013 7:18:36 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
May 31, 2013 7:18:36 PM org.hibernate.dialect.Dialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
May 31, 2013 7:18:36 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
May 31, 2013 7:18:36 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 31, 2013 7:18:36 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
INFO: HHH000397: Using ASTQueryTranslatorFactory
May 31, 2013 7:18:36 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export




Hibernate:


alter table Employee
drop
foreign key FK4AFD4ACEF1062AF1
Hibernate:
drop table if exists DEPT
Hibernate:
drop table if exists Employee
Hibernate:
create table DEPT (
dept_id bigint not null auto_increment,
dept_name varchar(255),
loc varchar(255),
primary key (dept_id)
)
Hibernate:
create table Employee (
MESSAGE_ID bigint not null auto_increment,
first_name varchar(255),
last_name varchar(255),
degn varchar(255),
sal double precision,
dept bigint,
primary key (MESSAGE_ID)
)
Hibernate:
alter table DEPT
add constraint uc_DEPT_1 unique (dept_name)
Hibernate:
alter table Employee
add index FK4AFD4ACEF1062AF1 (dept),
add constraint FK4AFD4ACEF1062AF1
foreign key (dept)
references DEPT (dept_id)







May 31, 2013 7:18:37 PM org.hibernate.tool.hbm2ddl.SchemaExport execute

INFO: HHH000230: Schema export complete








Hibernate:


/* insert com.test.beans.Department
*/ insert
into
DEPT
(dept_name, loc)
values
(?, ?)
Hibernate:
/* insert com.test.beans.Employee
*/ insert
into
Employee
(first_name, last_name, degn, sal, dept)
values
(?, ?, ?, ?, ?)

To convert same application to use Annotations, Refer next post.