Mock tests, Interview questions, Tutorials and Tech news
 
 
Home > Programming / tutorials > Hibernate Persistence Tutorial: Use Hibernate in your java applications to access database

Hibernate Persistence Tutorial: Use Hibernate in your java applications to access database

This is third hibernate tutorial for advanced users .We will talk about hibernate persistence  and how you will connect with hibernate to the database. The database we would be using is mysql.

Our last two posts had covered hibernate setup , hibernate configuration and how using annotation with hibernate.

First Hibernate Tutorial

Hibernate Using Annotations
 

Step 1:  Create java project in eclipse

Step2: add the required libraries.

 These steps are well explained with screenshots in :

The required jars used in my projects are:

mysql-connector.jar
ejb3-persistence.jar, antlr-2.7.6.jar
asm.jar
asm-attrs.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
concurrent-1.3.2.jar
connector.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
hibernate3.jar
hibernate-annotations.jar
hibernate-entitymanager.jar
hibernate-tools.jar
jaas.jar
jacc-1_0-fr.jar
javassist.jar
jaxen-1.1-beta-7.jar
jboss-cache.jar
jboss-common.jar
jboss-jmx.jar
jboss-system.jar
jdbc2_0-stdext.jar
jgroups-2.2.8.jar
jta.jar
log4j-1.2.11.jar
oscache-2.1.jar
proxool-0.8.3.jar
swarmcache-1.0rc2.jar
syndiag2.jar
xerces-2.6.2.jar
xml-apis.jar

Step 3:

The Directory structure of the application:

I created a following structure:

Com.myapp.eo this package will contain all the Entity Classes.

Com.myapp.vo this package will contain all the beans for Entity Classes.

Com.myapp.accessor this package contains interfaces common to both eo and vo packages

Com.myapp.hibernate for hibernate utility classes

Com.myapp.services for the beans which will query database

Com.myapp.client the client programs which will call service functions

Com.myapp.exception will contain all the possible exceptions thrown by our application.

 

Now create database Entity class.

DB Setup:

Create database myapp_db;
Connect myapp_db;

Create a table with following fields:

Create table users values(user_id int(11) auto_increment,
Username varchar(100),
Password varchar(20)),
Status tinyint(1) default 0,
Primary key user_id);

Now for every db table we’ll have 3 files for each:

One in accessor class which is a common interface to both com.myapp.eo and com.myapp.vo classes. The vo class is a simple java bean. We use this bean in eo class in setter and getter methods.

Interface: User.java. Add following interface to com.myapp.accessor package.

package com.myapp.accessor;

public interface User {

public Integer getUserId();

public void setUserId(Integer userId);

public String getUserName();

public void setUserName(String userName);

public String getPassword();

public void setPassword(String password);

public Byte getState();

public void setState(Byte state);

}

File:UserVO.java. Add this to com.myapp.vo package

package com.myapp.vo;

import com. myapp.accessor.User;

public class UserVO implements User{

Integer userId;

String userName;

String password;

Byte state;

public Integer getUserId() {

return userId;

}

public void setUserId(Integer userId) {

this.userId = userId;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public Byte getState() {

return state;

}

public void setState(Byte state) {

this.state = state;

}

}

The UserEO class: Add this to

package com.myapp.eo;

 

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

import javax.persistence.Transient;

import com.jda.server.accessor.User;

import com.jda.server.vo.UserVO;

@Entity

@Table(name=”users”)

public class UserEO implements User{

User user;

@Transient

public User getUser() {

return user;

}

public void setUser(User user) {

this.user = user;

}

public UserEO(){

user = new UserVO();

}

public UserEO(User user){

this.user = user;

}

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name=”user_id”, unique=true, nullable=false, insertable=true, updatable=true)

public Integer getUserId() {

return user.getUserId();

}

public void setUserId(Integer userId) {

user.setUserId(userId);

}

@Column(name=”username”)

public String getUserName() {

return user.getUserName();

}

public void setUserName(String userName) {

user.setUserName(userName);

}

@Column(name=”password”)

public String getPassword() {

return user.getPassword();

}

public void setPassword(String password) {

user.setPassword(password);

}

@Column(name=”state”)

public Byte getState() {

return user.getState();

}

public void setState(Byte state) {

user.setState(state);

}

}

 

