| In my previous post Hibernate, the ORM Library for Java, we have seen the General introduction of ORM Tools and how to configure the hibernate to use it in our applications. In this post we’ll look at the simple examples of DB Operations using Hibernate. |
| Please have all the libraries needed to work with MySQL with Hibernate, the most important libraries are hibernate3.jar and mysqlconnector.jar.(If you are using MyEclipse, that’ll help you in adding those jars). For using the MySQL the hibernate configuration will look like the following. |
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/Singer</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">demo</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
|
| For domain class we’ll take the example of Singer, Who performs some stage shows. As of now we’ll add two properties for him, Which is id and the name of the singer. So we’ll have to configure the Singer.hbm.xml file for Singer as follows. |
<hibernate-mapping>
<class name="com.techmaddy.singer" table="TBL_SINGER">
<meta attribute="class-description">Domain Object for Singer</meta>
<id name="singerId" type="long" column="SINGER_ID">
<generator class="native"/>
</id>
<property name="singerName" type="string" column="SINGER_NAME" not-null="true" />
</class>
</hibernate-mapping>
|
| We can make use of the MyEclipse’s “Hibernate Reverse Engineering” option from the database perspective, so that we can easily generate the Singer.hbm.xml and Singer.java domain class also. |
package com.techmaddy.singer;
public class Singer implements java.io.Serializable {
private Long singerId;
private String singerName;
public Singer() {
}
public Singer(String singerName) {
this.singerName = singerName;
}
public Long getSingerId() {
return this.singerId;
}
public void setSingerId(Long singerId) {
this.singerId = singerId;
}
public String getSingerName() {
return this.singerName;
}
public void setSingerName(String singerName) {
this.singerName = singerName;
}
}
|
This above code ss an domain class for Singer, It’s just nothing but an POJO or we can say an JavaBean. The other important component fo Hibernate is SessionFactory. The SessionFactory provides the session to work with RDBMS. SessionFactory should be created only once per application on web container. SessionFactory can be created many ways, most of the time SessionFactory will be created as a Singleton utility class.By using the following methods, we can creating the SessionFactory, they are
- An Utility Class with Singleton - A Singleton class with the option to create an SessionFactory and then the object can be made available to JVM.
- From an Servlet - A servlet which is loaded on startup of the container and the service method pushes the object into an Singleton Utility class
- Static Block - inside a static block in some sort of Utility Java class that can be used in program code to retrieve SessionFactory
We’ll implement the third option to create the SessionFactory.
|
package com.techmaddy.singer
public class FactoryUtil {
//Static Session Factory
private static org.hibernate.SessionFactory sessionFactory;
private FactoryUtil() {
}
static {
//Creates the SessionFactory based on the XML Configuration
Configuration configs = new Configuration();
sessionFactory = configs.configure().buildSessionFactory();
}
public static SessionFactory getInstance() {
return sessionFactory;
}
public Session openSession() {
return sessionFactory.openSession();
}
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public static void close() {
if (sessionFactory != null)
sessionFactory.close();
sessionFactory = null;
}
}
|
| The above code creates the SessionFactory, since the creation of SessionFactory is in Static block, we’ll be able control the creation of SessionFactory object. By this way we”l have the control of creating the session obejcts. The SessionFactory reads the hibernate cfg xml and then it creates the session object for our application. We are all set to go and write our class, to test the hibernate. |
| Basically we’ll look into the example of CRUD by making use of the Hibernate Session object. |
package com.techmaddy.singer;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class CRUDTest {
public static void main(String[] args) {
CRUDTest crudTest = new CRUDTest();
Long singer = crudTest.insertSinger("Jason");
singer = crudTest.insertSinger("Jerry");
singer = crudTest.insertSinger("Chun");
}
public Long insertSinger(String singerName) {
Session session = FactoryUtil.getSessionFactory().openSession();
Transaction transaction = null;
Long singerId = null;
try {
transaction = session.beginTransaction();
Singer singer = new Singer();
singer.setSingerName(singerName);
singerId = (Long)session.save(singer);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return singerId;
}
}
|
|
| When we run this following code, we’ll get the output in the console as follows,this is since we mentioned “show_sql” property in hibernate.cfg.xml to “true”. |
 |
| After executing this statement, we can check the database for inserted values. |
|

|
|
| I’ve added the update and delete operations in CRUDTest and it has been updated as follows |
package com.techmaddy.singer;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class CRUDTest {
public static void main(String[] args) {
CRUDTest crudTest = new CRUDTest();
Long singer = crudTest.insertSinger("William");
singer = crudTest.insertSinger("Jerry");
Long tempSinger = singer;
singer = crudTest.insertSinger("Stanley");
crudTest.listSinger();
crudTest.updateSinger(singer,"Chun");
crudTest.deleteSinger(tempSinger);
}
public Long insertSinger(String singerName) {
Session session = HibernateSessionFactory.getSessionFactory().openSession();
Transaction transaction = null;
Long singerId = null;
try {
transaction = session.beginTransaction();
Singer singer = new Singer();
singer.setSingerName(singerName);
singerId = (Long)session.save(singer);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return singerId;
}
public void listSinger() {
Session session = HibernateSessionFactory.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
List singers = session.createQuery("FROM Singer").list();
for (Iterator iterator = singers.iterator(); iterator.hasNext();) {
Singer singer = (Singer) iterator.next();
System.out.println(singer.getSingerName());
}
transaction.commit();
}
catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
}
finally {
session.close();
}
}
public void updateSinger(Long singerId, String singerName) {
Session session = HibernateSessionFactory.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Singer singer = (Singer) session.get(Singer.class, singerId);
singer.setSingerName(singerName);
session.update(singer);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public void deleteSinger(Long singerId) {
Session session = HibernateSessionFactory.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Singer singer = (Singer) session.get(Singer.class, singerId);
session.delete(singer);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
|
|
|
|