Full Web Application with Tomcat JSF Primefaces JPA Hibernate

Hello, how are you?

We are happy for the 100k visitors. To celebrate this mark in this blog we created this post that will show how to create a full web application using the following tools: Tomcat7, JSF2 (Facelets and Libraries) with Primefaces (with AutoComplete), JPA / Hibernate (with a relationship NxN), Login with Filter.

If you want to see a full web application with JSF + EJB + JPA + JBoss 7 click here.

To run the code of this post you will need the artifacts bellow (all jar file you will find in the last page of this post):

You can use the any database you want, you will need the specific driver of the database and to edit the URL connection at the persistence.xml.

At the end of this post you will find the source code with all needed libraries to download.

What you will see today in this post:

  • Page 02: Entity classes of the model. A relationship NxN (@ManyToMany), NamedQueries with JoinFetch, Enum as attribute.
  • Page 03: Generic DAO, application transaction methods, generic methods to populate query parameters.
  • Page 04: Façades an transactions, using the method findReferenceOnly, care using the entityManager.merge() method.
  • Page 05: Filters.
  • Page 06: ManagedBeans. How to inject a ManagedBean inside another ManagedBean, observations about @ViewScoped.
  • Page 07: JSFMessageUtil.
  • Page 08: Configurations file: log4j.properties, messages.properties.
  • Page 09: xhtml pages, Facelets.
  • Page 10: Primefaces AutoComplete, JSF Converter with “forClass”.
  • Page 11: Easiest way to use CSS/javascript/images with JSF.
  • Page 12: “web.xml” configurations.
  • Page 13: Increasing the security of your application.
  • Page 14: Running the application.
  • Page 15: BUG_FIX

The application that you will find in here will have a Dog and Person CRUD (Create, Read, Update, and Delete); only the ADMIN will have access to the Dog CRUD. Before you run this application you should create a database named “JSFCrudDB”.

98 thoughts on “Full Web Application with Tomcat JSF Primefaces JPA Hibernate

  1. Thanks for your useful tutorial. I used a h2 database instead and after I enter some username and password, my database is not created. Can you please help on this problem?

      • Hello,
        thanks for your response. My database is now created. I added two users to the users table. After entering correct username and password and pressing the login button, I keep getting the exception, java.lang.NoClassDefFoundError: Could not initialize class com.dao.UserDAO
        What do you think the problem can be?
        And how can I add extra tables to the database?

  2. I’m a newbie and working on JSF 2 project that using Primefaces jsf + jpa + Tomcat. I’m glad found your tutorial.
    If you have been developed jsf Primefaces app with Netbeans 7.3, please share your knowledge with us.

    Thank you for a great tutorial.

    • Hello Vinh,

      I do not have any material in NetBeans yet.

      I usually write the posts with Eclipse to show all possible configurations and files locations.

      The Netbeans provide several files and configurations after a project is created. I like to show the creation of the files and where it should be placed. [=

      Thanks for passing by.

  3. Hello uaihebert,
    I have a question about updating a Entity.

    public void updateDog(Dog dog) {
    dogDAO.beginTransaction();
    Dog persistedDog = dogDAO.find(dog.getId());
    persistedDog.setAge(dog.getAge());
    persistedDog.setName(dog.getName());
    dogDAO.update(persistedDog);
    dogDAO.commitAndCloseTransaction();
    }

    Why I cannot just call update(dog) like this:
    public void updateDog(Dog dog) {
    dogDAO.beginTransaction();
    dogDAO.update(dog);
    dogDAO.commitAndCloseTransaction();
    }

    Is there any better way to avoid calling whole bunches of set..() methods?

    Thanks.

    • Hello Vinh,

      Yes you could easily do update(dog) only.

      I wrote with all those set() because some users does not have the knowledge about detached entities.

      Imagine if dog has a list like List fleas, but when the application call the updateDog will pass the dog without the fleas. This might happen when the data is coming from a web page and the list is not passed forward. When the dog get persisted with the null list, the fleas list will be updated and lost all its data.

      With some web technologies it is possible to put a entity in a view module and persist only with entityManager.merge().

      I wrote with all those sets to avoid this kind of error to some rookie developers. [=

      I hope that I could help you.

      Thanks for passing by.

  4. Hi uaihebert,

    Excellent post. I will make this the backbone of the new app that I am using. I am a newbie in all these technologies and just reading this post makes me excited in doing my app.

    More powers!

  5. Hi uaihebert,
    I’m not quite understand how the Login works. Can you please write a separate tutorial for jsf login app with tomcat 7?
    Thank you very much.

    • Hello Vinh,

      I do not have time to do it now, sorry.

      To understand the login, just check the filters. A filter is responsible to check if the user has a valid login.

      Thanks for passing by.

  6. When I read page 14, I realized there was no db script. When I ran the application, on the login screen, I inputted values for User name and Password, and then clicked the Log in button. Then I saw an error message about email length. But the mysql database was not created. I didn’t find any error message. Do you have any suggestions to help me on this issue?
    Thanks.

    ————————–

    Hi uaihebert,

    Where do I download the database JSFCrudDB? I saw a underline line on this page:
    “Before you run this application you should create a database named JSFCrudDB”.
    But it’s not a link to download the db script.

    Thanks,
    -Lee

    • Hello Lee,

      I edited your post to put your questions together.

      Did you use the same code posted in this post? Without any change?

      Could you post the full error code here?

      Thanks for passing by.

  7. I think found the reason why the tables were not created for me – my user name was not long enough. When I change the user name to be an email account, the tables were created as you said.
    By the way, will you please tell me where your code to created tables is?

    Thanks.

    • Hello Lee,

      There is no need to create the tables by script.

      There is a configuration in the persistence.xml that will automatically create all the tables.

      All that you need to do is to start the application in login one time, the JPA will create the tables automatically. Remember to manually create the database schema. The database schema you create by yourself, easy action that you can find easily in the internet. No need for script if you use your database GUI.

      Thanks for passing by

  8. Hi uaihebert,
    I have a problem load css file in the Login.xhtml page. I put login.css under resources/css/login.css.

    login.xhtml:

    …..

    If you want to load a css file in your Login.xhtml, how would you do it?
    Thank you so much for your help.

  9. when running i get the error:

    14:59:05,115 INFO [javax.enterprise.resource.webcontainer.jsf.context] (http-/0.0.0.0:8080-3) Exception when handling error trying to reset the response.: com.sun.faces.context.FacesFileNotFoundException: /pages/public/login.xhtml Not Found in ExternalContext as a Resource
    at com.sun.faces.facelets.impl.DefaultFaceletFactory.resolveURL(DefaultFaceletFactory.java:232) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.facelets.impl.DefaultFaceletFactory.resolveURL(DefaultFaceletFactory.java:273) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.facelets.impl.DefaultFaceletFactory.getMetadataFacelet(DefaultFaceletFactory.java:209) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.application.view.ViewMetadataImpl.createMetadataView(ViewMetadataImpl.java:114) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:233) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:116) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.2.Final-redhat-1.jar:2.0.2.Final-redhat-1]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:840) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:622) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:560) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:488) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at com.filter.AbstractFilter.doLogin(AbstractFilter.java:16) [classes:]
    at com.filter.LoginCheckFilter.doFilter(LoginCheckFilter.java:49) [classes:]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.2.Final-redhat-1.jar:7.1.2.Final-redhat-1]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:679) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:931) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_05]

    14:59:05,116 WARNING [javax.enterprise.resource.webcontainer.jsf.renderkit] (http-/0.0.0.0:8080-3) JSF1087: Não foi possível gerar a página de erro de Facelets porque a resposta já foi enviada.
    14:59:05,116 SEVERE [javax.enterprise.resource.webcontainer.jsf.renderkit] (http-/0.0.0.0:8080-3) javax.faces.FacesException: /pages/public/login.xhtml Not Found in ExternalContext as a Resource: javax.faces.FacesException: /pages/public/login.xhtml Not Found in ExternalContext as a Resource
    at com.sun.faces.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:142) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:116) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.2.Final-redhat-1.jar:2.0.2.Final-redhat-1]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:840) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:622) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:560) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:488) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at com.filter.AbstractFilter.doLogin(AbstractFilter.java:16) [classes:]
    at com.filter.LoginCheckFilter.doFilter(LoginCheckFilter.java:49) [classes:]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.2.Final-redhat-1.jar:7.1.2.Final-redhat-1]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:679) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:931) [jbossweb-7.0.16.Final-redhat-1.jar:]
    at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_05]
    Caused by: com.sun.faces.context.FacesFileNotFoundException: /pages/public/login.xhtml Not Found in ExternalContext as a Resource
    at com.sun.faces.facelets.impl.DefaultFaceletFactory.resolveURL(DefaultFaceletFactory.java:232) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.facelets.impl.DefaultFaceletFactory.resolveURL(DefaultFaceletFactory.java:273) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.facelets.impl.DefaultFaceletFactory.getMetadataFacelet(DefaultFaceletFactory.java:209) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.application.view.ViewMetadataImpl.createMetadataView(ViewMetadataImpl.java:114) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:233) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.7-redhat-1.jar:2.1.7-redhat-1]
    … 24 more

    • Hello hilner,

      Check if the file is in the right place.

      The error message is: javax.faces.FacesException: /pages/public/login.xhtml Not Found in ExternalContext as a Resource

  10. hi :D

    I’m using MySql, how to change “persistence.xml” configuration to MySql DB configuration?

    thx a lot :)

    ——–

    I have change the “persistence.xml” like this :

    And I got this error message :
    “javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: Cannot open connection”

    please, help me

    thx a lot :)

    ——–

    Sorry, I mean I had changed the “persistence.xml” like this :

    update

    com.mysql.jdbc.Driver

    jdbc:mysql://localhost:3306/assetmgmt

    root

    org.hibernate.dialect.MySQLInnoDBDialect

    true

  11. Que bom que vc estudou pra caramba, pra deixar tudo de graça para os vagabundos que vao concorrer com as boas vagas de emprego e baixar o salario da categoria, Parabens por ser tao tapado assim. Veja se um vendedor ou um empresário faria isso, colocaria as coisas de graça na web. Seja inteligente.

    • Olá teste, tudo bem?

      Eu gosto de ajudar e note que deixo a explicação de tudo como funciona.

      Sou professor e utilizo meu blog como material adicional para ensino.

      Respeito sua opinião apesar de ser totalmente contrário a ela. [=

      Graças ao blog já consegui entrevistas, oportunidade para escrever para revistas e agora estou escrevendo meu primeiro livro.

      Você continuará sendo bem vindo aqui. [=

      Até mais.

  12. Hello,

    many thanks for this great application, but I have a dummy question: how to build the application (war file)? There is no ant script or Maven pom file.

    • Hello Sofa, how are you?

      The Eclipse can generate it for you.

      There is an option named Export, check it out. [=

      Thanks for passing by.

      • Hello uaihebert,

        Thanks, I am fine, hope you too. Thanks for your response, the export works. but I have a “small” problem:

        I tried to run this applicatiom with Jboss 7, I configured the mysql driver and the data source in JBoss. That works fine,
        the MySQL tables had been created automatically by hibernate. I inputed in the table users an user with the role ADMIN.

        The login screen works. When I submit the login form with no password I get correct response (“Password is empty…”) but when I
        submit the login form with the correct (or false) login data, a java.lang.NullPointerException occurs.

        Hope, you can help, I spent much time with this problem.

        The problem occurs in the class GenericDAO.java probably on this place:
        em = emf.createEntityManager();
        Seemingly the entity manager cannot be created.

        JBoss standalone.xml:
        ——————–

        jdbc:mysql://localhost:3306/jsfcruddb
        mysqlDriver

        root

        org.h2.jdbcx.JdbcDataSource

        com.mysql.jdbc.Driver

        persistence.xml:
        —————-

        org.hibernate.ejb.HibernatePersistence
        java:/MySQLDS

        JBoss log:
        ———-
        01:29:41,412 INFO [org.jboss.as.server] (DeploymentScanner-threads – 2) JBAS018559: Deployed “JSFCrudApp.war”
        01:30:04,343 INFO [org.hibernate.dialect.Dialect] (http–127.0.0.1-8080-2) HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
        01:30:04,361 INFO [org.hibernate.engine.transaction.internal.TransactionFactoryInitiator] (http–127.0.0.1-8080-2) HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory
        01:30:04,376 INFO [org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory] (http–127.0.0.1-8080-2) HHH000397: Using ASTQueryTranslatorFactory
        01:30:04,397 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (http–127.0.0.1-8080-2) HHH000228: Running hbm2ddl schema update
        01:30:04,409 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (http–127.0.0.1-8080-2) HHH000102: Fetching database metadata
        01:30:04,416 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (http–127.0.0.1-8080-2) HHH000396: Updating schema
        01:30:04,419 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (http–127.0.0.1-8080-2) HHH000232: Schema update complete
        01:30:04,508 WARNUNG [javax.enterprise.resource.webcontainer.jsf.lifecycle] (http–127.0.0.1-8080-2) #{loginMB.login}: java.lang.NullPointerException: javax.faces.FacesException: #{loginMB.login}: java.lang.NullPointerException
        at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:]
        at javax.faces.component.UICommand.broadcast(UICommand.java:315) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
        at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
        at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
        at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) [jsf-impl-2.1.7-jbossorg-2.jar:]
        at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.7-jbossorg-2.jar:]
        at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:]
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
        at com.filter.LoginCheckFilter.doFilter(LoginCheckFilter.java:68) [classes:]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
        at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final]
        at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
        at java.lang.Thread.run(Unknown Source) [rt.jar:1.6.0_27]
        Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
        at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
        at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [jsf-impl-2.1.7-jbossorg-2.jar:]
        … 24 more
        Caused by: java.lang.NullPointerException
        at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:73) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:115) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.engine.transaction.internal.jta.CMTTransaction.join(CMTTransaction.java:149) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.ejb.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1207) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.ejb.AbstractEntityManagerImpl.postInit(AbstractEntityManagerImpl.java:176) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.ejb.EntityManagerImpl.(EntityManagerImpl.java:89) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.ejb.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:125) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.ejb.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:120) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at com.dao.GenericDAO.beginTransaction(GenericDAO.java:24) [classes:]
        at com.dao.UserDAO.beginTransaction(UserDAO.java:1) [classes:]
        at com.facade.UserFacade.isValidLogin(UserFacade.java:10) [classes:]
        at com.mb.LoginMB.login(LoginMB.java:40) [classes:]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_27]
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_27]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_27]
        at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.6.0_27]
        at org.apache.el.parser.AstValue.invoke(AstValue.java:262) [jbossweb-7.0.13.Final.jar:]
        at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278) [jbossweb-7.0.13.Final.jar:]
        at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) [jsf-impl-2.1.7-jbossorg-2.jar:]
        at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
        … 25 more

  13. Great tutorial. I am new to all this. How would you go about creating a change password for a user. Just a bit advice on maybe the flow would be very helpful.

    Thanks :)

      • Hi again,

        I have got a link there for a change password. What I want to do is when I click it for it to display the users email which is easy enough as I use the login session. Then I want to check the old password and set a new one.

        I was wondering more which classes I would need to change.

        I have something like this:

        public void updatePassword(User user, String oldPassword, String newPassword) {
        userDAO.beginTransaction();
        User persistedUser = userDAO.find(user.getId());
        if (user != null && user.getPassword().equals(oldPassword)) {
        persistedUser.setPassword(newPassword);
        userDAO.update(persistedUser);
        userDAO.commitAndCloseTransaction();
        }
        }

        Which is in the facade do you think is this something that looks along the right lines? I appreciate you will more than likely be busy but just a hint of whether I am on the right track would be great. I tried to put oldPassword etc in bean but it complains about it not being a field.

        Thanks again Bri :)

        • Hello Brian.

          You could invoke the method just like the other invoked methods samples in the application.

          First, you have to understand better what the error means. Where should the oldPassword come from?

          I think you should read the book Core JavaServer Faces. It is a really great book about JSF.

          Thanks for passing by.

    • Rehan, how are you?

      I used the JSFMessageUtil before presenting it just like I see in the books.

      Most of the times the books show the code and than explains it.

      Thanks for passing by! [=

  14. Thank you so much for this. I’m using it as a template for my project. One question: In LoginMB.login() you save the User object to the session. I realize this is because you want to access it in the Filters. However, because userMB is already SessionScoped, can’t you simply get access to the user object through that? Seems like there would be two user objects in the session with this code. Let me know your thoughts, thank you.

    • Hello Justion,

      I used the UserMB to store inside it because it is a session scoped. The UserMB has other functions other than just the user methods.

      In memory you will have a Managedbean and a user object, but it will consume a very small memory of your server giving you a very usefull objects with methods easily to access.

      Thanks for passing by.

  15. Hi uaihebert,

    I came accross this post while reading various examples of integrating JSF & Hibernate. This is a great example of how to integrate the technologies. The sample application was simple enough so as not to detract from showing the key integration points. I happen to also be using Primefaces so that was a nice added bonus.

    Thanks for taking the time to put this together. I am sure many people will find this as usefull as I have.

  16. A great resource, the best have seen in recent times. Thank you for giving a brother a helping hand. may the good Lord bless you real good

  17. Hello
    First of all thanks for Sharing
    I want to source code of this Project If Possible
    Thanks in advance
    Have a Good Day !

  18. Hi uiaihebert,

    Thanks for sharing,

    I am having problem with “Remove the selected Dog from:
    Refer Error Message Below:

    Jun 05, 2013 2:50:01 PM com.sun.faces.context.AjaxExceptionHandlerImpl log
    SEVERE: JSF1073: javax.faces.event.AbortProcessingException caught during processing of INVOKE_APPLICATION 5 : UIComponent-ClientId=personsForm:personsTable:0, Message=Return type ‘void’ of method ‘resetDog’ in ‘class com.mb.PersonMB’ does not match ‘class java.lang.Void’
    Jun 05, 2013 2:50:01 PM com.sun.faces.context.AjaxExceptionHandlerImpl log
    SEVERE: Return type ‘void’ of method ‘resetDog’ in ‘class com.mb.PersonMB’ does not match ‘class java.lang.Void’
    javax.faces.event.AbortProcessingException: Return type ‘void’ of method ‘resetDog’ in ‘class com.mb.PersonMB’ does not match ‘class java.lang.Void’
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:182)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:777)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIData.broadcast(UIData.java:915)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.filter.DefaultUserPagesFilter.doFilter(DefaultUserPagesFilter.java:32)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.filter.LoginCheckFilter.doFilter(LoginCheckFilter.java:68)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Caused by: javax.el.MethodNotFoundException: Return type ‘void’ of method ‘resetDog’ in ‘class com.mb.PersonMB’ does not match ‘class java.lang.Void’
    at de.odysseus.el.tree.impl.ast.AstProperty.findMethod(AstProperty.java:174)
    at de.odysseus.el.tree.impl.ast.AstProperty.invoke(AstProperty.java:203)
    at de.odysseus.el.tree.impl.ast.AstEval.invoke(AstEval.java:71)
    at de.odysseus.el.TreeMethodExpression.invoke(TreeMethodExpression.java:132)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:153)
    … 32 more

    Thanks,

    LIto

    • Hello.

      There is something wrong with your method:

      Return type ‘void’ of method ‘resetDog’ in ‘class com.mb.PersonMB’ does not match ‘class java.lang.Void’

      I cannot tell you without looking your code.

      Post your code at coderanch it will be easier, if not for me, someone else to help you.

      Thanks for passing by.

  19. Hi,

    How to initiate the database structure in mysql? i put
    which created 4 tables, but when i run the application i get exceptions:
    11:06:38,186 ERROR SchemaUpdate:175 – could not get database metadata
    com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table ‘jsfcruddb.pg_class’ doesn’t exist

    Regards

    • Hello Raw,

      Just looking for this piece of error I cannot tell you for sure what is the error.

      To use MySQL just need to edit the application JAR, the providerand the connection URL at persistence.xml.

      I hope that helps.

      Thanks for passing by.

  20. Hello, and thank you for sharing this application. Finally I got it to work with my Eclipse and Tomcat. I’m new to hibernate and faces. For me it seems that hibernate documentation describes other configuration files, but I can only find the persistence.xml in your application. Do you know where I can get more information/documentation to fully being able to understand your application? Why is the database tables created first time I run the application? I would like to learn more so I’m able to use faces and hibernate for my next project.

    • Hello Tom.

      EntityManager is from JPA API.

      JPA is the Java Specification for persistence. Hibernate is an implementation of JPA.

      The application of this post uses the JPA API with the Hibernate implementation as background.

      Read the book: “Pro JPA 2″. It is a very good book.

      Thanks for passing by.

  21. Hi hebert,
    Thank you for this great tutorial. I have followed up, but in the end I can’t download the source code. The link you gave doesn’t work. you can post even though please

    Thanks

    • Hello, good afternoon.

      Some people around the world are reporting some problems about the source code.

      The code is hosted on google, maybe this is the problem.

      In the last page of this post I provided other link that you can use.

      Thanks for the feedback.

  22. hi,i am sree ,i buld your JSFCrudApp,when i run ur project.on tomcat server,it does not creat database,pls help me to configur the persistence.xml,for auto create database.

    • Hello.

      Check if the user that is written in the persistence.xml has access to create database tables.

      Thanks for passing by.

  23. Hi, uaiHebert;

    Fantastic web app! Having your end-to-end fully functioning app has been instrumental in seeing how all the pieces play together.

    If I were to take the next step and optimize the connection management ( I found that if I played with people and dogs long enough I’d run out of NonTransient jdbc connections ) what text would you recommend reading / learning?

    FYI, I have your web application running in an Amazon ElasticBeanstalk connected to its RDS database. Works great.

    Thank you so much for taking the time to not only create this app, but to provide feedback to your readers. That is very kind.

    Regards,

    Tony

    • Hello Tony, how are you?

      You would need to work with pool connections.

      Take a look at EhCache for pool management or how that tomcat can control connections with datasource. You could create a datasource with tomcat that it would managed the connections to you.

      Thanks for the good feedback, I was very happy to hear it.

      Sorry for the late reply, I am really busy this days.

      Thanks! =D

  24. 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.

    • 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.

  25. 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?

  26. 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!

    • 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.

  27. 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!

    • 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.

  28. 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.

    • Hello Kyon,

      thanks for the support.

      You could use the Primefaces component named autocomplete. [=

      Thanks for passing by.

  29. dear sir,
    you can teach me build webapp jsf primeface with Hibernate ?
    i need your help .
    i follow your sample but have problem when make entity relationship user ,role ,permission

    I’ m very grateful for your help

    • Hello huynv, how are you?

      You can download the sample here and see the code.

      I know that the code of this post works.

      Thanks for passing by.

  30. Hello Hebert,
    This’s a great tutorial. Can you please keep it-up-date with latest version of PrimeFaces 5 + JSF 2.2 + Tomcat 8?
    And I’m looking for a practical tutorial on implementing pagination in a JSF Page for my project.
    Thank you very much for a great tutorial.

    • Hello Vinh,

      I cannot do it right now. This post is huge and it is not easy to edit it.

      I am planning on creating a new version of this post, but it will not be until the end of this year.

      Thanks for passing by.

  31. Dear day Sir, nice tutorial but i am getting this error

    javax.faces.el.EvaluationException: java.lang.ExceptionInInitializerError
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
    at co.za.jmr.healthproj.filter.AbstractFilter.doLogin(AbstractFilter.java:21)
    at co.za.jmr.healthproj.filter.LoginFilter.doFilter(LoginFilter.java:45)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:722)
    Caused by: java.lang.ExceptionInInitializerError
    at co.za.jmr.healthproj.facade.UserFacade.(UserFacade.java:8)
    at co.za.jmr.healthproj.mb.LoginManagedBean.login(LoginManagedBean.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    … 38 more
    Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named JSFCrudPU
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    at co.za.jmr.healthproj.dao.GenericDAO.(GenericDAO.java:18)
    … 48 more

    • Hello, how are you?

      Check if the persistence.xml is in the correct path, or if the persistence-unit has the correct name.

      Thanks for passing by.

Leave a Comment