Error » Certification & Programming center Error !! » Programming tutorials » TopLink JPA outside EJB3 Container in TomCat 5.5

Programming tutorials All Knowledge Info and links to posted here

Post New Thread Reply
  TopLink JPA outside EJB3 Container in TomCat 5.5
LinkBack Thread Tools Display Modes
Old 03-Jan-2007, 10:23 PM   #1 (permalink)
Administrator
 
Anilrgowda's Avatar

Posts: 18,715
Join Date: Jan 2006
Rep Power: 10 Anilrgowda is on a distinguished road

IM:
Default TopLink JPA outside EJB3 Container in TomCat 5.5

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>
<hutputText value="#{rowVar.deptno}"/>
<f:facet name="header">
<hutputText value="Depatment"/>
</f:facet>
</h:column>
<h:column>
<hutputText value="#{rowVar.dname}"/>
<f:facet name="header">
<hutputText value="Department name"/>
</f:facet>
</h:column>
<h:column>
<hutputText value="#{rowVar.loc}"/>
<f:facet name="header">
<hutputText value="Location"/>
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<hutputText value="Select"/>
</f:facet>
<h:commandButton value="employee"
type="submit"
actionListener="#{dataBean.empSelected}"
action="toEmp">
<f:facet name="extraParameter">
<faram 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>


</PRE>


**************************
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>
<hutputText value="#{rowVar.empno}"/>
<f:facet name="header">
<hutputText value="Number"/>
</f:facet>
</h:column>
<h:column>
<hutputText value="#{rowVar.ename}"/>
<f:facet name="header">
<hutputText value="Last Name"/>
</f:facet>
</h:column>
<h:column>
<f:verbatim>$</f:verbatim>
<hutputText value="#{rowVar.sal}"/>
<f:facet name="header">
<hutputText value="Salary"/>
</f:facet>
</h:column>
<h:column>
<hutputText value="#{rowVar.mgr}"/>
<f:facet name="header">
<hutputText value="Manager ID"/>
</f:facet>
</h:column>
<h:column>
<hutputText value="#{rowVar.hiredate}"/>
<f:facet name="header">
<hutputText value="Date of hire"/>
</f:facet>
</h:column>
<h:column>
<hutputText value="#{rowVar.deptno}"/>
<f:facet name="header">
<hutputText value="Department"/>
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<hutputText value="Select"/>
</f:facet>
<h:commandButton value="Update"
type="submit"
actionListener="#{dataBean.empUpdate}"
action="toEntry">
<f:facet name="extraParameter">
<faram name="commandButtonParam"
value="#{rowVar.empno}"/>
</f:facet>
</h:commandButton>
</h:column>
<h:column>
<f:facet name="header">
<hutputText value="Remove"/>
</f:facet>
<h:commandButton value="Remove"
type="submit"
actionListener="#{dataBean.empRemove}"
action="erase">
<f:facet name="extraParameter">
<faram name="commandButtonParam"
value="#{rowVar.empno}"/>
</f:facet>
</h:commandButton>
</h:column>
</h:dataTable>
<f:verbatim>
<hr/>
</f:verbatim>
<hanelGroup style="vertical-align:middle;">
<h:commandButton value="Create New Employee"
type="submit"
actionListener="#{dataBean.createNewEmpAct}"
action="toEntry"/>
<hutputText value=" "/>
<h:commandButton value="Back to Departments"
action="Back"/>
</hanelGroup>
<f:verbatim>
<hr/>
</f:verbatim>
<hutputText value="#{dataBean.empModificationResult}"/>
</h:form>
</CENTER></BODY></HTML>
</f:view>


</PRE>


**************************
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>
<hanelGrid columns="1" style="text-align:center;">
<hanelGrid columns="2">
<hutputText value="Employee Number"/>
<h:inputText value="#{dataBean.currentEmp.empno}"/>
<hutputText value="Employee Name"/>
<h:inputText value="#{dataBean.currentEmp.ename}"/>
<hutputText value="Employee MGR"/>
<h:inputText value="#{dataBean.currentEmp.mgr}"/>
<hutputText value="Hire Date"/>
<h:inputText value="#{dataBean.hrString}"/>
<hutputText value="Salary"/>
<h:inputText value="#{dataBean.currentEmp.sal}"/>
</hanelGrid>
<f:verbatim>
<hr/>
</f:verbatim>
<hanelGroup>
<h:commandButton value="#{dataBean.empEntryOperation}"
action="result"
actionListener="#{dataBean.completeEmpUpdate}"
style="text-align:center;"/>
<h:commandButton value="Cancel"
action="cancel"
style="text-align:center;"/>
</hanelGroup>
</hanelGrid>
</h:form>
</body>
</html>
</f:view>


</PRE>


******************************************
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<DSTU.NET.EMP> 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<DSTU.NET.DEPT> 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<DSTU.NET.EMP> 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<DSTU.NET.EMP> 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.cur rentEmp.getEname(),this.currentEmp.getMgr(),this.c urrentEmp.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("erro rTag", message);
}
}
</DSTU.NET.EMP></DSTU.NET.EMP></DSTU.NET.DEPT></DSTU.NET.EMP></PRE>


************************************************** *****************************
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",n ew java.util.HashMap());
}
return emf;
}
}


</PRE>


*************************************
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;
}
}


</PRE>


*************************************
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;
}

}


</PRE>


***********************************
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>


</PRE>


************************************************** ********
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="jdbcracle:thin:@192.168.0.100:1522:jdevdb s"/>
<property name="toplink.jdbc.password" value="tiger"/>
<property name="toplink.jdbc.user" value="scott"/>
</properties>
</persistence-unit>
</persistence>


</PRE>




*************************
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:






Anilrgowda is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit!
Reply With Quote
   


   
Post New Thread Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump


All times are GMT -8. The time now is 11:10 AM.

Powered by vBulletin® Version 3.7.2
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0

DMCA Policy

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228