Monday, October 30, 2006

JPA outside EJB3 Container in TomCat 5.5



Web Application described bellow uses JSF for presentation layer,
methods for data management are encapsulated into JSF Managed
Beans and utilize JPA invokes Entity Manager. Persistence
layer is done with entity beans (Toplink Essentials).
Writing code for DataBean.java and JSF pages we follow Gordon Yorke (view [1]).
Basic explanation how to create entity beans for database tables (persistence layer) may be found in [1],[2],[3].

Main screen displays Dept table from scott’s schema. For each department "Employee" button displays records of all employees for selected department on the next page. Every employee record may be edited (including java.sql.Date type field "hiredate") or removed from scott.emp table.Button "Create new employee" inserts a new employee record for department been selected on the starting page . Button "Back to Departments" forwards back to starting page.


Web Application files layout:-




List of JSF pages:
***************************
File /department.jsp:-
***************************



<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">TOPLINK ESSENTIALS IN TOMCAT 5.5.X</TH></TR>
</TABLE>
<H3>Displaying Dept table from scott's schema</H3>
<h:form>
<h:dataTable value="#{dataBean.depts}"
var="rowVar"
border="1">
<h:column>
<h:outputText value="#{rowVar.deptno}"/>
<f:facet name="header">
<h:outputText value="Depatment"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.dname}"/>
<f:facet name="header">
<h:outputText value="Department name"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.loc}"/>
<f:facet name="header">
<h:outputText value="Location"/>
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Select"/>
</f:facet>
<h:commandButton value="employee"
type="submit"
actionListener="#{dataBean.empSelected}"
action="toEmp">
<f:facet name="extraParameter">
<f:param name="commandButtonParam"
value="#{rowVar.deptno}"/>
</f:facet>
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
<h:message id="errorTag" for="errorTag" showDetail="true"/>
</CENTER></BODY></HTML>
</f:view>




**************************
File /employee.jsp:-
**************************



<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">TOPLINK ESSENTIALS IN TOMCAT 5.5.X</TH></TR>
</TABLE>
<H3>Displaying employees records for department selected </H3>
<h:form>
<h:dataTable value="#{dataBean.empForDept}"
var="rowVar"
border="1">
<h:column>
<h:outputText value="#{rowVar.empno}"/>
<f:facet name="header">
<h:outputText value="Number"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.ename}"/>
<f:facet name="header">
<h:outputText value="Last Name"/>
</f:facet>
</h:column>
<h:column>
<f:verbatim>$</f:verbatim>
<h:outputText value="#{rowVar.sal}"/>
<f:facet name="header">
<h:outputText value="Salary"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.mgr}"/>
<f:facet name="header">
<h:outputText value="Manager ID"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.hiredate}"/>
<f:facet name="header">
<h:outputText value="Date of hire"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.deptno}"/>
<f:facet name="header">
<h:outputText value="Department"/>
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Select"/>
</f:facet>
<h:commandButton value="Update"
type="submit"
actionListener="#{dataBean.empUpdate}"
action="toEntry">
<f:facet name="extraParameter">
<f:param name="commandButtonParam"
value="#{rowVar.empno}"/>
</f:facet>
</h:commandButton>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Remove"/>
</f:facet>
<h:commandButton value="Remove"
type="submit"
actionListener="#{dataBean.empRemove}"
action="erase">
<f:facet name="extraParameter">
<f:param name="commandButtonParam"
value="#{rowVar.empno}"/>
</f:facet>
</h:commandButton>
</h:column>
</h:dataTable>
<f:verbatim>
<hr/>
</f:verbatim>
<h:panelGroup style="vertical-align:middle;">
<h:commandButton value="Create New Employee"
type="submit"
actionListener="#{dataBean.createNewEmpAct}"
action="toEntry"/>
<h:outputText value=" "/>
<h:commandButton value="Back to Departments"
action="Back"/>
</h:panelGroup>
<f:verbatim>
<hr/>
</f:verbatim>
<h:outputText value="#{dataBean.empModificationResult}"/>
</h:form>
</CENTER></BODY></HTML>
</f:view>




