Simple CRUD Using JSF2+Hibernate Integration and MySQL

This example shows how to develop a simple CRUD (Create Read Update Delete) by using JSF2, Hibernate and MySQL.
This application lets you manage customer database such as add new customer and update/delete customer info.

These two frameworks can be used for different purposes according to the usefulness and power of individual frameworks.

-JSF can be used to implement presentation layer.
-Hibernate can be used in the business logic tier to manage business objects, resource management.

First, lets create the database and table for customer.

CREATE DATABASE IF NOT EXISTS jsfhibercrud;
USE jsfhibercrud;
--
-- Definition of table `customer`
--
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer` (
  `cust_id` int(10) unsigned NOT NULL auto_increment,
  `first_name` varchar(45) NOT NULL,
  `last_name` varchar(45) NOT NULL,
  `email` varchar(45) NOT NULL,
  `dob` date NOT NULL,
  PRIMARY KEY  (`cust_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now create a netbean project using hibernate and jsf framework. While creating project choose or connect to your created database.

NetBeans Project Structure:
jsf-hiber-crud-project-structure

hibernate.cfg.xml

<?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/jsfhibercrud</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">pass</property>
    <mapping resource="com/javaknowledge/entity/Customer.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

After that add three packages named com.javaknowledge.entity, com.javaknowledge.util and com.javaknowledge.dao.
Now generate POJOs using reverse engineering at your entity package.
hibernate.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="jsfhibercrud"/>
  <table-filter match-name="customer"/>
</hibernate-reverse-engineering>

Customer.java

package com.javaknowledge.entity;
import com.javaknowledge.dao.CustomerDao;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

/**
 * @author javaknowledge
 */
@ManagedBean
@SessionScoped
public class Customer implements java.io.Serializable {

    private Integer custId;
    private String firstName;
    private String lastName;
    private String email;
    private Date dob;
    private String sd, msg, selectedname;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public Customer() {
    }

