PrimeFaces + EclipseLink / JPA + MongoDB Integration

This tutorial explains the PrimeFaces + JPA + MongoDD integration. We are going to create a Pie Chart application using the PrimeFaces component library with the additional software JPA and MongoDB for the persistence mechanism. Before writing any snippet of code, you should have a proper installation and configuration for both the database (MongoDB) and the EclipseLink JPA/NOSQL persistence layer.

Tutorial Tools

  • Mongo Database 2.6
  • Eclipselink JPA/NOSQL 2.5.0
  • PrimeFaces 4.0
  • Apache Tomcat Server 7.0.35
  • Windows 7

MongoDB Installation & Configuration

In our previous article, we have explained How To Install MongoDB on Windows. If you have not installed MongoDB, please follow that article and setup the MongoDB in your system

See the below figures that shows you a proper running MongoDB and an open connection using the command line.

Running Mongo

  • The above figure shows you the result in of executing mongod.exe command.

Connect Mongo

  • The above screen shows you the result of executing monog.exe command.

Maven has provided the library for connecting the MONGODB by adding the following dependency. Add the maven for Mongo Java Driver dependency.

Maven For Mongo Database Java Driver

	<dependency>
		<groupId>org.mongodb</groupId>
		<artifactId>mongo-java-driver</artifactId>
		<version>2.11.4</version>
	</dependency>

EclipseLink JPA/NOSQL Installation & Configuration

We have discussed before EclipseLink library that responsible for connecting upon Relational Database at the EclipseLink – JPA Tutorial. But for connecting a non-relational databases such MongoDB – Document Based – you have to consider the EclipseLink JPA/NOSQL library.

The installation and configuration of that library needs Maven configurations, so It is worth for you to have a look at the EclipseLink – JPA Tutorial that mentioned above for seeing the way that how could maven being used for that purpose. The following coming few lines assumes that you are aware about installing and configuring the EclipseLink using maven.

For installing and configuring the EclipseLink – JPA/NOSQL you have to follow the below steps:

  • Add the required entries for EclipseLink – JPA/NOSQL maven repositories and dependencies.
  • Create your business domain (Classes).
  • Type the persistence.xml with the required domain classes and properties for the database being connected.

Maven EclipseLink – JPA/NoSQL Repositories

<repositories>
  <repository>
	<id>oss.sonatype.org</id>
	<name>OSS Sonatype Staging</name>
	<url>https://oss.sonatype.org/content/groups/staging</url>
  </repository>
  <repository>
	<id>EclipseLink</id>
	<url>http://download.eclipse.org/rt/eclipselink/maven.repo</url>
  </repository>
</repositories>

Maven Eclipselink – JPA/NoSQL Dependencies

   <dependency>
	<groupId>org.eclipse.persistence</groupId>
	<artifactId>eclipselink</artifactId>
	<version>2.5.0-RC1</version>
		<exclusions>
			<exclusion>
				<groupId>org.eclipse.persistence</groupId>
				<artifactId>commonj.sdo</artifactId>
			</exclusion>
		</exclusions>
	</dependency>
	<dependency>
		<groupId>org.eclipse.persistence</groupId>
		<artifactId>org.eclipse.persistence.nosql</artifactId>
		<version>2.4.2-SNAPSHOT</version>
	</dependency>

Business Domain

For being this tutorial have a high intensity of concepts and snippet of codes, we’ve introduced a simple business domain for good understanding. The suggested domain contains of two classes, User and Address represent the domain where the User class has an association for Address.
User.java

package net.javabeat.eclipselink.persistence.data;

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.eclipse.persistence.nosql.annotations.DataFormatType;
import org.eclipse.persistence.nosql.annotations.Field;
import org.eclipse.persistence.nosql.annotations.NoSql;

@Entity
@NoSql(dataFormat=DataFormatType.MAPPED)
public class User {
	@Id
	@GeneratedValue
	@Field(name="_id")
	private String id;
	@Field(name="USERID")
	private String userId;
	@Field(name="fullName")
	private String fullName;
	@Field(name="AGE")
	private String age;
	@Field(name="STATUS")
	private String status;
	@Embedded
	private Address address = new Address();

	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getFullName() {
		return fullName;
	}
	public void setFullName(String fullName) {
		this.fullName = fullName;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
}

Address.java

package net.javabeat.eclipselink.persistence.data;

import javax.persistence.Embeddable;

import org.eclipse.persistence.nosql.annotations.DataFormatType;
import org.eclipse.persistence.nosql.annotations.Field;
import org.eclipse.persistence.nosql.annotations.NoSql;

@Embeddable
@NoSql(dataFormat=DataFormatType.MAPPED)
public class Address {
	@Field(name="addressId")
	private String addressId = "";
	@Field(name="addressValue")
	private String addressValue = "";