**************************
File /entryEmp.jsp:-
**************************



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=windows-1252"/>
<title>Product</title>
</head>
<body>
<h:form>
<h:panelGrid columns="1" style="text-align:center;">
<h:panelGrid columns="2">
<h:outputText value="Employee Number"/>
<h:inputText value="#{dataBean.currentEmp.empno}"/>
<h:outputText value="Employee Name"/>
<h:inputText value="#{dataBean.currentEmp.ename}"/>
<h:outputText value="Employee MGR"/>
<h:inputText value="#{dataBean.currentEmp.mgr}"/>
<h:outputText value="Hire Date"/>
<h:inputText value="#{dataBean.hrString}"/>
<h:outputText value="Salary"/>
<h:inputText value="#{dataBean.currentEmp.sal}"/>
</h:panelGrid>
<f:verbatim>
<hr/>
</f:verbatim>
<h:panelGroup>
<h:commandButton value="#{dataBean.empEntryOperation}"
action="result"
actionListener="#{dataBean.completeEmpUpdate}"
style="text-align:center;"/>
<h:commandButton value="Cancel"
action="cancel"
style="text-align:center;"/>
</h:panelGroup>
</h:panelGrid>
</h:form>
</body>
</html>
</f:view>




******************************************
File ./WEB-INF/classes/DataBean.java
******************************************



package dstu.net;

import javax.persistence.*;
import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.component.UIParameter;
import javax.faces.event.ActionEvent;
import java.util.Collection;
import javax.persistence.Query;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.lang.Exception;



import dstu.net.Emp;
import dstu.net.Dept;

