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