CODEXE

Hiberate Tutorial

1 What is Hibernate?

Hibernate is a Java based Object-relational mapping(ORM) tool which is used to map domain model to the database tables

2 How to learn Hibernate?

To learn how to use Hibernate, you can spend tow or three hours on reading this Hibernate tutorial. The following contents are summarized by myself according to my learning experience. Some contents are not covered in the tutorial.

3 Hibernte configuration file

This is an example of Java and MySQL. In the hibernate.cfg.xml file, set the value of hibernate dialect to org.hibernate.dialect.MySQLDialect. The hiernate connection driver id com.mysql.jdbc.Driver. The hibernate commeciton url, username and password should keep same with infomation in the database. The hibernte.cfg.xml file is shown as below:


<?xml version = "1.0" encoding = "utf-8"?> 
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/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>
 <!-- Assume test is the database name -->
 <property name = "hibernate.connection.url"> jdbc:mysql://localhost/test
 </property> 
 <property name = "hibernate.connection.username"> root 
 </property> 
 <property name = "hibernate.connection.password"> root123 
 </property> 
 </session-factory> 
</hibernate-configuration>
			 

4 Bind domain model and database table

After creating the configuration file, we can user annotation and xml file to bnd the domain model and database table.

5 Create session factory

After completing two steps above, let's see how to use Hibernate in the code.

Firstly, we need to create a session factory to manager all sessions. Generally, we just keep one factory for one database in our applicaiton. Thus, we use a sigleton to create session factory.


public enum HibernateUtil {
	INSTANCE;
	private SessionFactory factory = null;
	private HibernateUtil() {
		Configuration configuration = new Configuration().configure();
		configuration.addAnnotatedClass(Domain model.class);
		
		StandardServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
		factory = configuration.buildSessionFactory(registry);
	}
	public SessionFactory getSessionFactory() {
		return this.factory;
	}
}
			 

In the code above, if you use annotation to map domain class, you can call configuration.addAnnotatedClass() to load the resource. If you use xml file, you can call configuration.addResource("Domain Model.hbm.xml").

6 Manipulate database in Java code

Use the following code template to interact with database:


SessionFactory factory =  HibernateUtil.INSTANCE.getSessionFactory();
Transaction transaction = null;
Session session = factory.openSession();
try {
	transaction = session.beginTransaction();

	//Manipulation, update,insert...

	transaction.commit();
}catch(HibernateException e) {
	if(transaction != null) transaction.rollback();
	e.printStackTrace();
}finally {
	session.close();
}
			 

7 Three Hibernate Query Languages

Hibernate has three methods to manipulate database which are Hibernate Query Language (HQL), Criteria Queries, and Native SQL. I prefer to use HQL and criteria.

HQL

We use an example of getting a record in the database by primary key to show the code template used in implementation.


public List<System> getAllSystemsByVersionId(Integer VersionId){
	Session session = factory.openSession();
	Transaction transaction = null;
	List<Activitycompatibility> list = new ArrayList<Activitycompatibility>();
	try {
		transaction = session.beginTransaction();
		String hql = "FROM SystemS WHERE S.versionId = :versionId";
		Query query = session.createQuery(hql);
		query.setParameter("versionId", VersionId);
		list = query.list();
		transaction.commit();
	}catch(HibernateException e) {
		if(transaction != null) transaction.rollback();
		e.printStackTrace();
	}finally {
		session.close();
	}
	return list;
}
			 

Criteria

There are some questions we often meet in the implementation.

Hibernate criteria and or combination


Criteria criteria = getSession().createCriteria(Domain Model.class); 
Criterion cn1= Restrictions.and(Restrictions.eq("A", "1"),Restrictions.eq("B", 1);
Criterion cn2= Restrictions.and(Restrictions.eq("C", "1"),Restrictions.eq("D", 1);
criteria.add(Restrictions.or(cn1, cn2));
			 

Hibernate criteria count avg max etc


Criteria cr = session.createCriteria(persistentClass);

//add other restrictions	

//count				
 cr.setProjection(Projections.rowCount()).uniqueResult();
			 

Tips:

Create hibernate.cfg.xml and domain model mapping files by manual will waste too much time. I recommend to use Hibernate JBoss Tool incroduced in next chapter.