public class DataBean {

protected int departId;

protected dstu.net.Emp currentEmp;
protected JPAResourceBean jpaResourceBean;
protected static final String UPDATE_OPERATION = "Update";
protected static final String CREATE_OPERATION = "Create";
protected String empEntryOperation;
protected String empModificationResult;
protected static final String SUCCESS = "Success";
protected String hrString ;
protected java.sql.Date hrDate;


public DataBean() {}

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");


public dstu.net.Emp[] getEmps(){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try {
Collection tempCollection =
em.createNamedQuery("selectEmps").getResultList();
return(tempCollection.toArray(new dstu.net.Emp[tempCollection.size()]));
} finally { em.close();}
}


public dstu.net.Dept[] getDepts(){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try {
Collection tempCollection =
em.createNamedQuery("selectDepts").getResultList();
return(tempCollection.toArray(new dstu.net.Dept[tempCollection.size()]));
} finally { em.close();}
}

public void empSelected(ActionEvent actionEvent) {
this.departId =
((Integer)((UIParameter)actionEvent.getComponent().getFacet("extraParameter")).getValue()).intValue();
setEmpModificationResult(" ");
}

public dstu.net.Emp[] getEmpForDept(){
try {
Collection tempCollection = getEmpForDepartment(this.departId);
return tempCollection.toArray(new dstu.net.Emp[tempCollection.size()]);
} catch (RuntimeException ex){
handleException(ex);
}
return new dstu.net.Emp[0];
}

public Collection getEmpForDepartment(int deptId){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try{
Query query = em.createNamedQuery("empForDepartment");
query.setParameter("deptId", deptId);
return query.getResultList();
} finally { em.close();}
}


public void empUpdate(ActionEvent actionEvent){
Integer empId = ((Integer)((UIParameter)actionEvent.getComponent().getFacet("extraParameter")).getValue()).intValue();
try {
this.currentEmp = getEmpById(empId);
// Converting java.sql.Date to String for editing.
hrString=sdf.format(this.currentEmp.hiredate);
this.empEntryOperation = UPDATE_OPERATION;
} catch (RuntimeException ex) { handleException(ex); }
}

public dstu.net.Emp getEmpById(int empId){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try{
return em.find(dstu.net.Emp.class, empId);
}finally{
em.close();
}
}

public void empRemove(ActionEvent actionEvent){
Integer empId = ((Integer)((UIParameter)actionEvent.getComponent().getFacet("extraParameter")).getValue()).intValue();
try {
requestEmpRemove(empId);
this.empModificationResult = "Success";
}catch (OptimisticLockException ex){
this.empModificationResult = "Failed to " + this.empEntryOperation.toLowerCase() + "Employee status has changed since last viewed";
}catch (Exception ex){
this.empModificationResult = "Failed to " + this.empEntryOperation.toLowerCase() + "An unexpected Error ocurred: " +ex.toString();
}
}


public void requestEmpRemove(int empId){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try{
em.getTransaction().begin();
dstu.net.Emp employee = em.find(dstu.net.Emp.class, empId);
em.remove(employee);
em.getTransaction().commit();
}finally{
em.close();
}
}


public void updateEmployee (int empId,String newName,int newMgr, long newSalary,Date newDate){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try{
em.getTransaction().begin();
dstu.net.Emp employee = em.find(dstu.net.Emp.class, empId);
employee.setEname(newName);
employee.setMgr(newMgr);
employee.setSal(newSalary);
employee.setHiredate(newDate);
em.getTransaction().commit();
}finally{
em.close();
}
}


public void createNewEmpAct(ActionEvent actionEvent){
try {
setHrString(" ");
this.currentEmp = new dstu.net.Emp();
this.currentEmp.setDeptno(this.departId);
this.empEntryOperation = CREATE_OPERATION;
} catch (RuntimeException ex) { handleException(ex);}

}


public void completeEmpUpdate(ActionEvent actionEvent) {

try {
// Converting string to java.sql.Date
java.util.Date parsedDate = sdf.parse(hrString);
this.currentEmp.setHiredate(new java.sql.Date(parsedDate.getTime()));
}
catch (Exception err) { }

try{

if (this.empEntryOperation == this.UPDATE_OPERATION){

updateEmployee(this.currentEmp.getEmpno(),this.currentEmp.getEname(),this.currentEmp.getMgr(),this.currentEmp.getSal(), this.currentEmp.getHiredate());

} else {

createNewEmp(this.currentEmp);

}

this.empModificationResult = SUCCESS;

}catch (RollbackException ex){
if (ex.getCause() instanceof OptimisticLockException){
this.empModificationResult = "Failed to " + this.empEntryOperation.toLowerCase() + "Employee status has changed since last viewed";
} else {
this.empModificationResult = "Failed to " + this.empEntryOperation.toLowerCase() + " An unexpected Error ocurred: " +ex.toString();
}
} catch (Exception ex) {
this.empModificationResult = "Failed to " + this.empEntryOperation.toLowerCase() + " An unexpected Error ocurred: " +ex.toString();
}
}

public void createNewEmp(dstu.net.Emp emp){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try{
em.getTransaction().begin();
em.persist(emp);
em.getTransaction().commit();
}finally{
em.close();
}
}


public void setCurrentEmp(Emp currentEmp) {
this.currentEmp = currentEmp;
}

public Emp getCurrentEmp() {
return currentEmp;
}

public void setDepartId(int departId) {
this.departId = departId;
}

public int getDepartId() {
return departId;
}

public void setHrString(String hrString) {
this.hrString=hrString;
}

public String getHrString() {
return(hrString);
}

public void setEmpEntryOperation(String empEntryOperation) {
this.empEntryOperation = empEntryOperation;
}

public String getEmpEntryOperation() {
return empEntryOperation;
}

public void setEmpModificationResult(String empModificationResult) {
this.empModificationResult = empModificationResult;
}

public String getEmpModificationResult() {
return empModificationResult;
}

public void setJpaResourceBean(JPAResourceBean jpaResourceBean) {
this.jpaResourceBean = jpaResourceBean;
}

public JPAResourceBean getJpaResourceBean() {
return jpaResourceBean;
}

//This method is used to handle exceptions and display cause to user.
protected void handleException (RuntimeException ex){
StringBuffer details = new StringBuffer();
Throwable causes = ex;
while(causes.getCause() != null){
details.append(ex.getMessage());
details.append(" Caused by:");
details.append(causes.getCause().getMessage());
causes = causes.getCause();
}
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), details.toString());
FacesContext.getCurrentInstance().addMessage("errorTag", message);
}
}


*******************************************************************************
File ./WEB-INF/classes/JPAResourceBean.java (author Gordon Yorke)
*******************************************************************************



package dstu.net;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
* This is an Application Scoped bean that holds the JPA
* EntityManagerFactory. By making this bean Applciation scoped the
* EntityManagerFactory resource will be created only once for the application
* and cached here.
*
*@author Gordon Yorke
*/
public class JPAResourceBean {
protected EntityManagerFactory emf;
public EntityManagerFactory getEMF (){
if (emf == null){
emf = Persistence.createEntityManagerFactory("default",new java.util.HashMap());
}
return emf;
}
}




*************************************
File ./WEB-INF/classes/Emp.java:-
*************************************



package dstu.net;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.OneToOne;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQuery;
import javax.persistence.NamedQueries;
import javax.persistence.Version;
import java.sql.Date;
import javax.persistence.Table;

@Entity
@Table(name="emp")
@NamedQueries({
@NamedQuery(
name="selectEmps",
query="SELECT i FROM Emp i"
),
@NamedQuery(
name="empForDepartment",
query="SELECT o FROM Emp o WHERE o.deptno = :deptId"
)
})



