Thursday, November 02, 2006

Catching Rollback Exceptions in TopLink Essentials



This post follows up:

Toplink JPA outside EJB3 Container in TomCat 5.5



We just do exactly what advised in OTN Toplink Essentials JPA Reference.
******************************************************************
Modify WEB-INF/classes/DataBean.java and replace methods:
******************************************************************



public void empSelected(ActionEvent actionEvent) {

this.departId =
((Integer)((UIParameter)actionEvent.getComponent().getFacet("extraParameter")).getValue()).intValue();
setEmpModificationResult(" ");
}

// Handling rollback when delete.

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();
}
}

//Handling rollback wnen insert or update.

public void completeEmpUpdate(ActionEvent actionEvent) {

try {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
java.util.Date parsedDate = formatter.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 setEmpModificationResult(String empModificationResult) {
this.empModificationResult = empModificationResult;
}

public String getEmpModificationResult() {
return empModificationResult;
}




***************************************
Add to the bottom of employee.jsp:-
***************************************



<f:verbatim>
<hr/>
</f:verbatim>
<h:outputText value="#{dataBean.empModificationResult}"/>




Now attempt to violate primary key "empno" when inserting record
into table scott.emp won't crash apps and will display message:-








In case of success we get message: