Step 2: Adding a Method to the Session Bean

Previous topic
Previous
Next topic
Next

In this step, you'll add a new method to the session bean called listDepartments(). This method will call the default-generated findAll() method on the Dept entity bean.

To add a method to the session bean:

  1. In the UML diagram, create a new method by clicking in the local methods compartment (the middle one) and typing listDepartments() : String.
  2. The next step is to add implementation code to the bean class. In the Navigator, double click hrAppBean.java to open it in the Code Editor.
  3. In the Structure Pane, double click listDepartments() to jump to that method.
  4. Copy and paste the following code in place of the existing stub method:
      public String listDepartments()
      {
        try {
    	Collection col = getDeptLocalHome().findAll();
    	Iterator it = col.iterator();
    	StringBuffer sb = new StringBuffer ("Department Listing ....\n");
    	DeptLocal dept;
    	while(it.hasNext())
    	  {
    		dept = (DeptLocal)it.next();
        sb.append(dept.getDepartment_id() + "....." + 
                  dept.getDepartment_name()+ "....." + 
                  dept.getLocation_id() + ".....\n");
          
    	  }
        
    	return sb.toString();
           }
      catch(NamingException ne)
        {
    	System.out.println(ne.toString());
    	throw new javax.ejb.EJBException(ne);
        }
      catch(FinderException fe)
        {
      System.out.println(fe.toString());
      throw new javax.ejb.EJBException(fe);
         }
      }
    	
  5. Add the following to the import block:
    import javax.ejb.FinderException;
    import java.util.Collection;
    import java.util.Iterator;
    import hr.DeptLocal; 
    
  6. Compile your program to make sure you have no errors. From the Project menu, choose Make hrAppBean.java.