Step 4: Configuring Hibernate and creating a hibernate mapping file

I am using mysql DB. Create a file by name hibernate.cfg.xml in the src directory.

<?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=”connection.url”>jdbc:mysql://localhost/myapp_db</property>

<property name=”connection.username”>root</property>

<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>

<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>

<property name=”connection.password”>root</property>

<property name=”transaction.factory_class”>org.hibernate.transaction.JDBCTransactionFactory</property>

<!– thread is the short name for org.hibernate.context.ThreadLocalSessionContext and let Hibernate bind the session automatically to the thread –>

<property name=”current_session_context_class”>thread</property>

<!– this will show us all sql statements –>

<property name=”hibernate.show_sql”>true</property>

<mapping package=”com.myapp.eo”/>

<mapping class=”com.myapp.eo.UserEO”/>

</session-factory>

</hibernate-configuration>

Now in Hibernate for every database operation you will need a hibernate session.

Usually you do this using some code like below:

Now we have entity mapping and we have also configured the db. Now we need hibernate session to

AnnotationConfiguration cfg = new AnnotationConfiguration();

cfg.addAnnotatedClass(Contact.class);

cfg.configure();

SessionFactory sessionFactory = cfg.buildSessionFactory();

session =sessionFactory.openSession();

But it is not practical for the entire bean to open multiple sessions to same db for multiple operations. In a complex application you might have number of tables for which you will have number of beans to update/execute query.  So it’s important to make sure all your application share a single session object.

We can accomplish this using a Singleton design pattern. Create a static session object and initialize it in the static block. This ensures that the session will be open before anyone tries to access session object.  The class can look something like this:

package com.myapp.hibernate;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateSessionUtil {

private static org.hibernate.SessionFactory sessionFactory;

private HibernateSessionUtil() {

}

static{

sessionFactory = new AnnotationConfiguration().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;

}

}

Now we have the utility function ready.

We will also define exceptions which our application might throw. This are the application exceptions, part of business logic. For example in our application if we want to verify a user’s username ans pwd, then if the user is not found , we can throw a UserNotFound exception. If user’s password is not matching we can thorw a UserException with message the password didn’t match. If there is any other (checked) exception the system will wrap it inside a MyAppException and throw it.

Add following classes to the com.myapp.exception package.

package com.myapp.exception;

public class MyAppException extends Exception implements java.io.Serializable{

public MyAppException(String msg) {

super(msg);

}

public MyAppException(String msg, Throwable cause) {

super(msg, cause);

}

}

package com.myapp.exception;

public class UserException extends Exception implements java.io.Serializable{

public UserException(String msg) {

super(msg);

}

public UserException(String msg, Throwable cause) {

super(msg, cause);

}

}

package com.myapp.exception;

public class UserNotFoundException extends Exception implements java.io.Serializable{

public UserNotFoundException(String msg) {

super(msg);

}

public UserNotFoundException(String msg, Throwable cause) {

super(msg, cause);

}

}

Now we need functions for db operations. We do it in the service classess. For each business requirement we can have a service function which will perform the required task and return the results back. An example for user table business actions is shown below. It shows simple select, create and update and delete functions.

Creating the service classes.

package com.myapp.service;

import java.util.Iterator;

import java.util.List;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.Query;

import org.hibernate.Transaction;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import com.myapp.accessor.*;

import com.myapp.eo.*;

import com.myapp.vo.*;

import com.myapp.hibernate.*;

import com.myapp.exception.MyAppException;

import com.myapp.exception.UserException;

import com.myapp.exception.UserNotFoundException;

