Wednesday, February 22, 2012

Hibernate - HQL

HQL --> Hibernate Query Language

SQL queries have slight differences between different databases.

Hibernate has a SQL version called HQL - which closely mimics the SQL that you are used to. Behind the scenes Hibernate generates the correct SQL queries based on the database.

Let us update UserDAO to use HQL to get a list of Users from the database.

Your UserDAO.java will now look like this:
 package org.confucius;   

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

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class UserDAO {

// HQL with no parameters
public static List<User> getUsers () throws Exception{
List<User> users = new ArrayList<User>();
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

try {
Query query = session.createQuery("from User");
users = (List<User>) query.list();
tx.commit();
}
catch (Exception e){
tx.rollback();
throw e;
}

session.close();
return users;
}


// Getting an object given its Id
public static User getUser (long userId) throws Exception{
User user = null;
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

try {
user = (User) session.get(User.class, userId);
tx.commit();
}
catch (Exception e){
tx.rollback();
throw e;
}

session.close();
return user;
}


// Persist
public static void persist (User user) throws Exception{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

try {
session.persist(user);
tx.commit();

} catch (Exception e){
tx.rollback();
throw e;
}

session.close();
}
}


The HQL query "form User" is, in principle, equivalent to the SQL query "select from user". But Hibernate will generate all the SQL queries needed to get the Users, their Carts and the Items in the cart.

So HQL queries pack a lot of punch. In addition, they are optimized for the Database they are working against.


Update your TestPersistence.java to use this new HQL based DAO method:
 package org.confucius;   

import java.util.Iterator;
import java.util.List;


