JSF – PrimeFaces & Hibernate Integration Project

This article shows how to develop a project by using JSF, PrimeFaces and Hibernate. A sample application is below :

Used Technologies :

JDK 1.6.0_21
Maven 3.0.2
JSF 2.0.3
PrimeFaces 2.2.1
Hibernate 3.6.7
MySQL Java Connector 5.1.17
MySQL 5.5.8
Apache Tomcat 7.0

STEP 1 : CREATE USER TABLE

A new USER Table is created by executing below script:

CREATE TABLE USER (
   id int(11) NOT NULL,
   name varchar(45) NOT NULL,
   surname varchar(45) NOT NULL,
   PRIMARY KEY (`id`)
);

STEP 2 : CREATE MAVEN PROJECT

A maven project is created as below. (It can be created by using Maven or IDE Plug-in).

STEP 3 : LIBRARIES

JSF, Hibernate and the dependencies libraries are added to Maven’ s pom.xml. These libraries will be downloaded by Maven Central Repository.

<!-- JSF library -->
<dependency>
   <groupId>com.sun.faces</groupId>
   <artifactId>jsf-api</artifactId>
   <version>2.0.3</version>
</dependency>
<dependency>
   <groupId>com.sun.faces</groupId>
   <artifactId>jsf-impl</artifactId>
   <version>2.0.3</version>
</dependency>
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
</dependency>
<!-- Hibernate library -->
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>3.6.7.Final</version>
</dependency>
<dependency>
   <groupId>javassist</groupId>
   <artifactId>javassist</artifactId>
   <version>3.12.1.GA</version>
</dependency>
<!-- MySQL Java Connector library -->
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.17</version>
</dependency>
<!-- Log4j library -->
<dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>1.2.16</version>
</dependency>

Note : primefaces-2.2.1.jar can also be downloaded via maven or below link :

<repository>
   <id>prime-repo</id>
   <name>PrimeFaces Maven Repository</name>
   <url>http://repository.primefaces.org</url>
   <layout>default</layout>
</repository>  

<dependency>
   <groupId>org.primefaces</groupId>
   <artifactId>primefaces</artifactId>
   <version>2.2.1</version>
</dependency>

or

http://www.primefaces.org/downloads.html

STEP 4 : CREATE MANAGED BEAN CLASS

A new managed bean class is created. This bean is used that can be associated with UI components. Managed Beans contain property and getter and setter methods. Also, they can cover the methods for event handling, navigation, validation etc.


package com.otv;

import java.io.Serializable;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.otv.hbm.User;
import com.otv.util.HibernateUtil;

/**
 * @author onlinetechvision.com
 * @since 3 Oct 2011
 * @version 1.0.0
 *
 */
public class UserManagedBean implements Serializable{

	private static final long serialVersionUID = 1L;
	private static Logger log = Logger.getLogger(UserManagedBean.class);
	private static final String SUCCESS = "success";
	private static final String ERROR   = "error";
	private String name;
	private String surname;
	private String message;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSurname() {
		return surname;
	}
	public void setSurname(String surname) {
		this.surname = surname;
	}

	public String getMessage() {
		StringBuffer strBuff = new StringBuffer();
		strBuff.append("Name : ").append(this.getName());
		strBuff.append(", Surname : ").append(this.getSurname());
		this.setMessage(strBuff.toString());
		return this.message;
	}

	public void setMessage(String message) {
		this.message = message;
	}	

	public String save() {
		String result = null;
		Session session = HibernateUtil.getSessionFactory().openSession();

		User user = new User();
		user.setName(this.getName());
		user.setSurname(this.getSurname());

		Transaction tx = null;

		try {
			tx = session.beginTransaction();
			session.save(user);
			tx.commit();
			log.debug("New Record : " + user + ", wasCommitted : " + tx.wasCommitted());
			result = SUCCESS;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
				result = ERROR;
				e.printStackTrace();
			}
		} finally {
			session.close();
		}
		return result;
	}

	public List<User> getUsers() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		List<User>  userList = session.createCriteria(User.class).list();
		return userList;
	}

	public void reset() {
		this.setName("");
		this.setSurname("");
	}
}

STEP 5 : CREATE USER CLASS

A new User class is created to model User Table.

package com.otv.hbm;

/**
 * @author onlinetechvision.com
 * @since 3 Oct 2011
 * @version 1.0.0
 *
 */
public class User {

	private int id;
	private String name;
	private String surname;

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSurname() {
		return surname;
	}

	public void setSurname(String surname) {
		this.surname = surname;
	}	

	@Override
	public String toString() {
		StringBuffer strBuff = new StringBuffer();
		strBuff.append("id : ").append(id);
		strBuff.append(", name : ").append(name);
		strBuff.append(", surname : ").append(surname);
		return strBuff.toString();
	}
}

STEP 6 : CREATE HIBERNATEUTIL CLASS

Singleton HibernateUtil class is created to build a Hibernate SessionFactory Object.

package com.otv.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * @author onlinetechvision.com
 * @since 3 Oct 2011
 * @version 1.0.0
 *
 */
public class HibernateUtil {

	private static SessionFactory sessionFactory = null;

	public static SessionFactory getSessionFactory() {
		if(sessionFactory == null) {
			sessionFactory = new Configuration().configure().buildSessionFactory();
		}
		return sessionFactory;
	}

	public static void setSessionFactory(SessionFactory sessionFactory) {
		HibernateUtil.sessionFactory = sessionFactory;
	}

}

STEP 7 : CREATE index.xhtml

index.xhtml is created.

