Full WebApplication JSF EJB JPA JAAS

Business – DAOs

I will use a generic DAO to basic CRUD operations and others two DAOs: one for User and another for Dog. It will be very easy to understand its use:

package com.dao;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

public abstract class GenericDAO<T> {
	private final static String UNIT_NAME = "CrudPU";

	@PersistenceContext(unitName = UNIT_NAME)
	private EntityManager em;

	private Class<T> entityClass;

	public GenericDAO(Class<T> entityClass) {
		this.entityClass = entityClass;

	public void save(T entity) {

	protected void delete(Object id, Class<T> classe) {
		T entityToBeRemoved = em.getReference(classe, id);


	public T update(T entity) {
		return em.merge(entity);

	public T find(int entityID) {
		return em.find(entityClass, entityID);

	// Using the unchecked because JPA does not have a
	// em.getCriteriaBuilder().createQuery()<T> method
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<T> findAll() {
		CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
		return em.createQuery(cq).getResultList();

	// Using the unchecked because JPA does not have a
	// ery.getSingleResult()<T> method
	protected T findOneResult(String namedQuery, Map<String, Object> parameters) {
		T result = null;

		try {
			Query query = em.createNamedQuery(namedQuery);

			// Method that will populate parameters if they are passed not null and empty
			if (parameters != null && !parameters.isEmpty()) {
				populateQueryParameters(query, parameters);

			result = (T) query.getSingleResult();

		} catch (Exception e) {
			System.out.println("Error while running query: " + e.getMessage());

		return result;

	private void populateQueryParameters(Query query, Map<String, Object> parameters) {

		for (Entry<String, Object> entry : parameters.entrySet()) {
			query.setParameter(entry.getKey(), entry.getValue());
package com.dao;

import javax.ejb.Stateless;

import com.model.Dog;

public class DogDAO extends GenericDAO<Dog> {

	public DogDAO() {
package com.dao;

import java.util.HashMap;
import java.util.Map;

import javax.ejb.Stateless;

import com.model.User;

public class UserDAO extends GenericDAO<User> {

	public UserDAO() {

	public User findUserByEmail(String email){
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("email", email);		

		return super.findOneResult(User.FIND_BY_EMAIL, parameters);

About the code above:

  • I hid some warnings because the JPA code does not “understand” generics yet.
  • The method “findOneResult” is with protected access just to prevent external access from other classes; this method requires logic to populate the parameters as we can see in the UserDAO.
  • The class GenericDAO has a complete CRUD methods plus a method that returns a single object given a NamedQuery.
  • The UserDAO class has a method (findUserByEmail) that belongs only to the class; but it has all CRUD methods by inheritance. With this pattern of DAOs we got a code more flexible.
  • The DogDAO has no method in it but only the CRUD methods; you could implement any method in the class without problem.
  • Instead using a method to “save” and other to “update” your objects you could use one method “entityManager.merge()”. You will have the same result but you will need to pay attention to the Cascade options.
  • I did not use Interfaces because EJB 3.1 allows us to have Stateless Local Session Beans without interface. If you are using an older EJB version you will need to implement an interface (how to Implement EJBs with interfaces we will see in this post, in the Façades page). I will not develop with interfaces my DAO/Model just to save space in this post. Remember: “Always program to an interface” (Design Pattern – Strategy).
  • If you use the JBoss 4.2 you could use the org.jboss.annotation.ejb.LocalBinding or org.jboss.annotation.ejb.RemoteBinding annotations; in this annotation you can write the name that will be mapped and referred by the EJB.

75 thoughts on “Full WebApplication JSF EJB JPA JAAS

  1. Dude,

    Your collection of posts about the full webapp stack is awesome.

    Please keep up the good work as I love what you’re doing and how you’re doing it,

  2. I’m using MySQL instead of PostgreSQL and Hibernate doesn’t create the Schema and Tables for me. Do you know where my problem is? Thank you.

  3. I like your post very much. So much, I wanted to print it. However, no matter what page I am on if I hit your print command link, it prints the first page.

    • Hello,

      Indeed it will only print one page. You will have to change pages and print it one by one. =/

      This “print” button is from a WordPress plugin. I cannot change it. =/

      Thanks for passing by.

      I am glad that I could help you.

  4. the same methode that i used but it seem that the reqest of retreiving login and pass to verifiy user cant be acheived ,
    the error is 14:48:17,035 WARN [org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory] exception trying to create exception sorter (disabling):: java.lang.ClassNotFoundException: org.jboss.resource.adapter.jdbc.Driver

    i have my driver deployed and all my session works corectly

    • Hello Ahmed.

      You could check the connection that your JAAS is using. Maybe it is looking for other driver, a different of your applications.

      Thanks for passing by.

  5. i have some problems i need your help tanks
    “Error:no’server’JVM at ‘c:ProgramFilesjavajre6binserverjvm.dll’

  6. good job freind,,but how the mail has being the login identifier.! when i put FacesContext.getCurrentInstance().getUserPrincipal().getName(); i get nullpointerException

    • Hello soh,

      Check if you JSF context is correct. You will find the set up in the web.xml and you must access the application according with the URL defined in the web.xml.

      If you need more analysis about this, you can post your code in here http://www.coderanch.com .

      Thanks for the visit.

  7. Hi
    I am working in a project.
    I want to implement JPA 2 in some section but want to continue JDBC with reporting because huge data handling and complex queries are there. I also want to use JTA . So can you please provide some example how to manage both with JTA.

    I think it will be very helpful for many person.

    • Hello subs,

      That is not an easy subject to talk about.

      I was reading a book Pro JPA 2: Mastering the Java™ Persistence API – Mike Keith, Merrick Schincariol that talks about this approach of choosing JPA or JDBC in a legacy application.

      The author of the book says that it is worth to use JPA over JDBC even only for read only queries (Fast Lane Reader pattern). JPA has a good cache control and you can set up more of it for a better performance, with this cache the JPA performance will be better than JDBC.

      And if you need object to be created from a query (eg: just for a report), you can use a constructor of a class in a JPQL like select new com.report.MyClass(name, age) from Person p. (Check this post for more details for the JPQL http://uaihebert.com/?p=1274)

      I hope that this information might help you.

      Thanks for passing by.

  8. I am getting this in the logs after trying to log in: 17:38:03,209 ERROR [org.jboss.security.authentication.JBossCachedAuthenticationManager] (http– Login failure: javax.security.auth.login.FailedLoginException: Password Incorrect/Password Required

    There’s no other output in the logs. How would i go about solving this?
    I also had to modify a few bits to get this to work with AS7:

    1) standalone.xml Datasource declaration.
    Jboss prints that jndi names should start with java: or java:jboss
    So the datasource jndi name becomes: java:jboss/datasources/CrudDS

    2) Because we had to modify the datasource jndi, we also have to modify the security-domain dsjndi name to point to the above (standalone.xml again):

    I am also getting an error for the welcome-file in eclipse. It seems that eclipse can’t find that file (though it exists).
    Worked this out. You need a jboss-web.xml defining the security-domain INSIDE the META-INF directory of your JSF project.

    Otherwise jboss will not pick up the correct domain if there are more than one defined in your Jboss standalone.xml
    Correction: inside your WEB-INF directory

    • Hello Dimitris,

      I edited your message to put all your messages in just one.

      I glad that you could solve it.

      I do have the same problem with Eclipse, it says that the file do not exists when it does. =/

      The solution that I found was to turn off this warning. :D

      Thanks for passing by and for the feedback.

  9. Hi

    I have this error:

    Exception during createSubject()PB00024: Access Denied:Unauthenticated caller:null: java.lang.SecurityException: PB00024: Access Denied:Unauthenticated caller:null
    at org.jboss.security.plugins.JBossSecuritySubjectFactory.createSubject(JBossSecuritySubjectFactory.java:89)
    at org.jboss.jca.deployers.common.AbstractDsDeployer$1.run(AbstractDsDeployer.java:1020)
    at org.jboss.jca.deployers.common.AbstractDsDeployer$1.run(AbstractDsDeployer.java:1015)
    at java.security.AccessController.doPrivileged(Native Method) [rt.jar:1.7.0_05]
    at org.jboss.jca.deployers.common.AbstractDsDeployer.createSubject(AbstractDsDeployer.java:1014)
    at org.jboss.jca.deployers.common.AbstractDsDeployer.deployDataSource(AbstractDsDeployer.java:563)
    at org.jboss.jca.deployers.common.AbstractDsDeployer.createObjectsAndInjectValue(AbstractDsDeployer.java:283)
    at org.jboss.as.connector.subsystems.datasources.AbstractDataSourceService$AS7DataSourceDeployer.deploy(AbstractDataSourceService.java:271)
    at org.jboss.as.connector.subsystems.datasources.AbstractDataSourceService.start(AbstractDataSourceService.java:111)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.7.0_05]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.7.0_05]
    at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_05]

    the cause is the security-domain, if I set it in the datasource, the server cant to connect with the database :S.

    Im using Jboss As 7.1.0 Final, maybe is a bug with the version.

    Waiting for feedback, thanks !.

    PD: sorry my english

    • Hello Hernan,

      I do not thinkg that it is the bug version.

      Looking at the error message: Unauthenticated caller:null I do think that there is some configuration.

  10. i just configured the above application with JSF2, JAAS, EJB, JPA is working good and i just configured richfaces 4 to this application and skins but these skins not at all effecting to any page….i just configured in the web.xml as below.




    The simple xhtml page:

    The rich panel is not at showing in blue….not only the above page..if i take any page…static content being printed but blue skin/color is not applying to pages…Even custom CSS also not working even if i include the css file.

    Note: All richfaces jars(4 jars + ccsparser, guava, sac) included but not able to see any blue skin

    • Hello Santhosh, good morning.

      I cannot tell you for sure.

      I do not have a good knowledge in richfaces, I would need to read some Richfaces documentation.

      Sorry. =/

  11. Hi,

    Its just FYI…i want to share the solution with you i got configured richfaces 4 to above application….

    put these jars in WEF-INFlib directory…


    and my web.xml add these entries:




    my simple xhtml file:

    JSF Start


  12. Hola amigo disculpa estuve revisando tu post y me parece uno de los mas interesantes… empese a probarlo pero tengo un poco de dificultad al crear la base de datos con las tablas estaria muy agradecido si me pudieras dar una mano con el codigo de la base de datos…

    • Hi!

      Following this sample you will not need to create the database manually.

      Just follow the steps and start the JBoss, the database will be created automatically.

      Thanks for passing by.

  13. Hello. Great website, thanks for all the great information! I am getting stuck in this tutorial though at the lines:

    “Add the EJB project to the JBoss.

    Create the database in the Postgres and start the JBoss”

    I do not know how to do any of these things. Could you point out how, or show me a link that shows how to do it?

    Thanks a lot and Happy Holidays,

    • Hello MR. Bilbo, how are you? Is Frod fine? lol

      You can add the EJB to the JBoss just by right click in the server (tab server in the eclipse), and select the add option.

      To create the database in the postgres search in the google for: create database postgres.

      I am sorry for the late reply, I am really busy in this days. =/

    • Hello Asme,

      You could do it using the concepts. The EJB, JSF, JPA and JAAS will still the same, the difference will be your IDE only.

      Thanks for passing by.

  14. Hi I am getting the following error on EAP 6. I have modified the original code, but perhaps you can point me in the right direction:

    ERROR [org.jboss.security] (http-localhost/ PBOX000206: Login failure: javax.security.auth.login.LoginException: java.lang.IllegalArgumentException
    at javax.security.auth.callback.NameCallback.(NameCallback.java:73)
    at org.jboss.as.security.RealmDirectLoginModule.validatePassword(RealmDirectLoginModule.java:195)
    at org.jboss.security.auth.spi.UsernamePasswordLoginModule.login(UsernamePasswordLoginModule.java:280)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at javax.security.auth.login.LoginContext.invoke(LoginContext.java:769)
    at javax.security.auth.login.LoginContext.access$000(LoginContext.java:186)
    at javax.security.auth.login.LoginContext$4.run(LoginContext.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:680)
    at javax.security.auth.login.LoginContext.login(LoginContext.java:579)

    It’s as though my session is immediately invalidated?

    • Hello,

      I am sorry, but I cannot help you with this error.

      There is just a few information about the error.

      Undo your edits, then start editing it step by step.

      You will find the error easily.

  15. Thank you very much. very well done tutorial.
    I only have a problem with DogfacadeImp:
    public void delete(Dog dog) {

    where delete in GenericDAO is declared protected and with argument Object id and class. I guess that shouldn’t work.
    Thank you again.

    • Hello Yassine.

      Thank you so much for your feedback.

      I edited the post, the correct would be dogDAO.delete(dog.getId());

      I am really sorry for the wrong code.

      Thank you! =D

    • Hello,

      Unable to retrieve EntityManagerFactory for unitName CrudPU

      Check if the name is the same at the persistence.xml.

      See you later.

  16. works great! but i have a little problem when i try to do login from the login.jsf

    Estado HTTP 408 – El tiempo permitido para realizar login ha sido excedido. Si deseas continuar, debes hacer clik dos veces y volver a hacer clik otra vez o cerrar y reabrir tu navegador


    • Hello Camilo,

      I cannot tell you for sure what is going wrong.

      Check if the firewall/anti-virus is not blocking your server connection door.

      Thanks for passing by.

  17. Hello,

    Very nice tutorial! Thank You.
    I would ask as a beginner, I want to use Glassfish instead of JBoss. Is it possible and where must I make changes ?


    • Hello Ali,

      Yes, you can use it with Glassfish but I do not have here the files that you should change.

      Sorry about that.

      Thanks for passing by and the support.

  18. Hi,

    you’ve done a great job with this tutorial! It was a hell of a help for me starting with this topic!
    Nevertheless I found out that I had a problem with caching data:
    When creating a group and assining it to a user the information was stored in the database but not in cache. That results in wrong actions when trying to delete the group (it was not encountered that there is a user having this group). Restarting the application solved the problem as the cache was fresh but I wanted the cache to be refreshed as soon as I do any modifying action like insert, update or delete.

    Therefore I added the following code to my abstract class GenericDao (just used the update method – same has to be applied for save and delete method):

    public E update(final E entity) {
    return entity;

    public void refresh(E entity) {
    em.getEntityManagerFactory().getCache().evict(this.entityClass, entity);

    What do you think about this solution? Maybe it is a help for anybody who is looking for the same problem I was :-)


    • Stefanie, good morning.

      Thank you for the feedback.

      I cannot tell you if this is the best solution for the problem because I would need to understand every detail of what is going on.

      I appreciate your time in leaving the solution here to help others with the same kind of problem.

      Thank you!

  19. Hello,

    You’ve created great tutorial, but I have problem with the last step – deploy CrudEAR project. This is the console output:

    20:57:07,839 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-8) MSC00001: Failed to start service jboss.deployment.subunit."CrudEAR.ear"."CrudJSF.war".INSTALL: org.jboss.msc.service.StartException in service jboss.deployment.subunit."CrudEAR.ear"."CrudJSF.war".INSTALL: Failed to process phase INSTALL of subdeployment "CrudJSF.war" of deployment "CrudEAR.ear"
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:121) [jboss-as-server-7.0.2.Final.jar:7.0.2.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1824) [jboss-msc-1.0.1.GA.jar:1.0.1.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1759) [jboss-msc-1.0.1.GA.jar:1.0.1.GA]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [:1.7.0_45]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [:1.7.0_45]
    at java.lang.Thread.run(Unknown Source) [:1.7.0_45]
    Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: No component found for type 'com.facade.UserFacade' with name null
    at org.jboss.as.ejb3.deployment.processors.EjbInjectionSource.getResourceValue(EjbInjectionSource.java:68)
    at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor.addJndiBinding(ModuleJndiBindingProcessor.java:200)
    at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor$1.handle(ModuleJndiBindingProcessor.java:168)
    at org.jboss.as.ee.component.ClassDescriptionTraversal.run(ClassDescriptionTraversal.java:52)
    at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor.processClassConfigurations(ModuleJndiBindingProcessor.java:140)
    at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor.deploy(ModuleJndiBindingProcessor.java:133)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:115) [jboss-as-server-7.0.2.Final.jar:7.0.2.Final]
    ... 5 more

    Could you help me please, and explain what I did wrong?
    Kind regards,

  20. Great tuto but I’ve this errors can you help me.


    15:33:23,897 INFO [org.jboss.modules] JBoss Modules version 1.1.1.GA
    15:33:24,186 INFO [org.jboss.msc] JBoss MSC version 1.0.2.GA
    15:33:24,256 INFO [org.jboss.as] JBAS015899: JBoss AS 7.1.1.Final “Brontes” starting
    15:33:25,084 ERROR [org.jboss.as.server] JBAS015956: Caught exception during boot: org.jboss.as.controller.persistence.ConfigurationPersistenceException: JBAS014676: Failed to parse configuration
    at org.jboss.as.controller.persistence.XmlConfigurationPersister.load(XmlConfigurationPersister.java:141) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.ServerService.boot(ServerService.java:266) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.controller.AbstractControllerService$1.run(AbstractControllerService.java:155) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final]
    at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_26]
    Caused by: javax.xml.stream.XMLStreamException: com.ctc.wstx.exc.WstxParsingException: Duplicate attribute ‘use-java-context’.
    at [row,col {unknown-source}]: [105,154]
    at org.jboss.as.connector.subsystems.datasources.DataSourcesExtension$DataSourceSubsystemParser.readElement(DataSourcesExtension.java:784)
    at org.jboss.as.connector.subsystems.datasources.DataSourcesExtension$DataSourceSubsystemParser.readElement(DataSourcesExtension.java:333)
    at org.jboss.staxmapper.XMLMapperImpl.processNested(XMLMapperImpl.java:110) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
    at org.jboss.staxmapper.XMLExtendedStreamReaderImpl.handleAny(XMLExtendedStreamReaderImpl.java:69) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
    at org.jboss.as.server.parsing.StandaloneXml.parseServerProfile(StandaloneXml.java:894) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.parsing.StandaloneXml.readServerElement_1_1(StandaloneXml.java:330) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.parsing.StandaloneXml.readElement(StandaloneXml.java:127) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.parsing.StandaloneXml.readElement(StandaloneXml.java:100) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.staxmapper.XMLMapperImpl.processNested(XMLMapperImpl.java:110) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
    at org.jboss.staxmapper.XMLMapperImpl.parseDocument(XMLMapperImpl.java:69) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
    at org.jboss.as.controller.persistence.XmlConfigurationPersister.load(XmlConfigurationPersister.java:133) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final]
    … 3 more
    Caused by: com.ctc.wstx.exc.WstxParsingException: Duplicate attribute ‘use-java-context’.
    at [row,col {unknown-source}]: [105,154]
    at com.ctc.wstx.sr.StreamScanner.constructWfcException(StreamScanner.java:606)
    at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:479)
    at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:464)
    at com.ctc.wstx.sr.AttributeCollector.throwDupAttr(AttributeCollector.java:1143)
    at com.ctc.wstx.sr.AttributeCollector.resolveNamespaces(AttributeCollector.java:997)
    at com.ctc.wstx.sr.InputElementStack.resolveAndValidateElement(InputElementStack.java:498)
    at com.ctc.wstx.sr.BasicStreamReader.handleStartElem(BasicStreamReader.java:2942)
    at com.ctc.wstx.sr.BasicStreamReader.nextFromTree(BasicStreamReader.java:2802)
    at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1050)
    at com.ctc.wstx.sr.BasicStreamReader.nextTag(BasicStreamReader.java:1125)
    at org.jboss.staxmapper.XMLExtendedStreamReaderImpl.nextTag(XMLExtendedStreamReaderImpl.java:152) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
    at org.jboss.as.connector.subsystems.datasources.DsParser.parseDataSources(DsParser.java:185)
    at org.jboss.as.connector.subsystems.datasources.DsParser.parse(DsParser.java:165)
    at org.jboss.as.connector.subsystems.datasources.DataSourcesExtension$DataSourceSubsystemParser.readElement(DataSourcesExtension.java:776)
    … 13 more

    15:33:25,114 FATAL [org.jboss.as.server] JBAS015957: Server boot has failed in an unrecoverable manner; exiting. See previous messages for details.
    15:33:25,137 INFO [org.jboss.as] JBAS015950: JBoss AS 7.1.1.Final “Brontes” stopped in 14ms

    • Hello uddy,

      It looks like you edited a xml with an error. Check the edited xml.

      Thanks for passing by. I am sorry for the late response, I was very busy this last month.

  21. Hi am working an a Distributed java application with EJB and JPA. Am able to insert into database however am not able to retrieve any thing from the database. And am unsuccessful working with object in the remote interface. My entity classes are saved in the EJB Module and my Class Library is saving my Remote Inteface. Moreover if am saving my entity class in the class Library am not able to deploy the EJB application. Can you please help me regarding this.

    Regards Gaynusha

Leave a Comment