	public String getAddressId() {
		return addressId;
	}
	public void setAddressId(String addressId) {
		this.addressId = addressId;
	}
	public String getAddressValue() {
		return addressValue;
	}
	public void setAddressValue(String addressValue) {
		this.addressValue = addressValue;
	}
}
  • Note that we are using @NoSql annotation
  • Instead of @Column for binding a field with a column in a relational database, the @Field has been used
  • @Embedded is a persist strategy that used for embed document within the body of other document

PrimeFaces Pie Chart Component

Representation of data is one of the most challenges with JSF implementation vendor. Charts is one of the primary components that have been coming with the PrimeFaces distribution, one of them is the Pie chart. Pie chart displays category-data in a pie graphic.

Here is the PieChart tag information and attributes defined with the PieChart.

PieChart General Info

Pie Attributes

The View

index.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
	<h:head>
		<script name="jquery/jquery.js" library="primefaces"></script>
	</h:head>
	<f:view>
		<h:form prependId="false">
			<h1>JavaBeat Primefaces Example</h1>
			<h2>Primefaces - DataTable - User Registration </h2>
			<h:panelGrid columns="2">
				<h:outputText value="Enter Full Name:"/>
				<p:inputText value="#{registerationBean.user.fullName}"/>
				<h:outputText value="Enter Age:"/>
				<p:inputText value="#{registerationBean.user.age}"/>
				<h:outputText value="Enter Status [Example A, B, C or D]:"/>
				<p:inputText value="#{registerationBean.user.status}"/>
				<h:outputText value="Enter Address"/>
				<p:inputText value="#{registerationBean.user.address.addressValue}"/>
			</h:panelGrid>
			<h:panelGrid columns="1">
				<p:pieChart value="#{registerationBean.model}" legendPosition="w"></p:pieChart>
			</h:panelGrid>
			<h:commandButton value="Save User" action="#{registerationBean.saveUser}"/>
			<br/>

		</h:form>
	</f:view>
</html>

Managed Bean

RegistrationBean.java

package net.javabeat.primefaces.presenation;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import net.javabeat.eclipselink.persistence.data.User;

import org.primefaces.component.chart.pie.PieChart;
import org.primefaces.model.chart.PieChartModel;

@ManagedBean
@SessionScoped
public class RegisterationBean {
	static EntityManagerFactory factory = null;
	static EntityManager em = null;

	static {
		factory = Persistence.createEntityManagerFactory("mongoPU");
		em = factory.createEntityManager();
	}

	private User user = new User();
	private PieChartModel model = new PieChartModel();

	int aCounter = 0;
	int bCounter = 0;
	int cCounter = 0;
	int dCounter = 0;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@SuppressWarnings("unchecked")
	public PieChartModel getModel() {

		// At each rendering of data, a query has made upon mongo data.
		Query query = em.createQuery("SELECT u FROM User u");
		// Fetch the all users
		List<User> users = query.getResultList();
		// Categorize Users
		for(User u : users){
			if(u.getStatus().equals("A")){
				aCounter++;
			}
			if(u.getStatus().equals("B")){
				bCounter++;
			}
			if(u.getStatus().equals("C")){
				cCounter++;
			}
			if(u.getStatus().equals("D")){
				dCounter++;
			}
		}
		this.model = new PieChartModel();
		// Fill the model
		model.set("A", aCounter);
		model.set("B", bCounter);
		model.set("C", cCounter);
		model.set("D", dCounter);
		return model;
	}

	public void setModel(PieChartModel model) {
		this.model = model;
	}

	public String saveUser(){
		em.getTransaction().begin();
		em.persist(user);
		em.getTransaction().commit();
		this.user = new User();
		return "";
	}
}

Persistence Context

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
				xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
				xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
	<persistence-unit name="mongoPU" transaction-type="RESOURCE_LOCAL">
		<class>net.javabeat.eclipselink.persistence.data.User</class>
		<class>net.javabeat.eclipselink.persistence.data.Address</class>
		<properties>
   			<property name="eclipselink.target-database" value="org.eclipse.persistence.nosql.adapters.mongo.MongoPlatform"/>
            <property name="eclipselink.nosql.connection-spec" value="org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec"/>
            <property name="eclipselink.nosql.property.mongo.port" value="27017"/>
            <property name="eclipselink.nosql.property.mongo.host" value="localhost"/>
            <property name="eclipselink.nosql.property.mongo.db" value="JavaBeat"/>
            <property name="eclipselink.logging.level" value="FINEST"/>
		</properties>
	</persistence-unit>
</persistence>

Primefaces + EclipseLink JPA / NOSQL + MongoDB Integration

The below snapshots show you the using of MongoDB for storing the users and retrieving them again for drawing the Pie Chart. Pie Chart is categorized based on the status that has the value among of set A, B, C and D.

At the same time, a find query db.USER.find() has been executed to ensure that the Pie Chart has executed a correct query into USER collections.

Pie Chart Used In Registration Form

  • Save user has invoked the saveUser method, that’s in turn the saving is being proceed.
  • GetModel will reset the Pie model for next coming filling.

Mongo Records

  • When the database is connected via mongo.exe, the user has the ability to inquiry the database.
  • The db implicit object represnts the connected database, which has the value of JavaBeat.
  • By using the command db.USER.find(), the user has the ability to see all of the registered users.

Comments

comments

About Amr Mohammed

Speak Your Mind

*