Show TOC Start of Content Area

Procedure documentation Implementing the Business Logic  Locate the document in its SAP Library structure

Use

According to the J2EE standard, the Web front end should not directly access the persistence layer. Typically, a J2EE application should use a façade session bean for the communication between the Web components and the JDO instances. In this example, the business logic is implemented in a plain Java class for simplicity. The class includes methods that modify the data in the data store using JDO.

Prerequisites

You must have created:

·        The GettingStartedJDOWeb project

·        The temp.persistence.gettingstarted.jdo package

·        The persistence capable classes Employee and Department.

Procedure

       1.      In the J2EE Development perspective, choose GettingStartedJDOWeb project and open its context menu.

       2.      Choose New Java Class. To choose a package for the class, use Browse… next to the Package field, and select temp.persistence.gettingstarted.jdo from the list.

       3.      Enter BusinessLogic as the name of the class. Choose Finish.

       4.      The new Java file is created and opens automatically. Edit its contents as follows:

...

                            a.      The PersistenceManagerFactory (PMF) acts as a factory for PersistenceManagers (PMs) that establish the actual connection to the underlying data store. Therefore, the first thing a JDO application typically does is to acquire a PMF using a JNDI lookup operation.

In the beginning of the class, define a global variable for the PMF reference. Then in the constructor of the class, look up the PMF from the local environment java:comp/env using the JNDI name of the instance jdo/defaultPMF.Cast the object to javax.jdo.PersistenceManagerFactory and assign the value to the variable that you have declared.

Example

public class BusinessLogic {

  

   private PersistenceManagerFactory pmf; // Persistence Manager Factory (PMF)

  

   public BusinessLogic()

   throws NamingException {

  

   // Get the Persistence Manager Factory via JNDI using a reference.

   // (You have to declare this reference within the deployment descriptor.)     

      Context ctx = new InitialContext();

      pmf = (PersistenceManagerFactory) ctx.lookup("java:comp/env/jdo/defaultPMF");

   }

...

 

                            b.      Implement a method that creates a new department by name and ID. The method must first create a new instance of the Department class, which is transient – that is, it is not stored in the database. To make it persistent, you must get a PersistenceManager instance and invoke its makePersistent() method with the new JDO instance as a parameter. Note that the example uses the javax.jdo.Transaction interface for transaction demarcation. Therefore, you must first get a reference to a PM, then start a transaction, and then invoke the makePersistent() method. In the end of the method, you must complete the transaction and close the PM.

Example

public void createDepartment(

   int depId,

   String name)

   throws JDOException {

 

   PersistenceManager pm = null;

   try {

      Department dep = new Department(depId);

      dep.setName(name);

 

      // Get the Persistence Manager (PM)

      // PM manages transactions, the life cycle of objects, etc.

      pm = pmf.getPersistenceManager();

 

      // Start a local transaction.

      Transaction tx = pm.currentTransaction();

      tx.begin();

 

      // Create a new persistent department object

      pm.makePersistent(dep);

      // Insert the new department to the database

      tx.commit();

   }

   finally {

      // Close the Persistence Manager

      if (pm != null && !pm.isClosed()) {

      if (pm.currentTransaction().isActive())

         pm.currentTransaction().rollback();

         pm.close();

      } 

   }

}

 

                            c.      Implement a method that creates a new employee in a given department. The logic is the same as in the createDepartment()method:

Example

public void createEmployee(

   int empId,

   String fName,

   String lName,

   BigDecimal salary,

   int depId)

   throws JDOException {

   PersistenceManager pm = null;

   try {

      Employee emp = new Employee(empId);

      emp.setFirstName(fName);

      emp.setLastName(lName);

      emp.setSalary(salary);

 

// Obtain the related department object. We assume the department exists.

      pm = pmf.getPersistenceManager();

      Department department = (Department)pm.getObjectById(new Department.Id(depId), false);

 

      // Start a local transaction

      Transaction tx = pm.currentTransaction();

      tx.begin();

 

      // Establish a relationship between the employee and the department

      emp.setDepartment(department);

      department.addEmployee(emp); 

     

      // Create a new persistent employee object

      pm.makePersistent(emp);

 

      // Write the new employee to the database. Update the department object.

      tx.commit();

   }

   finally {

      // Close the Persistence Manager

      if (pm != null && !pm.isClosed()) {

         if (pm.currentTransaction().isActive())

            pm.currentTransaction().rollback();

         pm.close();

      }

   }

}

 

                            d.      Implement a method that retrieves the data about all employees in a department. The method uses a query with a parameter, which defines the ID of the department. The query returns a collection, which is then transformed into an array of employee records. Since the method does not involve data modification, you do not need to execute the query in a transaction:

Example

public Employee[] getEmployeesFromDepartment(

   int departmentId)

   throws JDOException {

 

   PersistenceManager pm = null;

   Employee[] result = new Employee[] {};

   try {

      // Prepare the query.

      pm = pmf.getPersistenceManager();

      Query query = pm.newQuery(Employee.class, "department.depId == id");

      query.declareParameters( "int id" );

 

      // Cast the return value of query.execute() to java.util.Collection

      Collection col = (Collection)query.execute(new Integer(departmentId));

 

      // convert the collection to an array. Return the array.

      // The method returns Employee PC objects for simplicity

      // It is recommended to create additional plain Java

      // objects (Data Transfer Objects DTO) as the return

      //objects

      pm.retrieveAll(col);

      pm.makeTransientAll(col);          

      result = (Employee[]) col.toArray(new Employee[] {});

 

      //free the resources

      query.close(col);

   }

   finally {

      // Close the Persistence Manager

      if (pm != null && !pm.isClosed())

            pm.close();

   }

   return (result);

}

 

                            e.      To add the required imports, position the cursor anywhere in the Java editor and open the context menu. Choose Source Organize Imports.

                              f.      Select javax.naming.Context and confirm by choosing Finish. The following import statements are added after the package declaration:

Example

import java.math.BigDecimal;

import java.util.Collection;

 

import javax.jdo.JDOException;

import javax.jdo.PersistenceManager;

import javax.jdo.PersistenceManagerFactory;

import javax.jdo.Query;

import javax.jdo.Transaction;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

 

                            g.      Save and close the file.

 

Result

You have implemented the business logic of the example. The next step is to implement the Web front end.

End of Content Area