Welcome to the Spring Primefaces and Hibernate Integration example. Integration between frameworks is a complex mission and mostly it needs a lot of time to achieve. We’ve discussed a Primefaces, Spring and Hibernate frameworks in a separate tutorials, but this time we will show you how can integrate all of them to create a layered (tiered) application.

Spring Primefaces Hibernate

Layered (tiered) application is a popular design that most of the enterprise applications are aligned with. In which:

  1. Primefaces framework will be used for handling all UI concerns and verify client’s inputs.
  2. Hibernate framework will be used for communicating your own persistence store that probably is a MySQL database.
  3. Spring framework will be used to glue between all of these frameworks.

This tutorial intended for implementing a layered application using all of these listed frameworks.

Spring Primefaces Hibernate Required Tools

Before getting started delve into, let’s see the required tools that you would need for:

  • Eclipse Kepler 4.3.
  • Hibernate 3.x.
  • Spring 4.x.
  • Primefaces 5.x.
  • JDK 1.6+.
  • MySQL 5.x.

Primefaces Spring Hibernate Project Structure

Our final project structure will look like below image, we will go through each of the components one by one.

Database-Tables-Create-Employee-Table (1)

Create Database Employee Table

MySQL database would be used for retaining all of employees instances/records. Used Employee Table looks like below:

Also, find below its SQL create-script:

Create Employee Model Bean

After we created an Employee Table, it’s a proper time to get a look at how Employee class would look like:

Spring Primefaces Hibernate Maven Dependencies

Maven is a build tool, it’s used mainly for managing project dependencies. So no need for downloading JARs and appending them into your project as you did normally. MySQL JDBC driver, hibernate core, Spring core framework, Primefaces and many libraries that we need for Spring Hibernate Primefaces integration. Our final pom.xml file looks like below.

Spring Primefaces – Hibernate Configuration

Hibernate is a standard Object Relational Mapping (ORM) solution, it’s used for mapping your object domain into relational tabular formula. Hibernate configuration process require below steps:

  • Specify all relevant database information like driver, JDBC URL, hibernate dialect and hibernate session context in a hibernate configuration file, mainly using hibernate.cfg.xml. Dialect will be used by hibernate implementation itself for make sure the execution of mapping process is done effectively. This file should be located under project’s src/main/resources folder.
  • Specify hibernate’s mapping file. Mapping file will contains all of mapping information, like objects-tables, attributes-columns and associations-relations, domain-classes.hbm.xml file is mainly used for this purpose. This file should be located under project’s src/main/resources folder so that it’s in the classpath of the application.
  • It’s important to say that some of modifications would be required when we’re going to use Spring.

hibernate.cfg.xml

domain-classes.hbm.xml

Test our Hibernate Application

Till now, we’ve created an Eclipse Web project configured with required dependencies, created database Employee Table and created hibernate framework accompanies.

Before going far away with Spring integration and developing a Primefaces UI form, let’s see how can we use a simple Java Application for getting Employee instance saved against our own database. Given Java Application would help us identifying the benefits we’ll get especially when it comes to use a Spring framework later on.

Test-Applicaiton-Insert-Employee

Here’s detailed clarifications for the above code:

  • Hibernate requires a defined context for make your acquired session affected. Standard Java Application context can be achieved by providing hibernate’s attribute hibernate.current_session_context_class. Value of org.hibernate.context.internal.ThreadLocalSessionContext will be binded the context to the current executed thread. That’s mean, if you’ve invoked any type of CRUD operations against session object within an active Transaction, they will be executing into your own database once the Transaction has committed. In our case, an new employee instance has been saved. If you’ve used hibernate 3, this property should be thread instead of using ThreadLocalSessionContext.
  • Hibernate 4 is used for Testing purpose, this version of hibernate isn’t applicable when it comes to integrate with Spring 4. To integrate with Spring 4, you’ve requested to use Hibernate 3.
  • Using of latest version of hibernate requires you to use StandardServiceRegistryBuilder to build SessionFactory.

Setting Up Spring

Spring is a comprehensive framework, it’s used mainly for Inversion of Control (IoC) which consider the more general category of the well-known concept Dependency Injection.

However, a provided simple Java Application keep you capable of getting your Employee instances saved against your own database, but typically, this isn’t the way that most of applications use to configure their own hibernate persistence layer.