public class TestPersistence {

public static void main(String[] args) {
try {
List<User> users = UserDAO.getUsers();
for (Iterator<User> iter = users.iterator(); iter.hasNext();)
System.out.println(iter.next());

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

R-click on the TestPersistence.java file in your Eclipse Navigator view.
Select Run As->Java Application.

You will see the user Joe printed to the console, including his cart and its items.

Note the SQL queries that Hibernate generated : the HQL "from User" query resulted in multiple SQL queries.

Hibernate - Querying

So far we saw how to persist objects to the database.

Now let us see how to get them back.

There are 3 ways to do this in Hibernate:
- To get objects directly by their Id, we can use the Session
- If we want to use SQL-like queries, we can use HQL (we will see this later)
- The preferred way is to use Hibernate Criteria API (we will see this later).

First, let us look at the simplest way - to get Objects by their Id.

Update your UserDAO.java with a method to get the User by Id, like this:
 package org.confucius;   

import org.hibernate.Session;
import org.hibernate.Transaction;

public class UserDAO {

// Getting an object given its Id
public static User getUser (long userId) throws Exception{
User user = null;
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

try {
user = (User) session.get(User.class, userId);
tx.commit();
}
catch (Exception e){
tx.rollback();
throw e;
}

session.close();
return user;
}


// Persist
public static void persist (User user) throws Exception{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

try {
session.persist(user);
tx.commit();

} catch (Exception e){
tx.rollback();
throw e;
}

session.close();
}
}

We have used Session.get() to get the User.

Next, let us update User.java with a toString() method, so we can print the User to console.

Your User.java will now look like this:
 package org.confucius;   

import java.util.Iterator;

public class User {
private long id;
private String firstName;
private String lastName;
private Cart cart;

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

public long getId() {
return id;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getFirstName() {
return firstName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getLastName() {
return lastName;
}

public Cart getCart() {
return cart;
}

public void setCart(Cart cart) {
this.cart = cart;
}

public String toString(){
StringBuffer userStr = new StringBuffer();

userStr.append(firstName + " " + lastName + "\n");
userStr.append("Number of Items in Cart = " + cart.getItems().size() + "\n");

for (Iterator<Item> iter = cart.getItems().iterator(); iter.hasNext();)
userStr.append("\tItem = " + iter.next().getName() + "\n");

return userStr.toString();
}

}

Next, update your TestPersistence.java to get a User from the database, like this:
 package org.confucius;   

public class TestPersistence {

public static void main(String[] args) {
try {
User joe = UserDAO.getUser(1);
System.out.println(joe);

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


Now we need to do a few updates to the Hibernate mappings. We need to turn off the "lazy" loading.

By default, Hibernate will not get the dependencies of an object. It will get them only if and when they are needed (lazy).

Update your User.hbm.xml, like this:
 <?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>
<class name="org.confucius.User">
<id name="id" type="long">
<generator class="identity" />
</id>
<property name="firstName" type="string" />
<property name="lastName" type="string" />
<many-to-one name="cart" unique="true" cascade="all" lazy="false"/>
</class>
</hibernate-mapping>

Update Cart.hbm.xml, like this:
 <?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>
<class name="org.confucius.Cart">
<id name="id" type="long">
<generator class="identity" />
</id>
<list name="items" cascade="all" lazy="false">
<key column="cartId"/>
<list-index column="cartListIndex"/>
<one-to-many class="org.confucius.Item"/>
</list>
</class>
</hibernate-mapping>

Finally, we need to update the hibernate.cfg.xml to prevent it from re-creating the tables (we need the data which is in there!).
Like this:
 <?xml version="1.0" encoding="utf-8"?>   
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.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/confuciusDB</property>
<property name="hibernate.connection.username">confucius</property>
<property name="hibernate.connection.password">changeit</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>

<mapping resource="hibernate-beans/Item.hbm.xml"></mapping>
<mapping resource="hibernate-beans/Cart.hbm.xml"></mapping>
<mapping resource="hibernate-beans/User.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

R-click on the TestPerssitence.java file in Eclipse Navigator view.
Select Run As--> Java Application

You will see user Joe printed to the console, along with the contents of his cart.

Notice how Hibernate generated all the SQL queries needed to get the User, Cart and Items.

Tuesday, February 21, 2012

Hibernate - List Mapping

To make our example more realistic, let us make Cart contain a List of Items.
Then see how to map this List of Items in Hibernate.

In your /src/org/confucius, create a class Item.java, like this:
 package org.confucius;  

public class Item {
private long id;
private String name;

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;
}
}


Now, update your Cart.java to contain a List of Items. Like this:
 package org.confucius;  

import java.util.List;

public class Cart {
private long id;
private List<Item> items;

public long getId() {
return id;
}

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

public List<Item> getItems() {
return items;
}

public void setItems(List<Item> items) {
this.items = items;
}
}

In your /classes folder, create a file Item.hbm.xml, like this:
 <?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>
<class name="org.confucius.Item">
<id name="id" type="long">
<generator class="identity" />
</id>
<property name="name" type="string" />
</class>
</hibernate-mapping>

Nothing new here. We map Item to Hibernate.

Update your hibernate.cfg.xml to make it aware of the Item mapping, like this:
 <?xml version="1.0" encoding="utf-8"?>   
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.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/confuciusDB</property>
<property name="hibernate.connection.username">confucius</property>
<property name="hibernate.connection.password">changeit</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="show_sql">true</property>

<mapping resource="hibernate-beans/Item.hbm.xml"></mapping>
<mapping resource="hibernate-beans/Cart.hbm.xml"></mapping>
<mapping resource="hibernate-beans/User.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

Note that we have added "show-sql" so we can see what Hibernate does behind the scenes.


Now, update your Cart.hbm.xml to map the List of Items, like this:
 <?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>
<class name="org.confucius.Cart">
<id name="id" type="long">
<generator class="identity" />
</id>
<list name="items" cascade="all">
<key column="cartId"/>
<list-index column="cartListIndex"/>
<one-to-many class="org.confucius.Item"/>
</list>
</class>
</hibernate-mapping>

We have declared a List of Items, and specified the column names for the Key and List-Index ...what these mean will become clear later.

Finally, update TestPersistence.java, like this:
 package org.confucius;   

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


public class TestPersistence {

public static void main(String[] args) {
User joe = new User();
joe.setFirstName("Joe");
joe.setLastName("Trumpet");

Cart cart = new Cart();
joe.setCart(cart);

List<Item> items = new ArrayList<Item> ();
cart.setItems(items);

Item toothpaste = new Item();
toothpaste.setName("toothpaste");
items.add(toothpaste);

Item diapers = new Item();
diapers.setName("diapers");
items.add(diapers);

Item detergent = new Item();
detergent.setName("detergent");
items.add(detergent);

try {
UserDAO.persist(joe);
} catch (Exception e) {
e.printStackTrace();
}
}
}


R-click on TestPersistence.java in Eclipse Navigator view.
Select Run As->Java Application.

Notice that Hibernate displays the SQL queries in the console because we set the show-sql to true.


If you look at the confuciusDB, you will see the three tables - user, cart and item - linked to each other through foreign keys.
 mysql> select * from user;  
+----+-----------+----------+------+
| id | firstName | lastName | cart |
+----+-----------+----------+------+
| 1 | Joe | Trumpet | 1 |
+----+-----------+----------+------+
1 row in set (0.00 sec)

mysql> select * from cart;
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.00 sec)

mysql> select * from item;
+----+------------+--------+---------------+
| id | name | cartId | cartListIndex |
+----+------------+--------+---------------+
| 1 | toothpaste | 1 | 0 |
| 2 | diapers | 1 | 1 |
| 3 | detergent | 1 | 2 |
+----+------------+--------+---------------+
3 rows in set (0.00 sec)

You will see how the key and list-index columns we specified in Cart mapping are used in the item table.

Note that the cartListIndex columns contains the exact sequence in which each item was added to the items list.

Hibernate - Dependency Mapping

The real power of Hibernate comes in when classes depend on other classes.

Let us create a class Cart and assign a cart to each user.

Update your Cart.java, like this:
 package org.confucius;  

public class Cart {
private long id;
private int numItems = 0;

public long getId() {
return id;
}

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

public int getNumItems() {
return numItems;
}

public void setNumItems(int numItems) {
this.numItems = numItems;
}
}

In yout /classes/hibernate-beans, create a file Cart.hbm.xml, like this:
 <?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>
<class name="org.confucius.Cart">
<id name="id" type="long">
<generator class="identity" />
</id>
<property name="numItems" type="integer" />
</class>
</hibernate-mapping>

Nothing new so far. We have mapped Cart to Hibernate.

Now, update your hibernate.cfg.xml to make it aware of the Cart mapping, like this:
 <?xml version="1.0" encoding="utf-8"?>   
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.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/confuciusDB</property>
<property name="hibernate.connection.username">confucius</property>
<property name="hibernate.connection.password">changeit</property>
<property name="hibernate.hbm2ddl.auto">create</property>

<mapping resource="hibernate-beans/Cart.hbm.xml"></mapping>
<mapping resource="hibernate-beans/User.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>


Now, let us update our User.java, to give users a cart. Like this:
 package org.confucius;   

public class User {
private long id;
private String firstName;
private String lastName;
private Cart cart;

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

public long getId() {
return id;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getFirstName() {
return firstName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getLastName() {
return lastName;
}

public Cart getCart() {
return cart;
}

public void setCart(Cart cart) {
this.cart = cart;
}
}

Now we update our User.hbm.xml to make it aware of the cart.
 <?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>
<class name="org.confucius.User">
<id name="id" type="long">
<generator class="identity" />
</id>
<property name="firstName" type="string" />
<property name="lastName" type="string" />
<many-to-one name="cart" unique="true" cascade="all"/>
</class>
</hibernate-mapping>

What have we done here?
Each User has one-to-one relation with a Cart.

There are two ways to specify a one-to-one relation in Hibernate.
Either with a one-to-one map.
Or with a many-to-one map with a "unique= true" constraint.

The second method is more robust, and more widely used. The first method requires IDs to be synchronized and is more sensitive.

We have specified a many-to-one mapping between User and Cart, with the unique=true constraint.

Further we have used the 'cascade' property, which tells Hibernate that whenever we persist User, the cart should be persisted too. Same for update and delete.

Finally, update TestPersistence.java to give a cart to the User, like this:
 package org.confucius;   


public class TestPersistence {

public static void main(String[] args) {
User joe = new User();
joe.setFirstName("Joe");
joe.setLastName("Trumpet");

joe.setCart(new Cart());
joe.getCart().setNumItems(10);

try {
UserDAO.persist(joe);
} catch (Exception e) {
e.printStackTrace();
}
}
}

R-click on TestPersistence.java in Eclipse Navigator view.
Select Run As->Application.

You can now see two tables created in the confuciusDB database - user and cart.
They are linked by a foreign-key, shown in bold below.

 mysql> select * from user;  
+----+-----------+----------+------+
| id | firstName | lastName | cart |
+----+-----------+----------+------+
| 1 | Joe | Trumpet | 1 |
+----+-----------+----------+------+
1 row in set (0.03 sec)

mysql> select * from cart;
+----+----------+
| id | numItems |
+----+----------+
| 1 | 10 |
+----+----------+
1 row in set (0.11 sec)

Monday, February 20, 2012

Hibernate - DAO

We will now update our UserDAO to use Hibernate.

Your UserDAO.java will now look like this:

 package org.confucius;  

import org.hibernate.Session;
import org.hibernate.Transaction;

public class UserDAO {
public static void persist (User user) throws Exception{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

try {
session.persist(user);
tx.commit();
}
catch (Exception e){
tx.rollback();
throw e;
}

session.close();
}
}


We start by getting a new session from the Hibernate SessionFactory.
We start a new transaction, persist the user, then commit (or rollback) the transaction.

Strictly speaking, we did not have to do this in a transaction. Because there is only one database interaction. However, it is highly recommended in Hibernate to do all database interactions inside a transaction. It keeps the internal state of the Hibernate session clean.

Finally, update the TestPersistence.java to use the new DAO, like this:

 package org.confucius;  


public class TestPersistence {

public static void main(String[] args) {
User joe = new User();
joe.setFirstName("Joe");
joe.setLastName("Trumpet");

try {
UserDAO.persist(joe);
} catch (Exception e) {
e.printStackTrace();
}
}
}

R-click on TestPersistence.java in Eclipse Navigator view. Select Run As-->Java Application.

Now if you go to your MySQL Command Line Client, you will see a new table 'user' containing 'Joe Trumpet', like this:
 mysql> select * from user;  
+----+-----------+----------+
| id | firstName | lastName |
+----+-----------+----------+
| 1 | Joe | Trumpet |
+----+-----------+----------+
1 row in set (0.00 sec)

Hibernate - Basic Mapping

Let us 'map' the User.java class to Hibernate.

To map, is to create a xml file which tells Hibernate how our Class is constructed.

First, our User.java class need to be updated to have a 'id' property.
Hibernate needs this to create a primary key for the table.

So, your User.java class should now look like this:

 package org.confucius;  

public class User {
private long id;
private String firstName;
private String lastName;

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

public long getId() {
return id;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getFirstName() {
return firstName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getLastName() {
return lastName;
}
}



In your /classes folder, create a folder 'hibernate-beans'.

In this folder, create a file User.hbm.xml, like this:

 <?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>
<class name="org.confucius.User">
<id name="id" type="long">
<generator class="identity" />
</id>
<property name="firstName" type="string" />
<property name="lastName" type="string" />
</class>
</hibernate-mapping>


This is the hibernate mapping fir the User class.

It tells Hibernate to use the 'id' field as the primary (id) key.
It specifies the built-in Hibernate generator 'identity' for generating the ids - this means that Hibernate will automatically generate a unique id for each object.

Then it tells Hibernate the properties of User class that we want to persist.

Now we want to tell Hibernate to load this mapping.

Update your hibernate.cfg.xml to make it aware of this mapping file, like this:

 <?xml version="1.0" encoding="utf-8"?>  
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.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/confuciusDB</property>
<property name="hibernate.connection.username">confucius</property>
<property name="hibernate.connection.password">changeit</property&http://www.blogger.com/img/blank.gifgt;
<property name="hibernate.hbm2ddl.auto">create</property>

<mapping resource="hibernate-beans/User.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>


Note the property "hibernate.hbm2ddl.auto" - this is a very useful developer facility. Setting it to 'create' tells Hibernate to automatically create all the necessary database tables. The other options for this property are 'update', 'validate', 'create-drop'.

You can find a brief explanation of these options here.

Hibernate - Setup

We are going to update our UserDAO to use Hibernate.

First, drop the 'users' table from your confuciusDB. Hibernate has its own rules for mapping classes to database schema.

The command for this in MySQL Command Line Client is:

 mysql> drop table users;  

Next, update your ivy.xml to get the hibernate-core.jar, like this:

(I have to add all the dependencies of hibernate-core.jar explicitly because of the way my internal maven repository is setup - you might not need to if you are pointing to Maven central repository)
 <ivy-module version="2.0">  
<info organisation="org.confucius" module="helloworld"/>
<dependencies>
<dependency org="javassist" name="javassist" rev="3.12.1.GA"/>
<dependency org="mysql" name="mysql-connector-java" rev="5.1.18"/>
<dependency org="javax.persistence" name="persistence-api" rev="1.0.2"/>
<dependency org="jboss" name="jboss-j2ee" rev="4.2.2.GA"/>
<dependency org="org.jboss.logging" name="jboss-logging" rev="3.1.0.GA"/>
<dependency org="org.hibernate.common" name="hibernate-commons-annotations" rev="4.0.1.Final"/>
<dependency org="org.hibernate" name="hibernate-annotations" rev="3.5.6-Final"/>
<dependency org="dom4j" name="dom4j" rev="1.6.1"/>
<dependency org="org.hibernate" name="hibernate-core" rev="4.0.1.Final"/>
<dependency org="org.springframework" name="spring" rev="2.5.6"/>
<dependency org="struts" name="struts" rev="1.2.9"/>
<dependency org="org.apache.struts" name="struts-taglib" rev="1.3.10"/>
<dependency org="commons-collections" name="commons-collections" rev="20040616"/>
<dependency org="commons-digester" name="commons-digester" rev="2.1"/>
<dependency org="commons-beanutils" name="commons-beanutils" rev="20030211.134440"/>
<dependency org="commons-logging" name="commons-logging" rev="1.1.1"/>
<dependency org="org.apache.httpcomponents" name="httpcore" rev="4.2-alpha2"/>
<dependency org="org.apache.httpcomponents" name="httpclient" rev="4.2-alpha1"/>
<dependency org="org.apache.commons" name="commons-exec" rev="1.1"/>
<dependency org="com.google.guava" name="guava" rev="r09"/>
<dependency org="org.seleniumhq.selenium" name="selenium-api" rev="2.17.0"/>
<dependency org="org.seleniumhq.selenium" name="selenium-remote-driver" rev="2.17.0"/>
<dependency org="org.seleniumhq.selenium" name="selenium-firefox-driver" rev="2.17.0"/>
<dependency org="org.seleniumhq.selenium" name="selenium-java" rev="2.16.1"/>
<dependency org="junit" name="junit" rev="4.10"/>
<dependency org="org.json" name="json" rev="20090211"/>
<dependency org="javax.servlet" name="servlet-api" rev="2.5"/>
<dependency org="javax.servlet" name="jsp-api" rev="2.0"/>
<dependency org="jstl" name="jstl" rev="1.2"/>
<dependency org="log4j" name="log4j" rev="1.2.16"/>
</dependencies>
</ivy-module>


Run your Ant 'resolve' target to download the hibernate-core.jar to your /lib directory.
It might also download additional jars on which this jar depends.

Update the Eclipse Classpath (Project-->Properties-->Java Build Path-->Libraries-->Add Jars) to include the hibernate-core.jar, and any other jars on which this jar depends.

Next, create a file hibernate.cfg.xml in your /classes directory (same level as /src), like this:

 <?xml version="1.0" encoding="utf-8"?>  
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.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/confuciusDB</property>
<property name="hibernate.connection.username">confucius</property>
<property name="hibernate.connection.password">changeit</property>

</session-factory>
</hibernate-configuration>


This tells Hibernate how to connect to your database, including username and password.

The dialect property tells Hibernate we are using a MySQL database.

If, later, we decide to use Oracle or any of the other 16 or so databases supported by Hibernate, we need to only change this one property!


Add your /classes folder to your Eclipse Classpath. (Project-->Properties-->Java Build Path-->Source-->Add Folders).
We need to do this because we will be running the Hibernate example directly from Eclipse.


Finally, in your /src/org/confucius, create a class HibernateUtil.java which can load the Hibernate configuration, like this:

 package org.confucius;  

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
return configuration.buildSessionFactory(serviceRegistry);
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

public static void shutdownSessionFactory() {
sessionFactory.close();
}
}



This class loads the Hibernate configuration.

By default the hibernate.cfg.xml file is loaded to create a SessionFactory.

If you like, you can specify the exact name of the file in the configuration.configure(), something like configuration.configure("foo.cfg.xml").

This is especially useful if you want to connect to multiple databases. You can create multiple .cfg.xml files, one for each database. Then create multiple SessionFactorys - one for each .cfg.xml.