creating jsf ejb jpa application with wildfly using eclipse

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello, in this tutorial we will create a simple application with ui, service and persistence layers to demonstrate how a java ee application can be designed in layered architecture. We will be creating jsf ejb jpa application with wildfly in eclipse

Objective:

We will creating a simple Employee management app which will be able to add employee details from a JSF page into database. We are creating jsf ejb jpa application with wildfly by using following development environment.

Environment.

Tools and software used in creating jsf ejb jpa application with wildfly are as below

  • jdk 1.8
  • eclipse luna
  • wildfly 8.2
  • mysql database
  • mysql connector jar file
  • jpa, jsf and ejb libraries provided by wildfly 8.2 runtime.
  • primefaces 5.1

Project Architecture:

Let us have a look at what we are going to do exactly in this jsf ejb jpa application with wildfly. Following diagram shows various layers used in application.

JSF EJB JPA Application architecture
JSF EJB JPA Application architecture

The application will flow as follows.

  • Browser request the JSF page on server.
  • JSF page has references to JSF managed beans which act as backing beans for data in the forms of JSF pages.
  • JSF beans have references to EJBs which act as service layer.
  • EJBs in Service layer call persistence methods on JPA entities.
  • Entity manager operations persist data into database.

Creating database in mysql:

We need to create two tables in database. One which represents Employee entity in JPA and the other which will store sequence names and their values. You can read about automatic id generation using jpa table generator strategy.

Create id_gen table for storing sequences names and values. Insert a row with sequence name as employee_gen and value 1.

Create employee table

The tables will be created and they will look as below

database tables

Configuring WildFly in Eclipse:

Please configure wildfly in eclipse if you have not done already

Creating DataSource in WildFly:

As we are going to use JPA, it needs to access database. create a datasource in wildfly to access mysql database

Creating JSF EJB JPA Application with Wildfly in Eclipse:

1. Open eclipse, make sure java EE perspective is opened and create a new dynamic web project by selecting File > New > Dynamic Web Project. Give project name as EmployeeApp. Select target runtime as WildFly 8.x Runtime  and click on Modify button as shown in red rectangle. We need to ensure the project has jsf ejb jpa application with wildfly characteristics.After that click Next

New Dynamic Web Project

 

2. Now as shown below, modify project facelets such that JSF, JPA and CDI checkboxes are checked. This tell that project that we are creating a JSF EJB JPA application with wildfly.Click OK

Modify project facets

 

3. Click Next till you get JPA Facelet dialog box. Here we have to specify which JPA implementation we have to use for project. Select Library provided by target runtime as we are going to use hibernate provided by Wildfly 8.x

JPA Library selected

4. Click Next till you are asked for generating web.xml. Check the box and then click Next.

2015-01-09 15_46_26-Check web.xml box - Windows Photo Viewer

 

5. When JSF Facelets dialog is displayed. Again select the Library provided by target runtime. Add the url pattern *.xhtml. Click Finish.

JSF Url Patterns

 

We are done with creating jsf ejb jpa application structure. It will look like below.

Project Directory Structure

 

External Libraries:

We are going to use primefaces 5.1 and its bluesky theme. So copy those jar files need to be put under WEB-INF/lib. 

Web.xml Configuration:

Put following code in web.xml.

  •   <servlet>  and <servlet-mapping>  elements define the faces servlet and its url pattern.
  • <context-param>  element is used to specify primefaces theme to application

Persistence.xml Configuration:

Configure persistence.xml so that we can declare datasource to be used for application.

 

Creating GUI Layer:

GUI layer consists of JSF page and managed beans

JSF page:

Create home.xhtml under WebContent directory and put following code in it.

Managed Beans:

Create a java class in package com.gui.controllers

 

Creating Service Layer:

Create an interface EmployeeService in package com.ejb.services.

Now provide an implementation. Create class EmployeeServiceImpl in package com.ejb.services.impl

 

Creating JPA Layer:

Now create Employee Entity in package com.jpa.entities as follows.

 

We are done with all code and configurtion. It is time to test jsf ejb jpa application with wildfly.

Testing JSF EJB JPA Application:

Simply start the server now and visit home page. You should see below screen

home.xhtmlEnter your first name, last name and salary and click save button. The data will get saved into database.

I hope this tutorial helped creating a jsf ejb jpa application with wildfly 8 and eclipse luna.

 

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