public class Emp {

@Id
protected int empno;

protected String ename;
protected String job;
protected int mgr;
protected Date hiredate;
protected long sal;
protected long comm;
protected int deptno;

public void setEmpno(int empno) {
this.empno=empno;
}
public int getEmpno() {
return empno;
}

public void setEname(String ename) {
this.ename=ename;
}
public String getEname() {
return ename;
}

public void setJob(String job) {
this.job=job;
}

public String getJob() {
return job;
}

public void setMgr(int mgr) {
this.mgr=mgr;
}
public int getMgr() {
return mgr;
}

public void setHiredate(Date hiredate) {
this.hiredate=hiredate;
}
public Date getHiredate() {
return hiredate;
}

public void setSal(long sal) {
this.sal=sal;
}

public long getSal() {
return sal;
}

public void setComm(long comm) {
this.comm=comm;
}

public long getComm() {
return comm;
}


public void setDeptno(int deptno) {
this.deptno=deptno;
}

public int getDeptno() {
return deptno;
}
}




*************************************
File ./WEB-INF/classes/Dept.java:-
*************************************



package dstu.net;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.OneToOne;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQuery;
import javax.persistence.NamedQueries;
import javax.persistence.Version;
import java.sql.Date;
import javax.persistence.Table;

@Entity
@Table(name="dept")

@NamedQueries({
@NamedQuery(
name="deptForEmployee",
query="SELECT i FROM Dept i WHERE i.deptno = :deptId"
),

@NamedQuery(
name="selectDepts",
query="SELECT o FROM Dept o "
) })

public class Dept {

@Id
protected int deptno;
protected String dname;
protected String loc;

public void setDeptno(int deptno) {
this.deptno=deptno;
}
public int getDeptno() {
return deptno;
}

public void setDname(String dname) {
this.dname=dname;
}
public String getDname() {
return dname;
}

public void setLoc(String loc) {
this.loc=loc;
}

public String getLoc() {
return loc;
}

}




***********************************
File WEB-INF/faces-config.xml:-
***********************************



<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<faces-config>
<managed-bean>
<managed-bean-name>jpaResourceBean</managed-bean-name>
<managed-bean-class>dstu.net.JPAResourceBean</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
</managed-bean>

<managed-bean>
<managed-bean-name>dataBean</managed-bean-name>
<managed-bean-class>
dstu.net.DataBean
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>jpaResourceBean</property-name>
<value>#{jpaResourceBean}</value>
</managed-property>
</managed-bean>

<navigation-rule>
<from-view-id>/department.jsp</from-view-id>
<navigation-case>
<from-outcome>toEmp</from-outcome>
<to-view-id>/employee.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/employee.jsp</from-view-id>
<navigation-case>
<from-outcome>Back</from-outcome>
<to-view-id>/department.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/employee.jsp</from-view-id>
<navigation-case>
<from-outcome>toEntry</from-outcome>
<to-view-id>/entryEmp.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/entryEmp.jsp</from-view-id>
<navigation-case>
<from-outcome>result</from-outcome>
<to-view-id>/employee.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/employee.jsp</from-view-id>
<navigation-case>
<from-outcome>erase</from-outcome>
<to-view-id>/employee.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/entryEmp.jsp</from-view-id>
<navigation-case>
<from-outcome>cancel</from-outcome>
<to-view-id>/employee.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>




**********************************************************
File ./WEB-INF/classes/META-INF/persistence.xml
**********************************************************



<persistence 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 persistence_1_0.xsd" version="1.0">
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<provider>
oracle.toplink.essentials.PersistenceProvider
</provider>
<class>dstu.net.Emp</class>
<class>dstu.net.Dept</class>
<properties>
<property name="toplink.logging.level" value="FINE"/>
<property name="toplink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
<property name="toplink.jdbc.url" value="jdbc:oracle:thin:@192.168.0.100:1522:jdevdbs"/>
<property name="toplink.jdbc.password" value="tiger"/>
<property name="toplink.jdbc.user" value="scott"/>
</properties>
</persistence-unit>
</persistence>






*************************
Runtime snapshots:-
*************************















Attempt to violate primary constraint "empno_PK" when inserting record
into table scott.emp will display message:-








In the case of success we get message:




References.


1. OTN JPA Reference
2. Toplink Named Queries in TomCat 5.5 (2)
3.Toplink Named Queries in TomCat 5.5 (1)