JSF Hibernate Integration (CRUD Example)
Code to integrate JSF with Hibernate and perform Create, Read, Update and Delete operations. This code is tested in Netbeans with MySQL Database.

Creating Project:
1) File –>New Project–>Java –>Web Application and click Next
2)Project name as HiberJSF and Click Next
3) Click Next
4) Choose the JSF and Hibernate framework and select the appropriate Database and click Finish

Structure
Structure

Table Creation

create table student
(
id int primary key,
name varchar(20),
department varchar(20)
)

NewHibernateUtil.java

package pojo;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class NewHibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

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="hibercrud"/>
  <table-filter match-name="student"/>
</hibernate-reverse-engineering>

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="pojo.Student" table="student" catalog="hibercrud" optimistic-lock="version">
        <id name="id" type="int">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <property name="name" type="string">
            <column name="Name" />
        </property>
        <property name="department" type="string">
            <column name="Department" />
        </property>
    </class>
</hibernate-mapping>

Student.java

package pojo;

import Dao.Dao;
import java.util.List;
import javax.faces.bean.ManagedBean;

@ManagedBean
public class Student  implements java.io.Serializable {


     private int id;
     private String name;
     private String department;

    public Student() {
    }

	
    public Student(int id) {
        this.id = id;
    }
    public Student(int id, String name, String department) {
       this.id = id;
       this.name = name;
       this.department = department;
    }
   
    public int getId() {
        return this.id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    public String getDepartment() {
        return this.department;
    }
    
    public void setDepartment(String department) {
        this.department = department;
    }


public void save()
{
    Dao sdao=new Dao();
    sdao.addStudent(this);
}

public void delete()
{    
    Dao sdao=new Dao();
    sdao.deleteStudent(id);
}

public List<Student> getbyid()
{ 
    Dao sdao=new Dao();
    List<Student> stud=sdao.getbyID(id);
    name=stud.get(0).name;
    department=stud.get(0).department;
    return stud;
}

public List<Student> getallrecords()
{
    Dao sdao=new Dao();
    List<Student> stud=sdao.retrieveStudent();
    return stud;
}

public void update()
{
    Dao sdao=new Dao();
    sdao.updateStudent(this);
}

}

Dao.java

package Dao;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.NewHibernateUtil;
import pojo.Student;

public class Dao {
    
    public void addStudent(Student student)
    {
        Transaction trans=null;
        Session session=NewHibernateUtil.getSessionFactory().openSession();
        try 
        {
            trans=session.beginTransaction();
            session.save(student);
            trans.commit();
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
    
    public void deleteStudent(int id)
    {
        Transaction trans=null;
        Session session=NewHibernateUtil.getSessionFactory().openSession();
        try 
        {
            trans=session.beginTransaction();
            Student stud=(Student)session.load(Student.class, new Integer(id));
            session.delete(stud);
            trans.commit();
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
    
    public List<Student> getbyID(int sno)
    {
        Student student=new Student();
        List<Student> student1=new ArrayList();
       
         Transaction trans=null;
        Session session=NewHibernateUtil.getSessionFactory().openSession();
        try 
        {
            trans=session.beginTransaction();
            Query query=session.createQuery("from Student where id= :id");
            query.setInteger("id", sno);
            student=(Student)query.uniqueResult();
            student1=query.list();
            
            trans.commit();
        }
        catch(Exception e)
        {
            
        }
        return student1;
    }
    
    public List<Student> retrieveStudent()
    {
       
        List stud=new ArrayList();
        Student stud1=new Student();
        Transaction trans=null;
        Session session=NewHibernateUtil.getSessionFactory().openSession();
        try
        {
            trans=session.beginTransaction();
            Query query=session.createQuery("from Student");
            stud=query.list();
            stud.add(stud1.getName());
            stud.add(stud1.getDepartment());
           
         
            trans.commit();
            
        }
        catch(Exception e)
        {
            
        }
        return stud;
    }
    
    public void updateStudent(Student student)
    {
        Transaction trans=null;
        Session session=NewHibernateUtil.getSessionFactory().openSession();
        try 
        {
            trans=session.beginTransaction();
            session.update(student);
            trans.commit();
        }
        catch(Exception e)
        {
            
        }
        
    }
    
}

    

index.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
    <h:head>
        <title>CRUD</title>
    </h:head>
    <h:body>
       <h:form>
            <h:panelGrid columns="2">
                Student ID Number: <h:inputText value="#{student.id}"/>
                Student Name: <h:inputText value="#{student.name}"/>
                Student Department: <h:inputText value="#{student.department}"/>
                <h:commandButton value="save student" action="#{student.save}"/>
               
            </h:panelGrid>
       </h:form> <br></br><br></br>
        <h:form>
            <h:panelGrid columns="2">
                Student ID to Delete: <h:inputText value="#{student.id}"/>
                <h:commandButton value="delete student" action="#{student.delete}"/>
            </h:panelGrid>
        </h:form><br></br><br></br>
       
        <h:form>
            <h:panelGrid columns="2">
                Student ID: <h:inputText value="#{student.id}"/>
                <h:commandButton value="Show student" action="#{student.getbyid}"/>
                <h:outputText value="#{student.name}"/>
                <h:outputText value="#{student.department}"/>
            </h:panelGrid><br></br><br></br>
        </h:form>
        
        <h:form>
            <h:panelGrid columns="2">
                Student ID: <h:inputText value="#{student.id}"/><br></br>
                <h:commandButton value="Show student" action="#{student.getbyid}"/><br></br>
                <h:inputText value="#{student.name}"/><br></br>
                <h:inputText value="#{student.department}"/><br></br>
                <h:commandButton value="Update" action="#{student.update}"/>
            </h:panelGrid>
        </h:form>
    </h:body>
</html>

show.xhtml (to display all records)

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
    <h:head>
        <title>Display All</title>
    </h:head>
    <h:body>
        <h:dataTable value="#{student.getallrecords()}" var="s" >
            <h:column>
                <f:facet name="header">ID</f:facet>
                #{s.id}
            </h:column>
        <h:column>                   
              <f:facet name="header">Name</f:facet>               
                #{s.name}
        </h:column>
            <h:column>                   
              <f:facet name="header">Department</f:facet>               
                #{s.department}
        </h:column>
        </h:dataTable>
    </h:body>
</html>

Output:
Save:
save

ID Name Department
1 Alpha Computer Science
21 Seline Models
90 Sean Physics

Delete
delete

ID Name Department
21 Seline Models
90 Sean Physics

Show Record by ID
showid

Update
update

ID Name Department
21 Christy Planner

Show.xhtml

ID Name Department
21 Christy Planner
90 Sean Physics

 NOTE:
Do not forget to Add @ManagedBean in student.java and import – import javax.faces.bean.ManagedBean; (Not javax.annotation.ManagedBean)

 

 

 

 

 

 

 

 

 

By Sri

5 thoughts on “JSF Hibernate Integration (CRUD Example)”
  1. i am follow this all the concept but is not work in my netbeans can u give a exact code for netbeans 8.0.2 version. and my project shows this error
    An Error Occurred:

    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

  2. i’ve been build the project that following same like yours, but when runing the program. i got an error : “/index.xhtml @12,61 value=”#{mhs.nim}”: Target Unreachable, identifier ‘mhs’ resolved to null “. the code “Student ID: “, i replaced and changes like : ” ID: ”

    please resolved this error for me….

    sorry #badEnglish

Leave a Reply

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