public class UserService {

public User authenticateUser(User user) throws UserException,UserNotFoundException,MyAppException{

Transaction tx = null;

Session session = HibernateSessionUtil.getInstance().getCurrentSession();

try {

tx = session.beginTransaction();

Query q =  session.createQuery(“select users from UserEO as users where users.userName = :userName”);

q.setParameter(“userName”, user.getUserName());

List users = q.list();

if(users.size() < 1)

throw new UserNotFoundException(“User Not found”);

for (Iterator iter = users.iterator(); iter.hasNext();) {

UserEO element = (UserEO) iter.next();

User userVO = element.getUser();

if(!user.getPassword().equals(userVO.getPassword()))

throw new UserException(“Username and password didnot match”);

else

user = userVO;

}

tx.commit();

} catch (Exception e) {

if (tx != null && tx.isActive()) {

try {

// Second try catch as the rollback could fail as well

tx.rollback();

}    catch (HibernateException e1) {

System.out.println(“Error rolling back transaction”);

}

// throw again the first exception

}

throw new MyAppException(“Exception while fetching user data”,e);

}

return user;

}

public User createUpdateUser(User user) throws MyAppException{

Transaction tx = null;

User userObj = null;

Session session = HibernateSessionUtil.getInstance().getCurrentSession();

try {

UserEO userEO = new UserEO(user);

tx = session.beginTransaction();

userEO = (UserEO)session.merge(userEO);

userObj = userEO.getUser();

tx.commit();

} catch (Exception e) {

if (tx != null && tx.isActive()) {

try {

// Second try catch as the rollback could fail as well

tx.rollback();

} catch (HibernateException e1) {

System.out.println(“Error rolling back transaction”);

}

// throw again the first exception

}

throw new MyAppException(“Exception while saving user data”,e);

}

return userObj;

}

public void deleteUser(User user) throws MyAppException{

Transaction tx = null;

Session session = HibernateSessionUtil.getInstance().getCurrentSession();

try {

UserEO userEO = new UserEO(user);

tx = session.beginTransaction();

session.delete(userEO);

tx.commit();

} catch (RuntimeException e) {

if (tx != null && tx.isActive()) {

try {

// Second try catch as the rollback could fail as well

tx.rollback();

} catch (Exception e1) {

System.out.println(“Error rolling back transaction”);

}

}

throw new MyAppException(“Exception while deleting user data”,e);

}

}

}

The client for this service would be :

package com.myapp.client;

import com.myapp.service.*;

import com.myapp.vo.*;

import com.myapp.accessor.*;

public class UserTest {

public static void main(String[] args) throws Exception{

UserService service = new UserService();

User user = new UserVO();

user.setUserName(“Alex”);

user.setPassword(“XXX”);

try{

User svd = service.authenticateUser(user);

}catch(Exception e){

e.printStackTrace();

}

//create new user

user = new UserVO();

user.setUserName(“Smitha2″);

user.setPassword(“XXX”);

user.setState((byte)1);

User svdUser = null;

try{

svdUser = service.createUpdateUser(user);

}catch(Exception e){

e.printStackTrace();

}

if(svdUser!=null && svdUser.getUserId()!=null){

System.out.println(“svdUser.getUserId() ==>”+svdUser.getUserId());

svdUser.setPassword(“YYY”);

try{

svdUser = service.createUpdateUser(svdUser);

}catch(Exception e){

e.printStackTrace();

}

}

try{

service.deleteUser(svdUser);

}catch(Exception e){

e.printStackTrace();

}

}

}

I hope that this hibernate tutorial would be helpful to you. Please let us know your comments and feedback

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Mixx
  • Google Bookmarks
  • IndianPad
  • Reddit
  1. sunnyside
    July 9th, 2011 at 17:08 | #1

    Where do I get the code for this tutorial to download and practice in my local?

  1. August 18th, 2009 at 13:42 | #1
  2. August 29th, 2009 at 11:10 | #2
  3. October 10th, 2009 at 12:33 | #3
Get Adobe Flash playerPlugin by wpburn.com wordpress themes