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.

Pre-requisites:

Preparations:

  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)
    values('Katrina','Kaif','1020131');
    insert into contact(first_name,last_name,phone_no)
    values('Kareena','Kapoor','10480131');
    insert into contact(first_name,last_name,phone_no)
    values('Prachi','desai','1045431');
  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
      </Resource>
      

      [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 java.io.Serializable;
    import javax.persistence.*;
    /**
    * The persistent class for the CONTACT database table.
    *
    */
    @Entity
    public class Contact implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int contactid;
    @Column(name="FIRST_NAME")
    private String firstName;
    @Column(name="LAST_NAME")
    private String lastName;
    @Column(name="PHONE_NO")
    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="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="pu2">
    <jta-data-source>testDS</jta-data-source>
    <class>com.mahendra.models.Contact</class>
    </persistence-unit></persistence>
  12. Create new Java Class [It’s actually a session bean]
    package com.mahendra.services;
    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 {
    @PersistenceContext(unitName="pu2")
    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();
    cn.setFirstName(firstName);
    cn.setLastName(lastName);
    cn.setPhoneNo(phone);
    em.persist(cn);
    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.io.Serializable;
    import java.util.List;
    import javax.ejb.EJB;
    import javax.faces.bean.*;
    import com.mahendra.models.Contact;
    import com.mahendra.services.ContactService;
    /**
    * Backing Bean for JSF pages. <br/>
    * This bean has reference of <code>ContactService</code> using @EJB Annotation
    * @author Mahendra Shinde
    *
    */
    @ManagedBean
    @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) {
    this.phone = phone;
    }
    
    /**
    * Call save method on ContactService and update list
    * @return Outcome for JSF Navigation
    */
    
    public String addContact(){
    service.save(firstName,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:
    <navigation-rule>
    <display-name>index.xhtml</display-name>
    <from-view-id>/index.xhtml</from-view-id>
    <navigation-case>
    <from-outcome>success</from-outcome>
    <to-view-id>/list.xhtml</to-view-id>
    <redirect />
    </navigation-case>
    </navigation-rule>
  15. Create “index.xhtml” inside “WebContents” folder:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html" ><h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>Home page</title>
    </h:head><h:body>
    <h:form>
    <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="#{contactBean.phone}"/>
    <h:commandButton value="submit" action="#{contactBean.addContact}"/>
    </h:form>
    </h:body>
    </html>
  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"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"><h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>List of Contacts</title>
    </h:head><h:body>
    <h2>My Contacts</h2>
    <h:dataTable value="#{contactBean.contactList}" var="c">
    <h:column>
    <f:facet name="header">Contact #</f:facet>
    #{c.contactid}
    </h:column>
    <h:column>
    <f:facet name="header">First Name</f:facet>
    #{c.firstName}
    </h:column>
    <h:column>
    <f:facet name="header">Last Name</f:facet>
    #{c.lastName}
    </h:column>
    <h:column>
    <f:facet name="header">Phone #</f:facet>
    #{c.phoneNo}
    </h:column>
    </h:dataTable>
    </h:body>
    </html>
    
  17. Now, run your application on Apache TomEE
    [Make sure Apache Derby is Still running]
    test url : http://localhost:8080/TestApp2/faces/index.xhtml
Advertisements