Tuesday, October 18, 2011

Hibernate Hello World Program

Hibernate Hello World using hibernate xml mapping :

Let us start with Hello world program as usual..,
The hibernate.cfg.xml in the application is used to configure the underlying database to Hibernate. Well, we will now go to the package com.demo.helloworld in the Sample application and run the java class HelloExecutor.java.

Things to look into..,


1. The ORM class Hello.java

2. The xml mapping file hello.hbm.xml


ORM class:
(Hello.java)

The ORM class is one whose objects will be persisted into database using hibernate. The Hello.java has three variables id, name, message which are representing the respective columns in the database table.


package com.demo.helloworld;

public class Hello {
private long id;
private String name;
private String message;

//getter and setter methods ...

}


XML mappring file: (hello.hbm.xml)

The Hibernate mapping file does the job of mapping the class to the respective table and mapping the class variables to the respective columns in the table.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping auto-import="false">
<class name="com.demo.helloworld.Hello" table="HELLO" lazy="false">
<id name="id" column="HELLO_ID" type="long">
<generator class="native" />
</id>
<property name="name" column="NAME" type="string" />
<property name="message" column="MESSAGE" type="string" />
</class>
</hibernate-mapping>

* auto-import="false" specifies that the classes must be mentioned with their fully qualified names.

* lazy = "false" specifies that we are not interested in lazy loading and lazy = "true" is recommended for some improved performance tuning.

* The xml element id represents the primary key of the table in the database.

* The element <generator class="native"> specifies the primary key generation and "native" is recommended for portable code between different databases.

Steps to follow before persisting any object:

1. Create a Hibernate Session which represents a particular unit of work with the database.
2. Create a Hibernate Transaction which will help us to commit or rollback our persisting operations.
3. Populate the object to be persisted with it's respective values.
4. Persist the object using session.save(object).

5. Commit or Rollback the transaction.
6. Close the session.

//Persisting the hello object
Session session =HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

Hello helloFirstObj = new Hello();
helloFirstObj.setName("John");
helloFirstObj.setMessage("Welcome");

Hello helloSecondObj = new Hello();
helloSecondObj.setName("Raja");
helloSecondObj.setMessage("Congrates");

session.save(helloFirstObj);
session.save(helloSecondObj);
tx.commit();
session.close();

Each object represents one row in the relational database table.

After executing the progam, check the eclipse for the out put generated. You can turn off the sql generation in the console by setting false in the hibernate.cfg.xml. The table involved in this example is "HELLO" and hence run the following simple sql query in the HSQL DB manager as "select * from hello". (The table name is not case sensitive). You will be able to see as follows.



Hibernate Hello World using Annotations :

Let us go to the package annotation.com.demo.helloworld and execute the java class HelloAnnotationExecutor.java.

Things to look into..

1.
The annotated ORM class annotation.com.demo.helloworld.Hello.java
2.
The utility class HibernateAnnotationUtil.java from the package com.demo.util.

Annotated ORM: (Hello.java)
Here no more hibernate mapping files are required and the mappings are carried out using the annotations available in the package javax.persistence.*

@Entity
@Table(name="Hello")
public class Hello {

@Id
@GeneratedValue (strategy = GenerationType.AUTO)
@Column(name="HELLO_ID")
private long id;

@Column (name="NAME")
private String name;

@Column (name = "MESSAGE")
private String message;

* @Entity marks the class as the entity to deal with
* @Table represents the respective table for this class
* @Id represents the primary key of the table
* @GeneratedValue represents the primary key generation mode.
* @Column represents the respective column for the variable in the class.

HibernateAnnotationUtil.java:

Here in this class we specifically use a different hibernate configuration file (annotation.hibernate.cfg.xml) though we can use the hibernate.cfg.xml. This is done intentionally to make clear that we are not dependent on the hibernate mapping files any more.

We are programatically adding the annotated Hello.java to the AnnatationConfiguration and also the
annotation.hibernate.cfg.xml as follows..,

public class HibernateAnnotationUtil {

private static SessionFactory sessionFactory;
static {
try {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.addAnnotatedClass(annotation.com.demo.helloworld.Hello.class);
sessionFactory=cfg.configure("annotation.hibernate.cfg.xml").buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}

Now execute the HelloAnnotationExecutor.java which is no different from previous
HelloExecutor.java except from creating the session. Verify the results in the eclipse console as well as in the HSQL DB manager as mentioned earlier.

I hope the above examples would have given you some idea on how hibernate persists the objects from the object oriented world to the relational database world.

Let us dig more in detail...