<html xmlns="http://www.w3.org/1999/xhtml"
     xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
     xmlns:p="http://primefaces.prime.com.tr/ui">  

 <h:head><title>Welcome to JSF_PrimeFaces_Hibernate Project</title></h:head>
 <body>
     <h:form>
	     <table>
		     <tr>
		     	<td><h:outputLabel for="name" value="Name:" /></td>
		     	<td><p:inputText id="name" value="#{userMBean.name}"/></td>
		     </tr>
		     <tr>
		     	<td><h:outputLabel for="surname" value="Surname:" /></td>
		     	<td><p:inputText id="surname" value="#{userMBean.surname}"/> </td>
		     </tr>
	         <tr>
		     	<td><p:commandButton id="submit" value="Save" action="#{userMBean.save}" ajax="false"/></td>
		     	<td><p:commandButton id="reset" value="Reset" action="#{userMBean.reset}" ajax="false"/></td>
		     </tr>
	     </table>
     </h:form>
</body>
</html>

STEP 8 : CREATE welcome.xhtml

welcome.xhtml is created.

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.prime.com.tr/ui">

<h:head>
	<title>Welcome to JSF_PrimeFaces_Hibernate Project</title>
</h:head>
<body>
	<h:form>
		<h:outputText value="Saved Record is #{userMBean.message}"></h:outputText>
		<p:dataTable id="users" value="#{userMBean.getUsers()}" var="user" style="width: 10%">
			<p:column>
				<f:facet name="header">
					<h:outputText value="ID" />
				</f:facet>
				<h:outputText value="#{user.id}" />
			</p:column>
			<p:column>
				<f:facet name="header">
					<h:outputText value="Name" />
				</f:facet>
				<h:outputText value="#{user.name}" />
			</p:column>
			<p:column>
				<f:facet name="header">
					<h:outputText value="Surname" />
				</f:facet>
				<h:outputText value="#{user.surname}" />
			</p:column>
		</p:dataTable>
	</h:form>
</body>
</html>

STEP 9 : CREATE error.xhtml

error.xhtml is created.

<html xmlns="http://www.w3.org/1999/xhtml"
     xmlns:h="http://java.sun.com/jsf/html"
     xmlns:f="http://java.sun.com/jsf/core"
     xmlns:p="http://primefaces.prime.com.tr/ui">  

 <h:head><title>Welcome to JSF_PrimeFaces_Hibernate Project</title></h:head>
 <body>
 <f:view>
     <h:form>
         <h:outputText value="Transaction Error has occurred!"></h:outputText>
     </h:form>
 </f:view>
</body>
</html>

STEP 10 : CONFIGURE faces-config.xml

faces-config.xml is created as below. It covers the configuration of both managed beans and navigation between the xhtml pages.

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 

http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"

    version="2.0">

	<managed-bean>
		<managed-bean-name>userMBean</managed-bean-name>
		<managed-bean-class>com.otv.UserManagedBean</managed-bean-class>
		<managed-bean-scope>request</managed-bean-scope>
	</managed-bean>

	<navigation-rule>
	    <from-view-id>/pages/index.xhtml</from-view-id>
	    <navigation-case>
	        <from-outcome>success</from-outcome>
            <to-view-id>/pages/welcome.xhtml</to-view-id>
        </navigation-case>
        <navigation-case>
	        <from-outcome>error</from-outcome>
            <to-view-id>/pages/error.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
</faces-config>

STEP 11 : UPDATE web.xml

web.xml is updated.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID"
	version="2.5">
	  <display-name>OTV_JSF_PrimeFaces_Hibernate</display-name>
	  <context-param>
	    <param-name>javax.faces.PROJECT_STAGE</param-name>
	    <param-value>Development</param-value>
	  </context-param>
	  <welcome-file-list>
	    <welcome-file>/pages/index.xhtml</welcome-file>
	  </welcome-file-list>
	  <servlet>
	    <servlet-name>Faces Servlet</servlet-name>
	    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
	    <load-on-startup>1</load-on-startup>
	  </servlet>
	  <servlet-mapping>
	    <servlet-name>Faces Servlet</servlet-name>
	    <url-pattern>/faces/*</url-pattern>
	  </servlet-mapping>
	  <servlet-mapping>
	    <servlet-name>Faces Servlet</servlet-name>
	    <url-pattern>*.jsf</url-pattern>
	  </servlet-mapping>
	  <servlet-mapping>
	    <servlet-name>Faces Servlet</servlet-name>
	    <url-pattern>*.faces</url-pattern>
	  </servlet-mapping>
	  <servlet-mapping>
	    <servlet-name>Faces Servlet</servlet-name>
	    <url-pattern>*.xhtml</url-pattern>
	  </servlet-mapping>
</web-app>

STEP 12 : CREATE user.hbm.xml

User Table Configuration are set.

<?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="com.otv.hbm.User" table="USER">
   <id name="id" type="int" column="ID" >
   <generator class="increment"/>
  </id>

  <property name="name">
    <column name="NAME" />
  </property>
  <property name="surname">
    <column name="SURNAME"/>
  </property>
 </class>
</hibernate-mapping>

STEP 13 : CREATE hibernate.cfg.xml

hibernate.cfg.xml is created to manage interaction between application and the database:

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

<hibernate-configuration>
<session-factory>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/Test</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password">root</property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <!-- Mapping files -->
  <mapping resource="hbm/user.hbm.xml"/>
</session-factory>
</hibernate-configuration>

STEP 14 : DEPLOY PROJECT TO APPLICATION SERVER

When Project is deployed to Application Server(Apache tomcat), the screen will be seen as below :

After submit button is clicked, welcome.xhtml page will be seen as below :

STEP 15 : DOWNLOAD

OTV_JSF_Hibernate_PrimeFaces

  • Facebook
  • Twitter
  • Reddit
  • LinkedIn
  • DZone
  • Add to favorites
  • Email
  • RSS
  • Delicious
  • Live