JSF App slow with JPA connection

If you are working on Java Persistence API JPA on tomcat or any other web server this would be happening if you have multiple threads going off for connections.

The rule of thumb shall be to have one EntityManagerFactory and get EntityManagers out of it. Hence we would have one factory but multiple products that would take care of closing and managing them selves.

What are the signs:

1. Do you instantiate Persistence.createEntityManagerFactory(“name”) from multiple places?
2. What do you see on Process when you run

ps -aux | grep tomcat

Do you see multiple instances

If either or both of the above have yes, then here is the solution.

The first thing have single instance of ManagerFactory

package com.enderase.persistence;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

* Singlton implementation for EntityManagerFactory
* @author Kaleb Woldearegay<kaleb@gullele.com>
public class HibernateUtil {
private static final EntityManagerFactory entityManagerFactory;

static {
try {
entityManagerFactory = Persistence.createEntityManagerFactory("jpa");
} catch (Throwable exception) {
//log your error here
throw new ExceptionInInitializerError(exception);

public static EntityManagerFactory getEntityManager() {
return entityManagerFactory;

Then make sure you are taking care of the instances of the EntityManagers that are created from the factory using

EntityManagerFactory entityManagerFactory = HibernateUtil.getEntityManager();
EntityManager em = entityManagerFactory.createEntityManager();

Make sure to close them appropriately after using them

This should pretty much take care of the problem


Accessing one bean in another without using annotation

I would say we have to use annotations and Injection to get the bean inside another bean.
But in case you are interested to get it without using annotation you can use the following in the action/actionListener

TheBean theBean = (TheBean)FacesContext.getCurrentInstance() .getExternalContext().getRequestMap().get("theBean");

Where theBean is one we are interested to get it from being in the other bean.

That is it!

Adding session bean to to requested bean using annotation JSF

One major part on JSF would separation of concerns even for beans. As a rule of thumb beans related to model are session beans and those which have actions to be taken care of are requested one.

So, In this particular scenario we would have two beans. Basically we don’t want to include any logic inside the session bean, rather we would add session bean as a member variable to request bean.

Lets take a simple registration process.

The requested bean which will be responsible for actions would look like

package com.enderase.beans;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

import com.enderase.model.Contractor;

public class ActionListeners implements Serializable{
	private Contractor contractor;
	public void setContractor(Contractor contractor){
		this.contractor = contractor;
	public Contractor getContractor() {
		return this.contractor;
	private static final long serialVersionUID = 1L;
	 * Action handler for Contractor save.
	 * @return String, next
	public String registerContractor() {
		Contractor contractor = this.contractor;
		if (contractor != null) {
			try {
				FileWriter fileWriter = new FileWriter("/tmp/name.note");
				BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
				bufferedWriter.write("Name "+contractor.getName()+" Email "+contractor.getEmail()
			} catch (Exception ex) {
				//log the exception here
		return "navigated";

So the key thing here would be the @ManagedProperty part.
That would inject the session bean into the request bean without creating any instance of it.

*Don’t for get to add getter and setter for the session bean you are adding otherwise you would get an error.

The session bean would be a simple holder of model

package com.enderase.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.enderase.model.Contractor;

public class ContractorBean {
	private Contractor contractor;
	public ContractorBean() {
		this.contractor = new Contractor();
	public Contractor getContractor(){
		return this.contractor;
	public void setContractor(Contractor contractor){
		this.contractor = contractor;

Where the contractor would be a simple POJO file

Mass/Multiple file upload in Java ServerFaces JSF

Without knowing if it is the best approach or not, I will post how I solved the multiple file upload problem in JSF as follows.
Here is the xhtml file that would take the files

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<h:outputScript library="javascript" name="amharic.js"/>
<title>OH YEA, PUT your face HERE</title>

<h:form id="uploadForm" enctype="multipart/form-data">
<h:panelGrid columns="3">
<h:outputLabel for="file1" value="Select file" />
<t:inputFileUpload id="file1" value="#{myBean.uploadedFile}" required="true" />
<h:message for="file1" style="color: red;" />
<h:outputLabel for="file2" value="Select file" />
<t:inputFileUpload id="file2" value="#{myBean.uploadedFile}" required="false" />
<h:message for="file2" style="color: red;" />
<h:outputLabel for="file3" value="Select file" />
<t:inputFileUpload id="file3" value="#{myBean.uploadedFile}" required="false" />
<h:message for="file3" style="color: red;" />

<h:panelGroup />
<h:commandButton value="save" action="#{myBean.uploadFiles}" />
<h:message for="uploadForm" infoStyle="color: green;" errorStyle="color: red;" />

As you can see, the file would be dealing with a single backing bean property uploadedFile. You would tomahawk for the file upload one. There is also file upload in richfaces as well.

Now, let’s see what is the hood of MyBean.java. In the bean you would have to member variables for this purpose:

private List<UploadedFile> uploadedFiles;
private UploadedFile uploadedFile;

You can get the uploaded file from org.apache.myfaces.custom.fileupload.UploadedFile.
Then have a normal getter and setter for both.
The trick is in the setter of the uploadedFile:

public void setUploadedFile(UploadedFile uploadedFile){

When the file is requested, add it to the list of the uploadedFiles.
For the action which would would do the actual uploading of the file, I have used the snippet from http://balusc.blogspot.com/2008/02/uploading-files-with-jsf.html.

public String uploadFiles(){
for(UploadedFile uploadedFile : this.uploadedFiles){
if (uploadedFile !=null ){

// Prepare filename prefix and suffix for an unique filename in upload folder.
String prefix = FilenameUtils.getBaseName(uploadedFile.getName());
String suffix = FilenameUtils.getExtension(uploadedFile.getName());

// Prepare file and outputstream.
File file = null;
OutputStream output = null;
try {
// Create file with unique name in upload folder and write to it.
file = File.createTempFile(prefix + "_", "." + suffix, new File("Your_Path"));
output = new FileOutputStream(file);
IOUtils.copy(uploadedFile.getInputStream(), output);

// Show succes message.
FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
FacesMessage.SEVERITY_INFO, "File upload succeed!", null));
} catch (IOException e) {
// Cleanup.
if (file != null) file.delete();

// Show error message.
FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
FacesMessage.SEVERITY_ERROR, "File upload failed with I/O error.", null));

// Always log stacktraces (with a real logger).
} finally {
return "done";


webxml attribute is required error on maven build of war

This error appears mostly when Maven could not find the web.xml file. If you are following the default maven structure, make sure the webapp folder is named correctly – like not webapps or something like that.
Once you make sure, you can try by explicitly telling maven where the web.xml file is using


Using JSF form fields with jQuery – Can’t use jQuery with : (colon) problem

if you have a jsf page of the following

<h:form id="frmRegistration">
<h:panelGrid columns="2" rules="rows">
<h:outputLabel id="lblFirstName" value="First Name"  />
<h:inputText id="txtFirstName" value="#{memberRegisterBean.member.name}" label="First Name" required="true"/>

And say you want assign default value from javascript to the text box you would use:

    $("#frmRegistration:txtFirstName").val("this val");

Since that is how JSF would generate the id of the component
But, you wont see any effect as jQuery don’ like the generated colon (:).
use this instead> ‘escape it’

    $("#frmRegistration\:txtFirstName").val("this val");

Component ID id:compid has already been found in the view JSF error

This error is quite explanatory in JSF.

I got once in a while when I work with dynamic generation of the components.

If you have this, the most common cause of this error would be you are trying to attach the an html component from your bean again.

Especially, if you have session scoped managed bean and you are attaching dynamically elements, may be one of your methods has already attached the component to the view (like the grid you are using for your component) and the other method is trying to attach it again.

If that is the case you might need to check the existence of the component in the grid (or any component you are using) before attaching it.

Also: see how to add session bean to request

NonUniqueObjectException: a different object with the same identifier value was already associated with the session

The error different object with the same identifier value was already associated with the session would happen quite sometime while working on hibernate with java web application

It occurs when the hibernate session contains object to be updated and when the application tries to update another object with the same id as that of the session owned one.

Let’s assume there is an object Can with properties material and volume as follows for simple illustration

public class Can{
  private Integer canId;
  private String material;
  private Double volume;
  //getters; setters;

Assume we have DAO for this object named CanDao.

So, being on your jsf dataTable you selected one ‘can’ object to be updated or deleted. I just put the CanDao object directly into the Bean for the illustration purpose – it is good to wrap this object in the service object, say CanService, for easier manupulation.

Lets have the bean as follows:

class CanBean{
   private HtmlDataTable canTable; //for binding list of can objects from jsf list
   private CanDao canDao; //dao object;
   private List cans; //list jsf datatable would use it.
   public String update(){
      //get the selected object from data table
      ICan selectedCan = (ICan)this.canTable.getRowData();
      return "Update";

Here the line calling saveOrUpdate would be responsible for throwing the error of different object with the same identifier value was already associated with the session

Here is how to fix it
Since the session contain the same identifier, let’s get the actual or original object from the session it self

  //corrected update method for Can Bean
   public String update(){
      //get the selected object from data table
      ICan selectedCan = (ICan)this.canTable.getRowData();
      ICan original = this.canDao.getById(selectedCan.getCanId()); //
      return "Update";

This would fix the problem. But, there are other ways of preventing the session problem from occurring – googling a bit might help.

If you are J2EE developer:

Hello world with maven step by step

See how you can add session bean

Why do I get can not forward after response error and how to solve it

Showing error message on selectOneMenu while selecting default

So, we have a menu, brimmed with our objects from list/database. The intention would be creating a default “Select” kind of the first row and to brag on the user when s/he selects the default.

The trick is simple, create the first list with null object and label it as Select. Lets show it with simple example.
We want to have a list of programming languages on our select menu. And, the first would be a default object.

    //Actual domain class
    class Language{
        private String name;
        private String type;
        private boolan isCompiled;

       getters/setters goes here
   //Bean class
   class someBean{
        private List languages;
        public String getLanguages(){
            //Let languages would be filled by some service or factory
            this.languages = someLanguageFactory.getAllLanguages(); 
           //Assign the first element as null
           this.languages.add(0, null);
   //JSF page
   <h:selectOneMenu id="selectLanguage" value="someBean.languages" 
     requred="true" ....

This should do the task, make the list required, and populate the first list null. So, during validation if the selection is null it would be rejected as we have told it to watch an eye on blank fields.

datatable/component not updated after deleting and adding new one

During working on tabular data, it is common to have edit and delete command buttons for each row.

And, after we update or delete we want the table to be updated. Let’s looks some simple example.

The table on the JSF might look like

<form id="tablularForm">
<h:datatable id="tabularData" value="#{someBean.list}"
binding="#{someBean.htmlDataTable}" var="data">
<h:outputText id="colum1" value="#{data.column}" />
<h:CommandLink id="edit" value="Edit" action="#{someBean.editAction}" reRender="tabularData"/>
<h:CommandLink id="delete" value="Delete" action="#{someBean.deleteAction}" reRender="tabularData"/>
<h:CommandButton id="add" value="add" action="#{someBean.addAction}" />

The above ideal table would work fine.

The datatable would store values by reading from bean and would be updated on Edit and Delete actions accordingly.

This is b/c of the reRender attribute of the components.

The glitch comes when there is no any data in the table. Say you daleted all the data and you want to add a new one.

Or it is the brand new table to be added.

The row would be added but it wont be shown on the table. In short the table would not be updated.

The thing is when we use reRender, we have to use the enclosing component not the component to be safe!.

When it tries to rerender if the component was not there initially, it wont rerender it.
So, here we can use the id of the form for rerendering the datatable and we would be OK.

See why jsf apps are slow in cases