    public Customer(String firstName, String lastName, String email, Date dob) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.dob = dob;
    }

    public String getSd() {
        return sd;
    }

    public void setSd(String sd) {
        this.sd = sd;
    }

    public Integer getCustId() {
        return this.custId;
    }

    public void setCustId(Integer custId) {
        this.custId = custId;
    }

    public String getFirstName() {
        return this.firstName;
    }

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

    public String getLastName() {
        return this.lastName;
    }

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

    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getDob() {
        return this.dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getSelectedname() {
        return selectedname;
    }

    public void setSelectedname(String selectedname) {
        this.selectedname = selectedname;
    }

    public void saveCustomer() {
        try {
            Date d = sdf.parse(sd);
            System.out.println(d);
            this.dob = d;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        CustomerDao dao = new CustomerDao();
        dao.addCustomer(this);
        this.msg = "Member Info Saved Successfull!";
        clearAll();
    }
    public void updateCustomer() {
        try {
            Date d = sdf.parse(sd);
            System.out.println(d);
            this.dob = d;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        CustomerDao dao = new CustomerDao();
        dao.updateCustomer(this);
        this.msg = "Member Info Update Successfull!";
        clearAll();
    }
    public void deleteCustomer() {
        CustomerDao dao = new CustomerDao();
        dao.deleteCustomer(custId);
        this.msg = "Member Info Delete Successfull!";
        clearAll();
    }

    public List<Customer> getAllCustomers() {
        List<Customer> users = new ArrayList<Customer>();
        CustomerDao dao = new CustomerDao();
        users = dao.getAllCustomers();
        return users;
    }

    public void fullInfo() {
        CustomerDao dao = new CustomerDao();
        List<Customer> lc = dao.getCustomerById(selectedname);
        System.out.println(lc.get(0).firstName);
        this.custId = lc.get(0).custId;
        this.firstName = lc.get(0).firstName;
        this.lastName = lc.get(0).lastName;
        this.email = lc.get(0).email;
        this.dob = lc.get(0).dob;
        this.sd = sdf.format(dob);
    }

    private void clearAll() {
        this.firstName = "";
        this.lastName = "";
        this.sd = "";
        this.email = "";
        this.custId=0;
    }
}

Customer.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jul 5, 2013 10:57:32 AM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
    <class name="com.javaknowledge.entity.Customer" table="customer" catalog="jsfhibercrud">
        <id name="custId" type="java.lang.Integer">
            <column name="cust_id" />
            <generator class="identity" />
        </id>
        <property name="firstName" type="string">
            <column name="first_name" length="45" not-null="true" />
        </property>
        <property name="lastName" type="string">
            <column name="last_name" length="45" not-null="true" />
        </property>
        <property name="email" type="string">
            <column name="email" length="45" not-null="true" />
        </property>
        <property name="dob" type="date">
            <column name="dob" length="10" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

In util package add a HibernateUtil.java file and change this as follows-
HibernateUtil.java

package com.javaknowledge.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil {
 
    private static final SessionFactory sessionFactory=buildSessionFactory();
 
   public static SessionFactory buildSessionFactory(){
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

This class will read the configuration in our hibernate.cfg.xml file which handles the database connection to our MySQL server.

Next, create a new class in com.javaknowledge.dao package, name it CustomerDao.java. DAO stands for Data Access Object. It contains the logic for database operation.
CustomerDao.java

package com.javaknowledge.dao;

import com.javaknowledge.entity.Customer;
import com.javaknowledge.util.HibernateUtil;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author javaknowledge
 */
public class CustomerDao {

    public void addCustomer(Customer cust) {
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            session.save(cust);
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (trns != null) {
                trns.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
    }

    public void deleteCustomer(int custid) {
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            Customer cust = (Customer) session.load(Customer.class, new Integer(custid));
            session.delete(cust);
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (trns != null) {
                trns.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
    }

    public void updateCustomer(Customer cust) {
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            session.update(cust);
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (trns != null) {
                trns.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
    }

    public List<Customer> getAllCustomers() {
        List<Customer> users = new ArrayList<Customer>();
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            users = session.createQuery("select concat(first_name, ' ', last_name) as name from Customer").list();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return users;
    }

    public List<Customer> getCustomerById(String custid) {
        System.out.println(custid);
//        Customer cust = null;
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            String queryString = "from Customer where concat(first_name, ' ', last_name) = :id";
            Query query = session.createQuery(queryString);
            query.setString("id", custid);
            //cust = (Customer) query.uniqueResult();
            List<Customer> list = query.list();
            if (list.size() > 0) {
                return list;
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return null;
    }
}

Finally create the view page using jsf2.

index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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:ui="http://java.sun.com/jsf/facelets">
    <h:head>
        <title>JSF Hibernate CRUD Example</title>
        <style>
            tfoot{
                text-align: center;
            }
            thead{
                background-color: magenta;
                color: white;
            }
            td{
                font-weight: bold;
            }
            .msg{
                font-size: small;
                color: blue;
            }
        </style>
    </h:head>
    <h:body>
        <h:form>
            <h:panelGrid id="panel1" columns="2" border="1" 
                         cellpadding="5" cellspacing="1">
                <f:facet name="header">
                    <h:outputText value="Add Customer Information"/>
                </f:facet>
                <h:outputLabel value="First Namer:"/>
                <h:inputText value="#{customer.firstName}" id="fn"/>
                <h:outputLabel value="Last Name:"/>
                <h:inputText value="#{customer.lastName}" id="ln"/>
                <h:outputLabel value="Email:"/>
                <h:inputText value="#{customer.email}" id="eml"/>
                <h:outputLabel value="Date of Birth:"/>
                <h:inputText value="#{customer.sd}" id="s"/>
                <f:facet name="footer">
                    <h:outputLabel value="#{customer.msg}" id="msg" styleClass="msg"/>
                    <h:commandButton value="Save" action="#{customer.saveCustomer}">
                    <f:ajax render="fn ln eml s msg" execute="@form"/>
                        </h:commandButton>
                </f:facet>
            </h:panelGrid>
            
        </h:form>
        
        <h:form>
                <h:panelGrid id="panel2" columns="2" border="1" 
                             cellpadding="5" cellspacing="1">
                    <f:facet name="header">
                        <h:outputText value="Update/Delete Customer Info"/>
                    </f:facet>
                    <h:outputLabel value="Select Customer:"/>
                    <h:selectOneMenu value="#{customer.selectedname}" id="ulist">
                        <f:selectItems value="#{customer.allCustomers}"/>
                        <f:ajax event="change" render="cid fname lname email sd" listener="#{customer.fullInfo}"/>
                    </h:selectOneMenu>
                      <h:outputLabel value="Customer ID:"/>
                      <h:inputText value="#{customer.custId}" id="cid" readonly="true"/>
                    <h:outputLabel value="First Name:"/>
                    <h:inputText value="#{customer.firstName}" id="fname"/>
                    <h:outputLabel value="Last Name:"/>
                    <h:inputText value="#{customer.lastName}" id="lname"/>
                    <h:outputLabel value="Email:"/>
                    <h:inputText value="#{customer.email}" id="email"/>
                    <h:outputLabel value="Date of Birth:"/>
                    <h:inputText value="#{customer.sd}" id="sd"/> 
                    <f:facet name="footer">
                        <h:outputLabel value="#{customer.msg}" id="msg2" styleClass="msg"/>
                        <h:commandButton value="Update Info" action="#{customer.updateCustomer}">
                            <f:ajax render="ulist cid fname lname email sd msg2" execute="@form"/>
                        </h:commandButton>
                        <h:commandButton value="Delete Info" action="#{customer.deleteCustomer}">
                            <f:ajax render="ulist cid fname lname email sd msg2" execute="@form"/>
                        </h:commandButton>
                    </f:facet>
                </h:panelGrid>
            </h:form>
    </h:body>
</html>

Screenshot:
jsf-hiber-crud

 

admin

Hello! I am Md. Abdul Bari; founder and admin of javaknowledge; currently providing training as a J2EE faculty in The Computers Ltd. Dhaka, Bangladesh under an IT Scholarship project provided by IDB-BISEW. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

More Posts - Website

Follow Me:
TwitterFacebookGoogle Plus

91,760` Total Views

14 comments

  • Thank you sir, This tuts is very helpful.

  • keep the good work

  • Hi,
    Thanks for the tutorial. It’s great.
    How can I download the source?
    I can’t do it because it’s necessary to log into the blog.

    Thanks in advance.

  • Hello, I’ve got 5 errors in the hibernate.cfg.xml file. These 5 errors are located at the 5 properties about the configuration of the database. Specifically, for example in the first property (org.hibernate.dialect.MySQLDialect) the error says: expected, got org.
    Can you help how to solve this matter?
    Thank you very much.

  • what version of Netbeans and the libraries and jars will this work on?

  • Hi did you missed the faces-config.xml here?

  • I got error

    javax.el.ELException: Error reading ‘allCustomers’ on type entity.Customer

    viewId=/index.xhtml
    location=C:\hibernateWorkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\JSFHiberCrud\index.xhtml
    phaseId=RENDER_RESPONSE(6)

    Caused by:
    java.lang.ClassNotFoundException – org.hibernate.cfg.Configuration
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)

    /index.xhtml at line 59 and column 74 value=”#{customer.allCustomers}”

    Where is error?

    http://twitter.com/java_knowledge

  • Hello
    I like this example that you explained.But I am trying to use Hibernate with jsf 2.0 using oracle as the database. The hibernate will work if I take a normal java application But does show a lot of errors when I try to integrate to make it a fully functionaly web application
    Please shows how to configure hibernate for a web application

  • excelent work!!! your implementation is clean and let me understand how work JSF.

  • Thanks, It is a great help for me who is trying to learn this language.

  • Saadmaan Mahmid Shoshi

    Sir, whenever I try to run the application, I get an error: “Deployment error: Starting of Tomcat failed.” But I have started the Apache Tomcat Server in my Netbeans from Window->Services->Servers. My Netbeans Version is 8.0.2; Apache Tomcat Version installed within this IDE is 8.0.15.0.

  • Great article! You could also take a look at this maven archetype which creates JSF/Spring crud app with custom components: https://github.com/ignl/happyfacescrud

Leave a Reply

Your email address will not be published. Required fields are marked *


− two = 4