30 thoughts on “creating jsf ejb jpa application with wildfly using eclipse

  • February 10, 2015 at 2:27 am
    Permalink

    Hi Prasad. It is a very good article , this guide has helped me a lot. Keep going. Congratulations

    Reply
  • February 11, 2015 at 7:37 am
    Permalink

    Hi Prasad,

    I am new to core java. I have completed theoretical part of core jave. Now I want to do any project in java.

    Could you please advice me how can I get a project on core java.

    Note: I have been working in different technology.

    Note: Currentl

    Thanks
    Sudhanshu

    Reply
    • February 12, 2015 at 5:36 pm
      Permalink

      Hi Sudhanshu, I am glad the tutorial was useful for you. I would recommend to start a personal project according to your requirements first.

      Reply
  • February 17, 2015 at 2:58 pm
    Permalink

    Hi 🙂

    In JSF 2.2, @javax.faces.bean.ManagedBean is targeted for deprecation in a future
    version, so it is highly recommended that you use @Named.

    Reply
  • April 27, 2015 at 12:51 am
    Permalink

    First of all thanks for your excellent tutorials on Java EE, clear simple and beautiful UX of this website.

    I wonder should my EJB class be in charged of all CRUD operations or each operation should have its own class?

    Reply
  • June 1, 2015 at 10:47 am
    Permalink

    Thank you sir it helped me a lot

    i can now insert in my database but the xhtml file wont load in my browser theres no output it only has blank page and all the inserted value in my database is null

    what should i do?

    Reply
    • June 1, 2015 at 2:49 pm
      Permalink

      you must be getting some stacktrace on the console. Could you please post that?

      Reply
      • June 5, 2015 at 8:49 am
        Permalink

        i already fixed it , i forget to put the jar files now its theres an output.
        thanks Prasad Kharkar for this tutorial

        can you create a tutorial that can add update delete?

        Reply
  • February 10, 2016 at 1:27 am
    Permalink

    Nice tutorial Sir 🙂 it helped me a lot

    Reply
  • February 24, 2016 at 2:18 pm
    Permalink

    Nice tutorial but ugh I hate Eclipse. Such a piece of garbage compared to IntelliJ. IntelliJ is light years ahead of Eclipse in terms of usability.

    Reply
  • March 22, 2016 at 3:53 am
    Permalink

    Nice stuffs it makes a lot of sense especially for Us. That’s we have little bit of development skills. Thanks was again.

    Reply
  • July 5, 2016 at 1:14 pm
    Permalink

    I am getting a 404 – why is that ? localhost:8080 works !

    Reply
  • July 18, 2016 at 10:18 am
    Permalink

    Hi Prasad,

    it’s very useful, thanks a lot.

    Reply
  • August 16, 2016 at 9:28 am
    Permalink

    Thanks Prasad, great tutorial.

    Just one thing, ¿If I need to use 2 or more tables it’s necessary to use 2 or more id generators tables?

    Thanks again!

    Reply
    • August 16, 2016 at 12:30 pm
      Permalink

      I am glad it was useful for you Gabriel, you do not need more than one id generator tables, you can define multiple id generators in single id generator table itself. You will simply have multiple rows in it.

      Reply
  • August 18, 2016 at 7:07 pm
    Permalink

    hello prasad, i have a problem. my project have all properties but i need list two entities and edit the cell in the table, i don’t know how persist in the database this changes i used wildfly 9 and primefaces for this.

    thanks

    Reply
    • August 19, 2016 at 8:38 am
      Permalink

      hi Pao, could you please be a bit clear? I am not able to fully understand your question.

      Reply
      • August 19, 2016 at 7:35 pm
        Permalink

        sorry, I need save in my database selected rows from my datatable, but in my datatable exist data from two entities, i have a ActionEvent for selected the rows but when select row i don’t have any value for persist in the database.

        public void actionListener(ActionEvent e) throws Exception{
        UIData data = (UIData) e.getComponent().findComponent(“tablaMaterial2”);
        Material_Requisicion d = (Material_Requisicion) data.getRowData();
        Bodega bo=(Bodega)data.getRowData();

        try {
        guardarBodega(d.getCodigo(), bo.getCantidadDevuelta());
        System.out.println(“Change saved!”);
        } catch (Exception ex) {
        System.out.println(“Label could not be saved!”);
        }

        }

        Reply
  • September 29, 2016 at 5:12 am
    Permalink

    Help
    Caused by: javax.el.PropertyNotFoundException: Target Unreachable, identifier ’employeeController’ resolved to null

    Reply
  • December 8, 2016 at 5:09 am
    Permalink

    ontext Path:/EmployeApp
    Servlet Path:/home.xhtml
    Path Info:null
    Query String:null
    Stack Trace
    javax.servlet.ServletException: javax.persistence.PersistenceException: org.hibernate.HibernateException: Could not apply work
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:86)
    io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58)
    io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70)
    io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76)
    io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:261)
    io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:248)
    io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:77)
    io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:167)
    io.undertow.server.Connectors.executeRootHandler(Connectors.java:199)
    io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:761)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    java.lang.Thread.run(Thread.java:745)

    Reply
  • July 13, 2017 at 8:35 am
    Permalink

    Thank you Prasad Kharkar for this tutorial. Very well elucidated. It helped me figure out creating JEE applications. I created it using an EAR (Enterprise Archive) project on Eclipse and Glassfish server 4.1.

    Thank you again Prasad, a solid foundation indeed. I can now start climbing the Ladder (moving up).

    Reply
    • November 22, 2017 at 1:32 am
      Permalink

      Hi Cyprian,
      were you able to get this to work?

      Reply
    • November 22, 2017 at 1:57 am
      Permalink

      I am also getting the 404 error, but localhost:8080 works.

      Here are my logs
      ===============

      14:51:54,377 INFO [orw missing/unsatisfied dependencies:

      Reply
  • November 22, 2017 at 1:59 am
    Permalink

    I am also getting the 404 error, but localhost:8080 works.

    Here are my logs
    ===============

    java:global/EmployeeApp/EmployeeServiceImpl!com.ejb.services.EmployeeService
    java:app/EmployeeApp/EmployeeServiceImpl!com.ejb.services.EmployeeService
    java:module/EmployeeServiceImpl!com.ejb.services.EmployeeService
    java:global/EmployeeApp/EmployeeServiceImpl
    java:app/EmployeeApp/EmployeeServiceImpl
    java:module/EmployeeServiceImpl

    14:52:04,343 INFO [org.infinispan.configuration.cache.EvictionConfigurationBuilder] (ServerService Thread Pool — 63) ISPN000152: Passivation configured without an eviction policy being selected. Only manually evicted entities will be passivated.
    14:52:04,345 INFO [org.infinispan.configuration.cache.EvictionConfigurationBuilder] (ServerService Thread Pool — 63) ISPN000152: Passivation configured without an eviction policy being selected. Only manually evicted entities will be passivated.
    14:52:04,442 INFO [org.jboss.weld.Version] (MSC service thread 1-4) WELD-000900: 2.3.5 (Final)
    14:52:04,785 INFO [org.jboss.as.jpa] (ServerService Thread Pool — 65) WFLYJPA0010: Starting Persistence Unit (phase 2 of 2) Service ‘EmployeeApp.war#EmployeeApp’
    14:52:04,919 INFO [org.jboss.as.clustering.infinispan] (ServerService Thread Pool — 63) WFLYCLINF0002: Started client-mappings cache from ejb container
    14:52:05,253 ERROR [stderr] (ServerService Thread Pool — 65) Tue Nov 21 14:52:05 EST 2017 WARN: Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false’. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

    14:52:05,398 WARN [org.jboss.jca.core.connectionmanager.pool.strategy.OnePool] (ServerService Thread Pool — 65) IJ000604: Throwable while attempting to get a new connection: null: javax.resource.ResourceException: IJ031084: Unable to create connection
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:345)
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:352)
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:287)
    at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.createConnectionEventListener(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:1320)
    at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.getConnection(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:496)
    at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getSimpleConnection(AbstractPool.java:617)
    at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getConnection(AbstractPool.java:589)
    at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:590)
    at org.jboss.jca.core.connectionmanager.tx.TxConnectionManagerImpl.getManagedConnection(TxConnectionManagerImpl.java:429)
    at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:747)
    at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:138)
    at org.jboss.as.connector.subsystems.datasources.WildFlyDataSource.getConnection(WildFlyDataSource.java:66)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:254)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:228)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874)
    at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:161)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:121)
    at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:667)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:193)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
    Caused by: java.sql.SQLException: Access denied for user ‘yourUserName’@’localhost’ (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:873)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1710)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1226)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2205)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2236)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2035)
    at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:790)
    at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at

    Reply
  • December 4, 2017 at 4:37 pm
    Permalink

    Very helpful tutorial!

    Do you have any tutorials on how to read the data and display it in the table and how to edit/delete records?

    Thank you very much!

    Reply
  • March 25, 2018 at 6:06 am
    Permalink

    There is another method ? like using @Local, @Remote, ear ….., I am new with EJB and JSF 🙁

    Reply

Leave a Reply

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