JSF 2 + Hibernate 4 Integration Example Using Gradle
January 24, 2015
This page will provide the example of JSF 2 and hibernate 4 Integration. To do this create hibernate utility to get hibernate session. And create Dao to fetch and save data in database. Now call the Dao method in JSF 2 managed bean to use hibernate. In our example, we are using a user form to save in MySQL database with tomcat server.
Software Required to Run Example
To run the example, we need the below software.1. Java 7
2. Eclipse
3. MySQL
4. Tomcat
5. Gradle
Project Structure in Eclipse
Find the project structure in eclipse of demo application.
Create Hibernate Utility using StandardServiceRegistryBuilder
To integrate hibernate and JSF, we have to create a hibernate util. In hibernate 4, we build the session using StandardServiceRegistryBuilder.HibernateUtil.java
package com.concretepage; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory sessionFactory ; static { Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()); sessionFactory = configuration.buildSessionFactory(builder.build()); } public static SessionFactory getSessionFactory() { return sessionFactory; } }
Create Pojo for Table Using Annotation
For the example, we have a user class with some property to save data in MySQL. We are using annotation based POJO.User.java
package com.concretepage; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="user") public class User { @Id @Column(name="id") private int id; @Column(name="name") private String name; @Column(name="age") private Integer age; public User (int id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } 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 Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
Table Structure in MySQL: user
Find the table structure in MYSQL.Table:user
CREATE TABLE `user` ( `id` INT NOT NULL, `name` VARCHAR(50) NULL, `age` INT NULL )
Create DAO to Fetch and Save Data
To save and fetch data from database, we are creating a DAO class.UserDAO.java
package com.concretepage; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; public class UserDAO { Session session = HibernateUtil.getSessionFactory().openSession(); public void save(User user){ session.beginTransaction(); session.save(user); session.getTransaction().commit(); session.close(); } public Integer getId (){ String hql = "select max(user.id) from User user"; Query query = session.createQuery(hql); List<Integer> results = query.list(); Integer userId = 1; if (results.get(0) != null ) { userId = results.get(0) + 1; } return userId; } }
Create Managed Bean
In managed bean, we are creating a method saveUser that will be called after page submit. Inside this method, we will call DAO method to save data.UserBean.java
package com.concretepage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; @ManagedBean(name = "userBean", eager = true) @RequestScoped public class UserBean { private String name; private Integer age; public String saveUser(){ UserDAO userDao = new UserDAO(); Integer userId= userDao.getId(); User user = new User(userId, name, age); userDao.save(user); System.out.println("User successfully saved."); return "output"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
Create XHTML for Input Value
We have a simple XHTML to get input.user.xhtml
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>JSF 2 + Hibernate 4 Integration Example</title> </h:head> <h:body> <h3>JSF 2 + Hibernate 4 Integration Example</h3> <h:form id="userForm"> <h:outputLabel value="User Name:" /> <h:inputText value="#{userBean.name}" /> <br /> <h:outputLabel value="User Age:" /> <h:inputText value="#{userBean.age}"/><br/> <h:commandButton value="Submit" action="#{userBean.saveUser}"/> </h:form> </h:body> </html>
output.xhtml
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>JSF 2 + Hibernate 4 Integration Example</title> </h:head> <h:body> <h3>JSF 2 + Hibernate 4 Integration Example</h3> User successfully saved. </h:body> </html>
hibernate.cfg.xml
Find the hibernate.cfg.xml for MySQL database connection.hibernate.cfg.xml
<!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.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/concretepage</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password"></property> <property name="hibernate.connection.pool_size">10</property> <property name="show_sql">true</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.hbm2ddl.auto">update</property> <mapping class="com.concretepage.User"/> </session-factory> </hibernate-configuration>
web.xml
Find the web.xml for JSF 2.web.xml
<?xml version="1.0" encoding="ISO-8859-1" ?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="3.0"> <display-name>JSF 2 + Hibernate 4 Integration Example</display-name> <servlet> <servlet-name>FacesServlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>FacesServlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>FacesServlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> </web-app>
build.gradle
Find the gradle file to resolve the JAR dependency of hibernate and JSF 2.build.gradle
apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'war' archivesBaseName = 'JSF2Hibernate4' version = '1' repositories { mavenCentral() } dependencies { compile 'com.sun.faces:jsf-api:2.2.9' compile 'com.sun.faces:jsf-impl:2.2.9' compile 'jstl:jstl:1.2' compile 'org.hibernate:hibernate-core:4.3.6.Final' compile 'mysql:mysql-connector-java:5.1.31' }
Output
To test the application, access the URL http://localhost:8080/JSF2Hibernate4-1/user.xhtml and we will get the UI as below.
Hibernate: select max(user0_.id) as col_0_0_ from user user0_ Hibernate: insert into user (age, name, id) values (?, ?, ?) User successfully saved.
