JPA with JSF and Session Bean on Apache TomEE

Even though I am going to use Apache TomEE (Tomcat 7 +OpenEJB + OpenJPA), It will work on ANY JAVA EE 6 (Web Profile) Compatible Application server.

In this example I am trying to demonstrate how to use Apache TomEE for developing an Application made with JPA + EJB + JSF.

This demo application uses Apache derby (JavaDB) database which comes free of cost with JDK 7 downloads. You may use any other database with tiny changes to some configuration files.



  1. Create Database [You may skip this if you are using any other database]
  2. Open Terminal / MS DOS prompt
  3. goto JAVA_HOME (on windows: C:\Program Files\Java\jdk1.7.x_xx)
  4. goto db\bin
  5. use command:    startNetworkServer
  6. open eclipse → create new workspace → using Data source Explorer connect to Derby connection properties:
    url: jdbc:derby://localhost:1527/sample;create=true
    username: app
    password: app
  7. Open SQL Scrapbook → execute following queries:
    create table Contact(
    contactId int primary key generated always as identity,
    first_name varchar(25),
    last_name varchar(35),
    phone_no varchar(15)
    insert into contact(first_name,last_name,phone_no)
    insert into contact(first_name,last_name,phone_no)
    insert into contact(first_name,last_name,phone_no)
  8. Add server to current workspace [You may skip this if you know how to do it]
    1. Open “Servers” view → Right click → New → Server → Apache: Apache Tomcat 7
    2. Click on “Browse” and provide path to your TomEE folder → Finish
    3. Double click on Apache Tomcat 7 inside “Servers” view
    4. Change “Server Locations” to “Use Tomcat Installation”

    [This must be done when BEFORE ANY PROJECT IS ADDED TO TOMCAT]

  9. Create New Dynamic Web Project
    1. New–> Dynamic Web Project → Name: TestApp2
    2. Click on “Modify” to change Configuration
    3. Select “JPA” and “JSF” project facets

    [ One Best thing about TomEE, it comes bundled with OpenJPA and JSF so forget about downloading and copying required JARs into your application’s WEB-INF/lib]

    • Create JNDI DataSource [MUST READ]
    • Stop Apache TomEE (If already started)
    • Open TomEE’s “conf” folder → Open “tomee.xml” in any text editor
    • add following resource definition:
      <Resource id="testDS" type="DataSource">
      JdbcDriver org.apache.derby.jdbc.ClientDriver
      JdbcUrl jdbc:derby://localhost:1527/sample
      UserName app
      Password app

      [No, I have not made any mistake there!!]

    • Save & close this file
    • Add following “datasource” in persistence.xml testDS
  10. Create JPA entity for Table “Contact”
    package com.mahendra.models;
    import javax.persistence.*;
    * The persistent class for the CONTACT database table.
    public class Contact implements Serializable {
    private static final long serialVersionUID = 1L;
    private int contactid;
    private String firstName;
    private String lastName;
    private String phoneNo;
    public Contact() {
    }public int getContactid() {
    return this.contactid;
    }public void setContactid(int contactid) {
    this.contactid = contactid;
    }public String getFirstName() {
    return this.firstName;
    public void setFirstName(String firstName) {
    this.firstName = firstName;
    public String getLastName() {
    return this.lastName;
    public void setLastName(String lastName) {
    this.lastName = lastName;
    public String getPhoneNo() {
    return this.phoneNo;
    public void setPhoneNo(String phoneNo) {
    this.phoneNo = phoneNo;
  11. Your modified persistence.xml should look like this:
    <persistence version="2.0"
    xmlns="" xmlns:xsi="" xsi:schemaLocation="">
    <persistence-unit name="pu2">
  12. Create new Java Class [It’s actually a session bean]
    import java.util.List;
    import javax.ejb.LocalBean;
    import javax.ejb.Stateless;
    import javax.persistence.*;
    import com.mahendra.models.Contact;/**
    * Stateless Session bean to save and/or list all contacts<br/>
    * We are using Java EE 6 Web Profile, so we don't need EJB Project
    * to create Stateless Session Beans!<br>
    * This is a CMT (Again thanks to Apache TomEE, It CAN make JTA data-sources
    * unlike plain Apache Tomcat which is just a Servlet Container)
    * @author Mahendra Shinde
    */@Stateless @LocalBean
    public class ContactService {
    private EntityManager em;
    public ContactService(){
    System.out.println("Instance created for Contact Service");
    * method to create new record using provided arguments<br/>
    * TransactionAttribute for this method is REQUIRED (default)
    * @param firstName
    * @param lastName
    * @param phone
    public void save(String firstName,String lastName,String phone){
    Contact cn = new Contact();
    System.out.println("Record saved");
    * method to load all contacts from database
    * @return List of all contacts
    public List<Contact> loadAll(){
    List<Contact> list = null;
    Query q =em.createQuery("select c from Contact c");
    list = q.getResultList();
    return list;
  13. Create Managed Bean (Backing bean) for JSF pages:
    package com.mahendra.beans;
    import java.util.List;
    import javax.ejb.EJB;
    import javax.faces.bean.*;
    import com.mahendra.models.Contact;
    * Backing Bean for JSF pages. <br/>
    * This bean has reference of <code>ContactService</code> using @EJB Annotation
    * @author Mahendra Shinde
    @SessionScopedpublic class ContactBean implements Serializable {
    @EJB private ContactService service;
    private String firstName,lastName,phone;
    private List<Contact> contactList;
    public ContactBean() {
    }public String getFirstName() {
    return firstName;
    public void setFirstName(String firstName) {
    this.firstName = firstName;
    public String getLastName() {
    return lastName;
    public void setLastName(String lastName) {
    this.lastName = lastName;
    public String getPhone() {
    return phone;
    public void setPhone(String phone) { = phone;
    * Call save method on ContactService and update list
    * @return Outcome for JSF Navigation
    public String addContact(){,lastName,phone);
    contactList = service.loadAll();
    return "success";
    public List<Contact> getContactList() {
    return contactList;
    public void setContactList(List<Contact> contactList) {
    this.contactList = contactList;
  14. Add following navigation rule inside “faces-config.xml” file:
    <redirect />
  15. Create “index.xhtml” inside “WebContents” folder:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
    <html xmlns=""
    xmlns:h="" ><h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>Home page</title>
    <h:outputText value="First name :" />
    <h:inputText value="#{contactBean.firstName}"/>
    <h:outputText value="Last name :" />
    <h:inputText value="#{contactBean.lastName}"/>
    <h:outputText value="Phone :" />
    <h:inputText value="#{}"/>
    <h:commandButton value="submit" action="#{contactBean.addContact}"/>
  16. create “list.xhtml” inside “WebContents” folder
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    <html xmlns=""
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>List of Contacts</title>
    <h2>My Contacts</h2>
    <h:dataTable value="#{contactBean.contactList}" var="c">
    <f:facet name="header">Contact #</f:facet>
    <f:facet name="header">First Name</f:facet>
    <f:facet name="header">Last Name</f:facet>
    <f:facet name="header">Phone #</f:facet>
  17. Now, run your application on Apache TomEE
    [Make sure Apache Derby is Still running]
    test url : http://localhost:8080/TestApp2/faces/index.xhtml

Creating Seam2 ejb application on eclipse using Seam Tools and JBoss AS

Creating new Seam 2 EJB application on JBoss AS 5.1 using eclipse indigo.

My Configuration:
eclipse (indigo) with JBoss Tools installed at d:\seam-dev\eclipse
<JBOSS-AS>         JBoss AS 5.1.0 installed at D:\seam-dev\jboss-5.1.0.GA
<SEAM-HOME>      D:\jboss-seam-2.2.2.Final

create new workspace for eclipse
add Jboss AS 5.1 from above location to workspace (use “default” server profile)
copy hsqldb.jar from <SEAM-HOME>\lib to <JBOSS-AS>\lib folder.

Steps to create EMPTY EJB application :
1    Create new “Seam Web Project” with name Test-ent1 –> use JBoss AS 5.1 as server with default settings –>next

2    Use libaries provided by Runtime for JSF –>next

3    Application type: EAR with two modules : test-ent1-ejb and test-ent1-ear

4    Database connection : create new HSQL DB connection to database (empty database)
5    finish to create application.

6    Click on run to Run created application on JBoss AS 5.1 (data source first!  + test-ent1.ear)

NOTE: “war” module is part of “ear” so no need to run “Test-ent1” (war module) directly on server!
7    Incase if you got 404 error, just wait for server to finish loading (see server log in output panel) and then refresh page.

Steps to add “Entities”:
1    New –> New Seam
Entity : entity name: person

2    Open “” , add following two fields

 private String address;
 private String contact;

3    Generate getters and setters for them.
4    Open person.xhtml (from test-ent1 project), add follwoing lines just after “</s:decorate>”

 <s:decorate id="addressField" template="layout/edit.xhtml">
 <ui:define name="label">Address</ui:define>
 <h:inputText id="address" required="true"
 <s:decorate id="contactField" template="layout/edit.xhtml">
 <ui:define name="label">Contact Number</ui:define>
 <h:inputText id="contact" required="true"

5    Open personList.xhtml page, change columns (inside <h:dataTable> )to following:

 <f:facet name="header">Id</f:facet>
 <f:facet name="header">Name</f:facet>
 <f:facet name="header">Address</f:facet>
 <f:facet name="header">Phone number</f:facet>
 <s:link id="person"
 <f:param name="personId"

6    Remove application from Server.

7    add following line inside “layout\menu.xhtml” to create menu item (only if not generated by eclipse)

 <s:link id="menuPersonListId" view="/personList.xhtml" value="Person" propagation="none"/>

8    Run application (causing un-deploy and then deploy)

Convert Seam2 example to eclipse project

Convert Seam example applications to eclipse Project

Project folder structure in seam 2. x examples is different than folder structure used by seam tools project.(Project created in eclipse using JBoss Tools).

Seam (JBoss) Tools  project:

  1. src/
    1. hot/
      1. <ALL-Action-classes>
      2. <other-classes-for-HOT-deployment>
      3. <empty file>
    2. main/
      1. <ALL-entity/model-classes>
      2. components.propeties
      3. import.sql (Database DDL and DML statements)
      5. security.drl
      6. <empty file>
      7. META-INF/
        • persistence.xml
  2. WebContent/
    1. css/
    2. img/
    3. META-INF/
      1. context.xml
    4. <All-xhtml-pages>
    5. <All-xhtml.xml-pages>
    6. WEB-INF/
      1. classes/
      2. web.xml
      3. component.xml
      4. faces-config.xml
      5. jboss-web.xml (only for JBoss AS)
      6. pages.xml
  4. <project_name>.launch

Convert “jboss-seam-jpa” example Application to eclipse (Seam) project.

1         Create new “Seam Web Project” à enter name of project “jboss-seam-jpa”

2         accept all details in above screen and press “Next” àNextàNext

3         Disable Library configuration for JSF capabilities (You need to copy all JAR’s manually to Tomcat’s LIB folder) àNext

4         Select (Or add new) JBoss Seam Runtime

  1. Deploy As :                          WAR
  2. Libraries:                             Copy library from Seam Runtime
  3. Database Type:                 Select HSQL
  4. Connection Profile:         create new Connection profile for HSQL DB
  5. DB Tables already exists in Database: FALSE
  6. Recreate Database tables and data on deploy : TRUE
  7. Package name(session):             org.jboss.seam.example.jpa
  8. Package name(Entity):                 org.jboss.seam.example.jpa
  9. Create Test Project:                      NO

5         Now click finish to generate Project

6         Now create new Package “org.jboss.seam.example.jpa” under source folder “src/main”

7         Delete auto-created “” from src/hot

8         Open <SEAM-HOME> /LIB folder, copy following files:


  1. hibernate-core.jar
  2. hibernate-annotations.jar
  3. hibernate-commons-annotations.jar
  4. hibernate-entitymanager.jar
  5. hibernate-search.jar
  6. lucene.jar (ONLY FOR SEAM VER = 2.2.2.FINAL)
  7. hibernate-validator.jar

JSF 1.2:

  1. jsf-api.jar
  2. jsf-impl.jar
  3. jsf-facelets.jar


  1. jta.jar
  2. persistence-api.jar
  3. ejb3-persistence.jar (used by hibernate+JPA)

Logging for Hibernate and Seam:

  1. log4j.jar
  2. slf4j-api.jar
  3. slf4j-log4j12.jar
  4. (for debug messages)

Database Driver

1    hsqldb.jar


  • drools-api.jar
  • drools-compiler.jar
  • drools-core.jar
  • drools-decisiontables.jar
  • drools-templates.jar

9         paste them all inside <TOMCAT-HOME>/LIB

10     Open <SEAM-HOME>/examples/jpa folder

11     open “src/org/jboss/seam/example/jpa” folder

12     Copy all java classes which ends with “Action”

13     inside eclipse goto src/hot/org/jboss/seam/example/jpa folder à delete existsing classes

14     inside eclipse, goto src/hot/org/jboss/seam/example/jpa folder à paste

15     copy remaining files from “src/org/jboss/seam/example/jpa” folder to src/main/org/jboss/seam/example/jpa folder

16     inside eclipse, delete all .xhtml and .xml files from WebContent folder, delete “css” , “img” & “layout” folders

17     Open “VIEW” folder of examples /jpa àcopy all files

18     inside eclipse, paste them all in “WebContent” folder (Overwrite duplicates)

19     Open “Resource-tomcat” folder from your examples/jpa

20     copy import.sql file

21     inside eclipseà paste it in src/main

22     Copy “persistence.xml” from resource-tomcat/META-INF to eclipse project’s src/main/META-INF

23     Copy “context.xml” from resource-tomcat/META-INF to eclipse project’s WebContent/META-INF

24     copy “WEB-INF” folder from resources-tomcat to eclipse project’s WebContent folder (Overwrite existsing WEB-INF)