Using of Spring will help you avoiding all creating and associating objects stuffs. Creating required objects, associating others are mainly a Spring job. Following are Spring context configuration file, updated hibernate configuration, updated Maven pom.xml and our deployment descriptor file. Let’s see how can we configure all of these to make a proper use of Spring.

applicationContext.xml

hibernate.cfg.xml

web.xml

Here’s detailed explanation for the code given above:

  • We’ve created a SessionFactory by instantiating a Spring Bean called sessionFactory. Instantiating of SessionFactory does require passing an instant of data source instance, passing mapping files (domain-classes.hbm.xml as is), passing all required Hibernate properties via using of hibernate.cfg.xml. As you’ve noticed, hibernate.cfg.xml doesn’t contain database information, cause it’s defined instantly – Data Source Bean – and no need for hibernate session context, cause it’s enriched by Apache Tomcat. Even Apache Tomact isn’t a managed server, but it contains facilities that make help create a contextual session.
  • Transaction Manager will help you eliminate using a snippet of code like session.getTransaction().begin() and commit(). @Transactional annotation will be used alternatively. That’s mean, executing of any Spring Service’s methods annotated with @Transactional will be done in a Transnational manner. In case you’ve called a CRUD operation against your session within a Transnational scope like session.save(), it will be executing directly into your own database at the end of called method. That’s called Transaction Demarcation.
  • You can define your own Spring Services by using @Component. That will be scanned automatically.
  • A new libraries are added into our pom.xml maven dependencies file, common-dbcp and javassist  are required by hibernate 3. If you’ve noticed, these libraries aren’t required for Hibernate 4.
  • It’s mandatory to add Spring context loader listener for your web.xml file. This listener required an applicationContext.xml to be defined underneath of WEB-INF/ folder. This is the default location and name for Spring configuration context file. In case you would to change its location and name you must add below snippet of code provided with required path.

Configure non-default Spring Context Location:

NOTE: If you are looking for Spring 4 and Hibernate 4 integration, we need to make some small changes in the Spring Bean configuration file, you can get more details about that at Spring Hibernate Integration Example.

Spring EmployeeService

In a layered application like what we’re doing here, all of business operations must be achieved by services. Spring provides you ability to define your own services that would contain your own business rules. EmployeeService would contain the required business for create an Employee.

Here’s detailed explanation for the above code:

  • EmployeeService is a Spring service, @Component annotation is used for defining Spring Service. By default, Spring will scan your mentioned package(s) for locating your service based on context:component-scanTag.
  • @Autowired will help you get required instances injected. That’s Dependency Injection or IoC (Inversion of Control) concept. It’s important concept, it means that instead of allowing the developer controlling the process of creating instances and making required associations as well. It makes all of these creation and association in behind seen. That is an incredible power of Spring. @Autowired is used for injecting one instance of SessionFactory, if you’re worry about performance issue, you can define your SessionFactory bean as a singleton scope. For complete information about autowiring, read Spring autowiring example.
  • @Transactional annotation is used for Transaction Demarcation purpose. Transaction demarcation is used for associating your contextual session with an active Transaction. That will cause a CRUD operation to get executed against your own database. You should go through Spring Declarative Transaction Management Example.

Primefaces Managed Bean – RegisterEmployee

Managed Bean is a JSF facility, and it’s used for handling all required User Interface validations. In a layered application, Managed Bean is used for invoking Business services. You may be wondering once you know that it’s applicable for you to inject EmployeeService Spring bean into your own Managed Bean. That becomes true if you’re used @ManagedProperty annotation.

faces-config.xml

Here’s detailed explanation for the above code:

  • RegisterEmployee Managed Bean is developed with using of @ManagedProperty annotation that will help you get a Spring EmployeeService instance injected. That association won’t be applicable if you don’t provide a special faces-config.xml file that contains a newly added Spring’s el-resolver.
  • Primefaces UI form will help you gather all required information about registered employee.
  • Register action will ask EmployeeService saving given employee instance.

Primefaces – Register Form

index.xhtml

Primefaces-Register-Form-Employee-Registered

Spring Primefaces Hibernate Example Summary

Hibernate integration with Spring and Primefaces is a popular development task. This tutorial guides you thoroughly to get Hibernate integrated with Spring and Primefaces that would lead you into getting an employee persisted against your database. Some technical details are mentioned intentionally. Contribute us by commenting below and find the source code for downloading purpose.

By admin

Leave a Reply

%d bloggers like this: