Full Web Application with Tomcat JSF Primefaces JPA Hibernate

92

Posted on June 21, 2012 by

Share it now!

ManagedBeans

In the “com.mb” package you will need to create the classes bellow:

package com.mb;

import org.primefaces.context.RequestContext;

import com.util.JSFMessageUtil;

public class AbstractMB {
	private static final String KEEP_DIALOG_OPENED = "KEEP_DIALOG_OPENED";

	public AbstractMB() {
		super();
	}

	protected void displayErrorMessageToUser(String message) {
		JSFMessageUtil messageUtil = new JSFMessageUtil();
		messageUtil.sendErrorMessageToUser(message);
	}

	protected void displayInfoMessageToUser(String message) {
		JSFMessageUtil messageUtil = new JSFMessageUtil();
		messageUtil.sendInfoMessageToUser(message);
	}

	protected void closeDialog(){
		getRequestContext().addCallbackParam(KEEP_DIALOG_OPENED, false);
	}

	protected void keepDialogOpen(){
		getRequestContext().addCallbackParam(KEEP_DIALOG_OPENED, true);
	}

	protected RequestContext getRequestContext(){
		return RequestContext.getCurrentInstance();
	}
}
package com.mb;

import java.io.Serializable;
import java.util.List;

import javax.faces.bean.*;

import com.facade.DogFacade;
import com.model.Dog;

@ViewScoped
@ManagedBean
public class DogMB extends AbstractMB implements Serializable {
	private static final long serialVersionUID = 1L;

	private Dog dog;
	private List<Dog> dogs;
	private DogFacade dogFacade;

	public DogFacade getDogFacade() {
		if (dogFacade == null) {
			dogFacade = new DogFacade();
		}

		return dogFacade;
	}

	public Dog getDog() {
		if (dog == null) {
			dog = new Dog();
		}

		return dog;
	}

	public void setDog(Dog dog) {
		this.dog = dog;
	}

	public void createDog() {
		try {
			getDogFacade().createDog(dog);
			closeDialog();
			displayInfoMessageToUser("Created With Sucess");
			loadDogs();
			resetDog();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageToUser("Ops, we could not create. Try again later");
			e.printStackTrace();
		}
	}

	public void updateDog() {
		try {
			getDogFacade().updateDog(dog);
			closeDialog();
			displayInfoMessageToUser("Updated With Sucess");
			loadDogs();
			resetDog();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageToUser("Ops, we could not create. Try again later");
			e.printStackTrace();
		}
	}

	public void deleteDog() {
		try {
			getDogFacade().deleteDog(dog);
			closeDialog();
			displayInfoMessageToUser("Deleted With Sucess");
			loadDogs();
			resetDog();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageToUser("Ops, we could not create. Try again later");
			e.printStackTrace();
		}
	}

	public List<Dog> getAllDogs() {
		if (dogs == null) {
			loadDogs();
		}

		return dogs;
	}

	private void loadDogs() {
		dogs = getDogFacade().listAll();
	}

	public void resetDog() {
		dog = new Dog();
	}
}
package com.mb;

import java.io.Serializable;

import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import com.model.User;

@SessionScoped
@ManagedBean(name="userMB")
public class UserMB implements Serializable {
	public static final String INJECTION_NAME = "#{userMB}";
	private static final long serialVersionUID = 1L;

	private User user;

	public boolean isAdmin() {
		return user.isAdmin();
	}

	public boolean isDefaultUser() {
		return user.isUser();
	}

	public String logOut() {
		getRequest().getSession().invalidate();
		return "/pages/public/login.xhtml";
	}

	private HttpServletRequest getRequest() {
		return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
	}

	public User getUser() {
		return user;
	}

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

import java.io.Serializable;
import java.util.*;

import javax.faces.bean.*;

import com.facade.*;
import com.model.*;
import com.sun.faces.context.flash.ELFlash;

@ViewScoped
@ManagedBean
public class PersonMB extends AbstractMB implements Serializable {
	private static final long serialVersionUID = 1L;

	private static final String SELECTED_PERSON = "selectedPerson";

	private Dog dog;
	private Person person;
	private Person personWithDogs;
	private Person personWithDogsForDetail;

	private List<Dog> allDogs;
	private List<Person> persons;

	private DogFacade dogFacade;
	private PersonFacade personFacade;

	public void createPerson() {
		try {
			getPersonFacade().createPerson(person);
			closeDialog();
			displayInfoMessageToUser("Created With Sucess");
			loadPersons();
			resetPerson();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageToUser("Ops, we could not create. Try again later");
			e.printStackTrace();
		}
	}

	public void updatePerson() {
		try {
			getPersonFacade().updatePerson(person);
			closeDialog();
			displayInfoMessageToUser("Updated With Sucess");
			loadPersons();
			resetPerson();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageToUser("Ops, we could not create. Try again later");
			e.printStackTrace();
		}
	}

	public void deletePerson() {
		try {
			getPersonFacade().deletePerson(person);
			closeDialog();
			displayInfoMessageToUser("Deleted With Sucess");
			loadPersons();
			resetPerson();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageToUser("Ops, we could not create. Try again later");
			e.printStackTrace();
		}
	}

	public void addDogToPerson() {
		try {
			getPersonFacade().addDogToPerson(dog.getId(), personWithDogs.getId());
			closeDialog();
			displayInfoMessageToUser("Added With Sucess");
			reloadPersonWithDogs();
			resetDog();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageToUser("Ops, we could not create. Try again later");
			e.printStackTrace();
		}
	}

	public void removeDogFromPerson() {
		try {
			getPersonFacade().removeDogFromPerson(dog.getId(), personWithDogs.getId());
			closeDialog();
			displayInfoMessageToUser("Removed With Sucess");
			reloadPersonWithDogs();
			resetDog();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageToUser("Ops, we could not create. Try again later");
			e.printStackTrace();
		}
	}

	public Person getPersonWithDogs() {
		if (personWithDogs == null) {
			if (person == null) {
				person = (Person) ELFlash.getFlash().get(SELECTED_PERSON);
			}

			personWithDogs = getPersonFacade().findPersonWithAllDogs(person.getId());
		}

		return personWithDogs;
	}

	public void setPersonWithDogsForDetail(Person person) {
		personWithDogsForDetail = getPersonFacade().findPersonWithAllDogs(person.getId());
	}

	public Person getPersonWithDogsForDetail() {
		if (personWithDogsForDetail == null) {
			personWithDogsForDetail = new Person();
			personWithDogsForDetail.setDogs(new ArrayList<Dog>());
		}

		return personWithDogsForDetail;
	}

	public void resetPersonWithDogsForDetail(){
		personWithDogsForDetail = new Person();
	}

	public String editPersonDogs() {
		ELFlash.getFlash().put(SELECTED_PERSON, person);
		return "/pages/protected/defaultUser/personDogs/personDogs.xhtml";
	}

	public List<Dog> complete(String name) {
		List<Dog> queryResult = new ArrayList<Dog>();

		if (allDogs == null) {
			dogFacade = new DogFacade();
			allDogs = dogFacade.listAll();
		}

		allDogs.removeAll(personWithDogs.getDogs());

		for (Dog dog : allDogs) {
			if (dog.getName().toLowerCase().contains(name.toLowerCase())) {
				queryResult.add(dog);
			}
		}

		return queryResult;
	}

	public PersonFacade getPersonFacade() {
		if (personFacade == null) {
			personFacade = new PersonFacade();
		}

		return personFacade;
	}

	public Person getPerson() {
		if (person == null) {
			person = new Person();
		}

		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public List<Person> getAllPersons() {
		if (persons == null) {
			loadPersons();
		}

		return persons;
	}

	private void loadPersons() {
		persons = getPersonFacade().listAll();
	}

	public void resetPerson() {
		person = new Person();
	}

	public Dog getDog() {
		if (dog == null) {
			dog = new Dog();
		}

		return dog;
	}

	public void setDog(Dog dog) {
		this.dog = dog;
	}

	public void resetDog() {
		dog = new Dog();
	}

	private void reloadPersonWithDogs() {
		personWithDogs = getPersonFacade().findPersonWithAllDogs(person.getId());
	}
}
package com.mb;

import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import com.facade.UserFacade;
import com.model.User;

@RequestScoped
@ManagedBean
public class LoginMB extends AbstractMB {
	@ManagedProperty(value = UserMB.INJECTION_NAME)
	private UserMB userMB;

	private String email;
	private String password;

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String login() {
		UserFacade userFacade = new UserFacade();

		User user = userFacade.isValidLogin(email, password);

		if(user != null){
			userMB.setUser(user);
			FacesContext context = FacesContext.getCurrentInstance();
			HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
			request.getSession().setAttribute("user", user);
			return "/pages/protected/index.xhtml";
		}

		displayErrorMessageToUser("Check your email/password");

		return null;
	}

	public void setUserMB(UserMB userMB) {
		this.userMB = userMB;
	}	
}

About the above code:

  • All ManagedBeans are responsible only for the VIEW actions; the ManagedBeans should be responsible to handle the only outcome of the business methods. There are no business rules in the ManagedBeans. It is very easy to do some business actions in the view layer but is not a good practice.
  • The LoginMB class uses another ManagedBean (UserMB) there were injected inside of it. To inject a ManagedBean inside another ManagedBean you must do as bellow:
    • Uses the @ManagedProperty on the top of the injected ManagedBean
    • Create a set method to the property like “loginMB.setUserMB(…)
  • The PersonMB class could receive refactoring actions because it is too big. The PersonMB is like that to make easer for rookie developers to understand the code faster.

Observations about @ViewScoped

You will see in the managed beans with the @ViewScoped annotation some reload and reset methods. Both methods are required to reset the objects state; e.g. a dog object would hold values from the view after a method execution (persist in the database, display values in a dialog).  If the user open de create dialog and successfully create a dog this dog object will hold all values while the user stays in the same page. If the user opens the create dialog again all the data of the last recorded dog will be displayed there. That is why we have the reset methods.

If you update an object in the database the object in the user view must receive this update too, the ManagedBean objects must receive this new data. If you updated a dog name in the database the list of dog should receive this updated dog too. You can query this new data in the database or just update the managed bean values.

A developer must be aware of:

  • Reload the managed bean data querying the database (the reload methods): if the fired query to reload the ManagedBean object comes with a huge amount of data his query may affect the application performance. A developer could use a datatable with lazy load. Click here to see more about Lazy Datatable.
  • Reload the updated object directly in the managed bean without querying the database: imagine that the user1 updates the dog1 name in the database and at the same time user2 updates the dog2 age. The user1 will see the old data about the dog2 that could cause a database integrity issue if the user1 updates the dog2. A solution to this approach could be a version field in the database table. Before the update takes place this field would be checked. If the version field does not hold the same value found in the database an exception could be raised. With this approach if the user1 updates the dog2 the version value would not be the same.

Response to Full Web Application with Tomcat JSF Primefaces JPA Hibernate

1 3 4 5
  1. Kyon

    Nice work! Thank you for share it.

    I have a question.. What should i do if i wanna make the create person with that autocomplete combo? So, once i want to create a person, i have to choose 1 dog already created.

    • uaihebert Post author

      Hello Kyon,

      thanks for the support.

      You could use the Primefaces component named autocomplete. [=

      Thanks for passing by.

  2. Joel Mestres

    hello again, in your facade you make a new instance of DAO, besides you begin transaction on facade… both things are not good choice, aren’t them?
    I got understood that you have to manage transaction on DAO’s … and facade is just a conector between to layers… what do you think? thanks for yor answer!

    • uaihebert Post author

      Hello Joel.

      If you want it, you could create the transaction in the Facade as well, but you will have to sync in the DAO with the current transaction.

      I just used it in the DAO because this is a simple project, but if a transaction must go on between DAOS it would be better let the Facade handle the transaction.

      Thanks for passing by.

  3. Joel Mestres

    hi thansk for great full example. How can I change db provider for this? I try changing parameters in persistence.xml but result is “unable to find default provider” thanks for your help!

    • uaihebert Post author

      Hello Joel, how are you?

      In the pages of this posts it is displayed where you should change to have a different db provider for the project.

      Thanks for passing by.

  4. Hanan Ahmed

    Thanks for great tutorial, i had a small question here is the only purpose for hibernate in your tutorial is to generate the schema in other words as you are already use JPA 2 can i do without hibernate and use EclipseLink to generate my schema?

  5. Chris Georgoulis

    Hello Hebert,

    Very nice and detailed tutorial. It gave me a lot of nice ideas to improve my own web apps.
    I just have one comment:

    The Persons-Dogs are a @ManyToMany relationships. I see that when removing either dogs or persons you do not remove the other side of the relationship.

    For example a Person has many dogs. Shouldnt before you remove the person, search all the dogs(dogList) and remove the person from them(so basically updating them) – then finally remove the person himself? Shouldnt this be done in order for the bi-directional relationship to be synchronized?

    Thank you in advance,
    Chris.

    • uaihebert Post author

      Hello Chris, good afternoon.

      Indeed your should remove the reference of the entities. I found some other problems in the codes above, like, I forgot to add the mappedBy in the relationship also… -_-”

      Thanks for the feedback. Right now I cannot edit it, but I will do it later.

      I am sorry for the late response, I am very busy these days.

1 3 4 5

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *